--- mail_ru_auth.module	2010-08-25 18:41:30.000000000 +0100
+++ /var/www/multisite/www/sites/all/modules/mail_ru/mail_ru_auth/mail_ru_auth.module	2010-10-12 12:51:50.000000000 +0100
@@ -1,475 +1,507 @@
-<?php
-// $Id: mail_ru_auth.module,v 1.6 2010/08/25 18:41:30 seaji Exp $
-
-define('MAILRU_DEFAULT_LOGIN', 1);
-define('MAILRU_DEFAULT_NICK', 2);
-
-/**
- * Implementation of hook_perm().
- */
-function mail_ru_auth_perm() {
-  return array('administer mail_ru_auth');
-}
-
-/**
- * Implementation of hook_menu().
- */
-function mail_ru_auth_menu() {
-
-  $items['admin/settings/mail_ru_auth'] = array(
-    'title' => 'Mail.ru authorization settings',
-    'description' => 'Assign API keys, configure login forms and new user defaults.',
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('mail_ru_auth_admin_settings'),
-    'access arguments' => array('administer site configuration'),
-    'file' => 'mail_ru_auth.admin.inc',
-  );
-
-  $items['receiver.html'] = array(
-    'page callback' => 'mail_ru_auth_receiver',
-    'access callback' => TRUE,
-    'type' => MENU_CALLBACK,
-  );
-
-  $items['mail_ru_auth/finalize'] = array(
-    'page callback' => 'mail_ru_auth_finalize',
-    'access callback' => TRUE,
-    'type' => MENU_CALLBACK,
-    'file' => 'mail_ru_auth.finalize.inc',
-  );
-
-  $items['user/%user/edit/mailru'] = array(
-    'title' => 'mail.ru',
-    'page callback' => 'mail_ru_auth_user_page',
-    'page arguments' => array(1),
-    'access callback' => 'user_edit_access',
-    'access arguments' => array(1),
-    'type' => MENU_LOCAL_TASK,
-    'file' => 'mail_ru_auth.pages.inc',
-  );
-  return $items;
-}
-
-function mail_ru_auth_receiver() {
-  $path = drupal_get_path('module', 'mail_ru_auth') . '/_receiver.html';
-  print file_get_contents($path);
-  exit;
-}
-
-/**
- * Implementation of hook_init().
- */
-function mail_ru_auth_init() {
-  drupal_add_css(drupal_get_path('module', 'mail_ru_auth') .'/mail_ru_auth.css');
-  drupal_add_js(drupal_get_path('module', 'mail_ru_auth') .'/mail_ru_auth.js');
-}
-
-/**
- * Implementation of hook_boot().
- */
-function mail_ru_auth_boot() {
-
-  if(!empty($_COOKIE['mrc'])) {
-    $data = array();
-    parse_str(urldecode($_COOKIE['mrc']), $data);
-    if($data['vid']) {
-      $uid = _mail_ru_get_id('uid', $data['vid']);
-    }
-    if($_COOKIE['mail_ru_auth'] == 'logout') {
-      /* drupal_add_js('mailru.connect.logout();', 'inline', 'footer'); */
-    }
-    elseif($uid && $_COOKIE['mail_ru_auth'] == 'login') {
-      drupal_load('module', 'user');
-      setcookie("mail_ru_auth", 'logged', 0, '/');
-      global $user;
-      if($user->uid == 0) {
-        $account = user_load(array('uid' => $uid, 'status' => 1));
-        if($account) {
-          $GLOBALS['conf']['cache'] = false;
-          $user = $account;
-          $user->login = time();
-          db_query("UPDATE {users} SET login = %d WHERE uid = %d", $user->login, $user->uid);
-          $edit = (array) $user;
-          // Regenerate the session ID to prevent against session fixation attacks.
-          include_once './includes/session.inc';
-          sess_regenerate();
-          user_module_invoke('login', $edit, $user);
-          watchdog('user', 'Session opened for %name via mail_ru.', array('%name' => $user->name));
-          // Cache bypass
-          // TODO here needs more robust way
-          include_once './includes/path.inc';
-          include_once './includes/common.inc';
-          // 'user/register' is denied for registered users
-          if ($_GET['q'] == 'user/register') {
-            drupal_goto('user');
-          }
-          else {
-            drupal_goto($_GET['q']);
-          }
-        }
-        else {
-          drupal_set_message(t('Account is blocked. Cannot login.'), 'error');
-        }
-      }
-      elseif ($user->uid != $uid) {
-        drupal_set_message(t('Wrong mail.ru authorization! LogOut!'), 'error');
-      }
-    }
-    elseif($_COOKIE['mail_ru_auth'] == 'login') {
-      include_once './includes/path.inc';
-      include_once './includes/common.inc';
-      if(arg(0) != 'mail_ru_auth') {
-        drupal_goto('mail_ru_auth/finalize');
-      }
-    }
-  }
-}
-
-/**
- * Implementation of hook_user().
- */
-function mail_ru_auth_user($op, &$edit, &$account, $category = NULL) {
-  switch ($op) {
-    case 'login':
-      if (variable_get('mail_ru_auth_avatar', 0) && isset($account->mailru['sync_avatar'])) {
-        // Get Mail.ru ID and info.
-        $muid = _mail_ru_get_id('muid', $account->uid);
-        if ($muid && $state = mail_ru_auth_users_getinfo($muid) && $url = _mail_ru_get_pic($state)) {
-          $array['picture'] =_mail_ru_auth_save_remote_image($url, $account);
-          user_save($account, $array);
-        }
-      }
-      break;
-
-    case 'logout':
-      // Cookie hardening with httponly.
-      // TODO: (andypost) remove when drupal require PHP 5.2.
-      // TODO: (seaji) this have to be implemented in mail_ru_auth_boot(), and in javascript also.
-      /*
-      $params = session_get_cookie_params();
-      if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
-        setcookie('mail_ru_auth', 'logout', 0, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
-      }
-      else {
-        setcookie('mail_ru_auth', 'logout', 0, $params['path'], $params['domain'], $params['secure']);
-      }
-      */
-      setcookie("mail_ru_auth", 'logout', 0, '/');
-      break;
-
-    case 'delete':
-      db_query("DELETE FROM {mail_ru_users} WHERE uid = %d", $account->uid);
-      break;
-  }
-}
-
-
-/**
- * Implementation of hook_form_FORM_ID_alter().
- */
-function mail_ru_auth_form_user_login_alter($form, $form_state) {
-  if (variable_get('mail_ru_auth_alter_login_form', 1)) {
-    _mail_ru_auth_login_form_alter($form, $form_state);
-  }
-}
-
-/**
- * Implementation of hook_form_FORM_ID_alter().
- */
-function mail_ru_auth_form_user_login_block_alter($form, $form_state) {
-  if (variable_get('mail_ru_auth_alter_login_block', 1)) {
-    _mail_ru_auth_login_form_alter($form, $form_state);
-  }
-}
-
-/**
- * Implementation of hook_form_FORM_ID_alter().
- */
-function mail_ru_auth_form_user_register_alter($form, $form_state) {
-  if (variable_get('mail_ru_auth_alter_register_form', 1)) {
-    _mail_ru_auth_login_form_alter($form, $form_state);
-  }
-}
-
-function _mail_ru_auth_login_form_alter(&$form, &$form_state) {
-  $weight = variable_get('mail_ru_auth_button_weight', 100);
-  $form['mail_ru_auth_button'] = array(
-    '#value' => '<div id="mail_ru_auth_login" class="mail_ru_auth_button"></div>',
-    '#weight' => $weight,
-  );
-}
-
-/**
- * Returns a new unique user name.
- *
- * @param $name
- *   Suggested user's name.
- *
- * @return string
- */
-function _mail_ru_auth_check_name($name) {
-  $counter = 0;
-  $original_name = $name;
-  do {
-    $user_exist = db_result(db_query("SELECT 1 FROM {users} WHERE LOWER(name) = LOWER('%s')", $name));
-    if ($user_exist) {
-      $name = $original_name .'_'. $counter++;
-    }
-  } while ($user_exist);
-  return $name;
-}
-
-/**
- * Fetches and saves user's avatar.
- *
- * @param $path_to_img
- *   Remote image path.
- * @param $account
- *   (optional) User account, current user will be used if not passed.
- *
- * @return
- *   Image filepath.
- */
- //TODO try to use file_get_contents()
- //TODO use drupal core API if possible.
-function _mail_ru_auth_save_remote_image($path_to_img, $account = NULL) {
-  if(is_null($account)) {
-    global $user;
-    $account = $user;
-  }
-  $ch = curl_init ($path_to_img);
-  curl_setopt($ch, CURLOPT_HEADER, 0);
-  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
-  curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
-  $rawdata = curl_exec($ch);
-  curl_close($ch);
-
-  $data = @getimagesize($path_to_img);
-  if (isset($data) && is_array($data)) {
-    $extensions = array('1' => 'gif', '2' => 'jpg', '3' => 'png');
-    $extension = array_key_exists($data[2], $extensions) ?  $extensions[$data[2]] : '';
-    $details = array('width'     => $data[0],
-                     'height'    => $data[1],
-                     'extension' => $extension,
-                     'mime_type' => $data['mime']);
-  }
-  include_once './includes/file.inc';
-  $ext = ($details['extension']) ? '.'. $details['extension'] : '';
-  $fullpath = file_directory_path() . '/' . variable_get(user_picture_path, 'pictures') . '/picture-' . $account->uid . $ext;
-
-  if (file_exists($fullpath)){
-    unlink($fullpath);
-  }
-  $fp = fopen($fullpath, 'x');
-  fwrite($fp, $rawdata);
-  fclose($fp);
-
-  return $fullpath;
-}
-
-/**
- * Implementation of API method users.getInfo().
- */
-function mail_ru_auth_users_getinfo($muid) {
-  $mail_ru_app_id = variable_get('mail_ru_auth_app_id', 0);
-  $mail_ru_secret_key = variable_get('mail_ru_auth_secret_key', 0);
-  $mail_ru_private_key = variable_get('mail_ru_auth_private_key', 0);
-  include_once './includes/common.inc';
-
-  $data = array();
-  parse_str(urldecode($_COOKIE['mrc']), $data);
-
-  $path = 'http://www.appsmail.ru/platform/api';
-
-  $method = 'method=users.getInfo';
-  $app_id = 'app_id='. $mail_ru_app_id;
-  $session_key = 'session_key=' . $data['session_key'];
-  $secure = 'secure=1';
-  $uids = 'uids=' . $muid;
-
-  $params = $app_id . $method . $secure . $session_key . $uids;
-  $sid_to_encode = $params . $mail_ru_secret_key;
-  $sig = md5($sid_to_encode);
-
-  $api_uri = sprintf('%s&%s&%s&%s&%s&sig=%s', $method, $app_id, $session_key, $secure, $uids, $sig);
-  $uri = $path . '?' . $api_uri;
-  $api_result = drupal_http_request($uri);
-  $res = json_decode($api_result->data);
-
-  if(is_object($res) && isset($res->error)) {
-    drupal_set_message(t($res->error->error_msg), 'error');
-    if(user_access('administer mail_ru_auth')) {
-      if($res->error->error_code == 104) {
-        drupal_set_message(t('Check your settings !url', array('!url' => l(t('here'), 'admin/settings/mail_ru_auth'))), 'error');
-      }
-    }
-    return FALSE;
-  }
-  elseif(is_array($res)) {
-    $state['link'] = $res[0]->link;
-    $state['muid'] = $muid;
-    $state['nick'] = $res[0]->nick;
-    $state['pic_small'] = $res[0]->pic_small;
-    $state['pic_big'] = $res[0]->pic_big;
-    $state['pic'] = $res[0]->pic;
-
-    $url = parse_url($state['link']);
-    $url['path'] = trim($url['path'], "/");
-    $args = explode("/", $url['path']);
-    $state['host'] = $args[0];
-    $state['login'] = $args[1];
-    if($state['host'] == 'corp') {
-      $state['host'] = 'corp.mail';
-    }
-    $state['email'] = sprintf('%s@%s.ru', $state['login'], $state['host']);
-
-    return $state;
-  }
-}
-
-/**
- * Returns default size avatar from Mail.ru data.
- *
- * @param $state
- *   Service data state.
- *
- * @return
- *   Size preset for avatar.
- */
-function _mail_ru_get_pic($state) {
-  $avatar = variable_get('mail_ru_auth_avatar', 0);
-  return ($avatar && isset($state[$avatar])) ? $state[$avatar] : FALSE;
-}
-
-/**
- * Get and staticaly cache mail.ru IDs and user IDs of Drupal site.
- *
- * @param string $op
- *   The ID you want to get:
- *   - uid: Returns Drupal user ID from Mail.ru ID.
- *   - muid: Returns mail.ru ID from user ID.
- * @param $id
- *   A Drupal uid or Mail.ru ID.
- *
- * @return int
- *
- * @todo proposed API change: function($id, $return_drupal_uid = FALSE)
- */
-function _mail_ru_get_id($op, $id) {
-  static $ids;
-
-  switch ($op) {
-    case 'uid':
-      $muid = $id;
-      if(!isset($ids['uids'][$muid])) {
-        $uid = db_result(db_query('SELECT uid FROM {mail_ru_users} WHERE muid = "%s"', $muid));
-        if($uid) {
-          $ids['uids'][$muid] = $uid;
-          $ids['muids'][$uid] = $muid;
-        }
-        else {
-          $ids['uids'][$muid] = FALSE;
-        }
-      }
-    return $ids['uids'][$id];
-
-    case 'muid':
-      $uid = $id;
-      if(!isset($ids['muids'][$id])) {
-        $muid = db_result(db_query('SELECT muid FROM {mail_ru_users} WHERE uid = %d', $uid));
-        if($muid) {
-          $ids['muids'][$uid] = $muid;
-          $ids['uids'][$muid] = $uid;
-        }
-        else {
-          $ids['muids'][$uid] = FALSE;
-        }
-      }
-    return $ids['muids'][$id];
-  }
-}
-
-
-/**
- * Copy of user_authenticate() with extra features.
- */
-function mail_ru_auth_authenticate($form_values = array()) {
-  global $user;
-
-  if($form_values['name'] && $form_values['pass']) {
-    $account = user_load(array('name' => $form_values['name'], 'pass' => trim($form_values['pass']), 'status' => 1));
-    if ($account && drupal_is_denied('mail', $account->mail)) {
-      form_set_error('name', t('The name %name is registered using a reserved e-mail address and therefore could not be logged in.', array('%name' => $account->name)));
-    }
-    if (!form_get_errors() && !empty($form_values['name']) && !empty($form_values['pass']) && $account) {
-      $user = $account;
-      user_authenticate_finalize($form_values);
-      watchdog('user', 'Session opened for %name via mail_ru.', array('%name' => $user->name));
-      return $user;
-    }
-    else {
-      watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_values['name']));
-    }
-  }
-}
-
-function mail_ru_auth_authenticate_validate($form, &$form_state) {
-  mail_ru_auth_authenticate($form_state['values']);
-}
-
-function mail_ru_auth_name_validate($form, &$form_state) {
-  if (!empty($form_state['values']['name'])) {
-    if (user_is_blocked($form_state['values']['name'])) {
-      // blocked in user administration
-      form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
-    }
-    else if (drupal_is_denied('user', $form_state['values']['name'])) {
-      // denied by access controls
-      form_set_error('name', t('The name %name is a reserved username.', array('%name' => $form_state['values']['name'])));
-    }
-  }
-}
-
-function mail_ru_auth_final_validate($form, &$form_state) {
-  if (user_is_anonymous() && !empty($form_state['values']['name'])) {
-    form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password'))));
-  }
-}
-
-/**
- * Implementation of hook_footer().
- */
-function mail_ru_auth_footer($main = 0) {
-  global $user;
-
-  $mail_ru_app_id = variable_get('mail_ru_auth_app_id', 0);
-  $mail_ru_secret_key = variable_get('mail_ru_auth_secret_key', 0);
-  $mail_ru_private_key = variable_get('mail_ru_auth_private_key', 0);
-
-  if ($mail_ru_app_id && $mail_ru_secret_key && $mail_ru_private_key) {
-    if ($user->uid == 0 || isset($user->mailru['muid'])) {
-      return '<script type="text/javascript" src="http://connect.mail.ru/js/loader.js"></script>'. "
-        <script type=\"text/javascript\">
-          //<![CDATA[
-          $(document).ready(function(){
-            mailru.loader.require('api', function() {
-              // инициализирует внутренние переменные
-              mailru.connect.init(". $mail_ru_app_id .", '". $mail_ru_private_key ."');
-              // регистрируем обработчики событий, которые будут вызываться при логине и логауте
-              mailru.events.listen(mailru.connect.events.login, function(session){
-                  document.cookie = 'mail_ru_auth=login; path=/';
-                  window.location.reload();
-              });
-              mailru.events.listen(mailru.connect.events.logout, function(){
-                  document.cookie = 'mail_ru_auth=logout; path=/';
-                  window.location.reload();
-              });
-              $('<a class=\"mrc__connectButton\">вход@mail.ru</a>').appendTo('.mail_ru_auth_button');
-              mailru.connect.initButton();
-            });
-          });
-          //]]>
-        </script>";
-    }
-  }
-}
+<?php
+// $Id: mail_ru_auth.module,v 1.6 2010/08/25 18:41:30 seaji Exp $
+
+define('MAILRU_DEFAULT_LOGIN', 1);
+define('MAILRU_DEFAULT_NICK', 2);
+
+/**
+ * Implementation of hook_perm().
+ */
+function mail_ru_auth_perm() {
+  return array('administer mail_ru_auth');
+}
+
+/**
+ * Implementation of hook_menu().
+ */
+function mail_ru_auth_menu() {
+
+  $items['admin/settings/mail_ru_auth'] = array(
+    'title' => 'Mail.ru authorization settings',
+    'description' => 'Assign API keys, configure login forms and new user defaults.',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('mail_ru_auth_admin_settings'),
+    'access arguments' => array('administer site configuration'),
+    'file' => 'mail_ru_auth.admin.inc',
+  );
+
+  $items['receiver.html'] = array(
+    'page callback' => 'mail_ru_auth_receiver',
+    'access callback' => TRUE,
+    'type' => MENU_CALLBACK,
+  );
+
+  $items['mail_ru_auth/finalize'] = array(
+    'page callback' => 'mail_ru_auth_finalize',
+    'access callback' => TRUE,
+    'type' => MENU_CALLBACK,
+    'file' => 'mail_ru_auth.finalize.inc',
+  );
+
+  $items['user/%user/edit/mailru'] = array(
+    'title' => 'mail.ru',
+    'page callback' => 'mail_ru_auth_user_page',
+    'page arguments' => array(1),
+    'access callback' => 'user_edit_access',
+    'access arguments' => array(1),
+    'type' => MENU_LOCAL_TASK,
+    'file' => 'mail_ru_auth.pages.inc',
+  );
+  return $items;
+}
+
+function mail_ru_auth_receiver() {
+  $path = drupal_get_path('module', 'mail_ru_auth') . '/_receiver.html';
+  print file_get_contents($path);
+  exit;
+}
+
+/**
+ * Implementation of hook_init().
+ */
+function mail_ru_auth_init() {
+  drupal_add_css(drupal_get_path('module', 'mail_ru_auth') .'/mail_ru_auth.css');
+  drupal_add_js(drupal_get_path('module', 'mail_ru_auth') .'/mail_ru_auth.js');
+}
+
+/**
+ * Implementation of hook_boot().
+ */
+function mail_ru_auth_boot() {
+
+  if(!empty($_COOKIE['mrc'])) {
+    $data = array();
+    parse_str(urldecode($_COOKIE['mrc']), $data);
+    if($data['vid']) {
+      $uid = _mail_ru_get_id('uid', $data['vid']);
+    }
+    if($_COOKIE['mail_ru_auth'] == 'logout') {
+      /* drupal_add_js('mailru.connect.logout();', 'inline', 'footer'); */
+    }
+    elseif($uid && $_COOKIE['mail_ru_auth'] == 'login') {
+      drupal_load('module', 'user');
+      setcookie("mail_ru_auth", 'logged', 0, '/');
+      global $user;
+      if($user->uid == 0) {
+        $account = user_load(array('uid' => $uid, 'status' => 1));
+        if($account) {
+          $GLOBALS['conf']['cache'] = false;
+          $user = $account;
+          $user->login = time();
+          db_query("UPDATE {users} SET login = %d WHERE uid = %d", $user->login, $user->uid);
+          $edit = (array) $user;
+          // Regenerate the session ID to prevent against session fixation attacks.
+          include_once './includes/session.inc';
+          sess_regenerate();
+          user_module_invoke('login', $edit, $user);
+          watchdog('user', 'Session opened for %name via mail_ru.', array('%name' => $user->name));
+          // Cache bypass
+          // TODO here needs more robust way
+          include_once './includes/path.inc';
+          include_once './includes/common.inc';
+          // 'user/register' is denied for registered users
+          if ($_GET['q'] == 'user/register') {
+            drupal_goto('user');
+          }
+          else {
+            drupal_goto($_GET['q']);
+          }
+        }
+        else {
+          drupal_set_message(t('Account is blocked. Cannot login.'), 'error');
+        }
+      }
+      elseif ($user->uid != $uid) {
+        drupal_set_message(t('Wrong mail.ru authorization! LogOut!'), 'error');
+      }
+    }
+    elseif($_COOKIE['mail_ru_auth'] == 'login') {
+      include_once './includes/path.inc';
+      include_once './includes/common.inc';
+      if(arg(0) != 'mail_ru_auth') {
+        drupal_goto('mail_ru_auth/finalize');
+      }
+    }
+  }
+}
+
+/**
+ * Implementation of hook_user().
+ */
+function mail_ru_auth_user($op, &$edit, &$account, $category = NULL) {
+  switch ($op) {
+    case 'login':
+      if (variable_get('mail_ru_auth_avatar', 0) && isset($account->mailru['sync_avatar'])) {
+        // Get Mail.ru ID and info.
+        $muid = _mail_ru_get_id('muid', $account->uid);
+        if ($muid && $state = mail_ru_auth_users_getinfo($muid) && $url = _mail_ru_get_pic($state)) {
+          //Get new avatar
+          $array['picture'] =_mail_ru_auth_save_remote_image($url, $account);
+          if($array['picture']){
+            //remove previous avatar file
+            file_delete($account->picture);
+          }
+          //Save new picture
+          user_save($account, $array);
+        }
+      }
+      break;
+
+    case 'logout':
+      // Cookie hardening with httponly.
+      // TODO: (andypost) remove when drupal require PHP 5.2.
+      // TODO: (seaji) this have to be implemented in mail_ru_auth_boot(), and in javascript also.
+      /*
+      $params = session_get_cookie_params();
+      if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
+        setcookie('mail_ru_auth', 'logout', 0, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
+      }
+      else {
+        setcookie('mail_ru_auth', 'logout', 0, $params['path'], $params['domain'], $params['secure']);
+      }
+      */
+      setcookie("mail_ru_auth", 'logout', 0, '/');
+      break;
+
+    case 'delete':
+      db_query("DELETE FROM {mail_ru_users} WHERE uid = %d", $account->uid);
+      break;
+  }
+}
+
+
+/**
+ * Implementation of hook_form_FORM_ID_alter().
+ */
+function mail_ru_auth_form_user_login_alter($form, $form_state) {
+  if (variable_get('mail_ru_auth_alter_login_form', 1)) {
+    _mail_ru_auth_login_form_alter($form, $form_state);
+  }
+}
+
+/**
+ * Implementation of hook_form_FORM_ID_alter().
+ */
+function mail_ru_auth_form_user_login_block_alter($form, $form_state) {
+  if (variable_get('mail_ru_auth_alter_login_block', 1)) {
+    _mail_ru_auth_login_form_alter($form, $form_state);
+  }
+}
+
+/**
+ * Implementation of hook_form_FORM_ID_alter().
+ */
+function mail_ru_auth_form_user_register_alter($form, $form_state) {
+  if (variable_get('mail_ru_auth_alter_register_form', 1)) {
+    _mail_ru_auth_login_form_alter($form, $form_state);
+  }
+}
+
+function _mail_ru_auth_login_form_alter(&$form, &$form_state) {
+  $weight = variable_get('mail_ru_auth_button_weight', 100);
+  $form['mail_ru_auth_button'] = array(
+    '#value' => '<div id="mail_ru_auth_login" class="mail_ru_auth_button"></div>',
+    '#weight' => $weight,
+  );
+}
+
+/**
+ * Returns a new unique user name.
+ *
+ * @param $name
+ *   Suggested user's name.
+ *
+ * @return string
+ */
+function _mail_ru_auth_check_name($name) {
+  $counter = 0;
+  $original_name = $name;
+  do {
+    $user_exist = db_result(db_query("SELECT 1 FROM {users} WHERE LOWER(name) = LOWER('%s')", $name));
+    if ($user_exist) {
+      $name = $original_name .'_'. $counter++;
+    }
+  } while ($user_exist);
+  return $name;
+}
+
+/**
+ * Fetches and saves user's avatar.
+ *
+ * @param $path_to_img
+ *   Remote image path.
+ * @param $account
+ *   (optional) User account, current user will be used if not passed.
+ *
+ * @return
+ *   Image filepath.
+ */
+ //TODO try to use file_get_contents()
+ //TODO use drupal core API if possible.
+function _mail_ru_auth_save_remote_image($path_to_img, $account = NULL) {
+  if(is_null($account)) {
+    global $user;
+    $account = $user;
+  }
+  $ch = curl_init ($path_to_img);
+  curl_setopt($ch, CURLOPT_HEADER, 0);
+  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+  curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
+  $rawdata = curl_exec($ch);
+  curl_close($ch);
+
+  $data = @getimagesize($path_to_img);
+  if (isset($data) && is_array($data)) {
+    $extensions = array('1' => 'gif', '2' => 'jpg', '3' => 'png');
+    $extension = array_key_exists($data[2], $extensions) ?  $extensions[$data[2]] : '';
+    $details = array('width'     => $data[0],
+                     'height'    => $data[1],
+                     'extension' => $extension,
+                     'mime_type' => $data['mime']);
+  }
+  include_once './includes/file.inc';
+  $ext = ($details['extension']) ? '.'. $details['extension'] : '';
+  
+  //     temp
+  $filename = 'avatar-' . $account->uid.'-'. time().$ext;
+  $fullpath = file_directory_path() . '/' . variable_get(user_picture_path, 'pictures') . '/'.$filename;
+  
+  if (file_exists($fullpath)){
+    unlink($fullpath);
+  }
+  $fp = fopen($fullpath, 'x');
+  fwrite($fp, $rawdata);
+  fclose($fp);
+  
+  // Begin building file object.
+  $file = new stdClass();
+  $file->filename = $filename;
+  $file->filepath = $fullpath;
+  $file->filemime = file_get_mimetype($file->$fullpath);
+  $file->filesize = filesize($file->$fullpath);
+
+  //   
+  $validators = array(
+    'file_validate_is_image' => array(),
+    'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
+    'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
+  );
+
+  // Call the validation functions.
+  $errors = array();
+  foreach ($validators as $function => $args) {
+    array_unshift($args, $file);
+    // Make sure $file is passed around by reference.
+    $args[0] = &$file;
+    $errors = array_merge($errors, call_user_func_array($function, $args));
+  }
+  
+  return $fullpath;
+}
+
+/**
+ * Implementation of API method users.getInfo().
+ */
+function mail_ru_auth_users_getinfo($muid) {
+  $mail_ru_app_id = variable_get('mail_ru_auth_app_id', 0);
+  $mail_ru_secret_key = variable_get('mail_ru_auth_secret_key', 0);
+  $mail_ru_private_key = variable_get('mail_ru_auth_private_key', 0);
+  include_once './includes/common.inc';
+
+  $data = array();
+  parse_str(urldecode($_COOKIE['mrc']), $data);
+
+  $path = 'http://www.appsmail.ru/platform/api';
+
+  $method = 'method=users.getInfo';
+  $app_id = 'app_id='. $mail_ru_app_id;
+  $session_key = 'session_key=' . $data['session_key'];
+  $secure = 'secure=1';
+  $uids = 'uids=' . $muid;
+
+  $params = $app_id . $method . $secure . $session_key . $uids;
+  $sid_to_encode = $params . $mail_ru_secret_key;
+  $sig = md5($sid_to_encode);
+
+  $api_uri = sprintf('%s&%s&%s&%s&%s&sig=%s', $method, $app_id, $session_key, $secure, $uids, $sig);
+  $uri = $path . '?' . $api_uri;
+  $api_result = drupal_http_request($uri);
+  $res = json_decode($api_result->data);
+
+  if(is_object($res) && isset($res->error)) {
+    drupal_set_message(t($res->error->error_msg), 'error');
+    if(user_access('administer mail_ru_auth')) {
+      if($res->error->error_code == 104) {
+        drupal_set_message(t('Check your settings !url', array('!url' => l(t('here'), 'admin/settings/mail_ru_auth'))), 'error');
+      }
+    }
+    return FALSE;
+  }
+  elseif(is_array($res)) {
+    $state['link'] = $res[0]->link;
+    $state['muid'] = $muid;
+    $state['nick'] = $res[0]->nick;
+    $state['pic_small'] = $res[0]->pic_small;
+    $state['pic_big'] = $res[0]->pic_big;
+    $state['pic'] = $res[0]->pic;
+
+    $url = parse_url($state['link']);
+    $url['path'] = trim($url['path'], "/");
+    $args = explode("/", $url['path']);
+    $state['host'] = $args[0];
+    $state['login'] = $args[1];
+    if($state['host'] == 'corp') {
+      $state['host'] = 'corp.mail';
+    }
+    $state['email'] = sprintf('%s@%s.ru', $state['login'], $state['host']);
+
+    return $state;
+  }
+}
+
+/**
+ * Returns default size avatar from Mail.ru data.
+ *
+ * @param $state
+ *   Service data state.
+ *
+ * @return
+ *   Size preset for avatar.
+ */
+function _mail_ru_get_pic($state) {
+  $avatar = variable_get('mail_ru_auth_avatar', 0);
+  return ($avatar && isset($state[$avatar])) ? $state[$avatar] : FALSE;
+}
+
+/**
+ * Get and staticaly cache mail.ru IDs and user IDs of Drupal site.
+ *
+ * @param string $op
+ *   The ID you want to get:
+ *   - uid: Returns Drupal user ID from Mail.ru ID.
+ *   - muid: Returns mail.ru ID from user ID.
+ * @param $id
+ *   A Drupal uid or Mail.ru ID.
+ *
+ * @return int
+ *
+ * @todo proposed API change: function($id, $return_drupal_uid = FALSE)
+ */
+function _mail_ru_get_id($op, $id) {
+  static $ids;
+
+  switch ($op) {
+    case 'uid':
+      $muid = $id;
+      if(!isset($ids['uids'][$muid])) {
+        $uid = db_result(db_query('SELECT uid FROM {mail_ru_users} WHERE muid = "%s"', $muid));
+        if($uid) {
+          $ids['uids'][$muid] = $uid;
+          $ids['muids'][$uid] = $muid;
+        }
+        else {
+          $ids['uids'][$muid] = FALSE;
+        }
+      }
+    return $ids['uids'][$id];
+
+    case 'muid':
+      $uid = $id;
+      if(!isset($ids['muids'][$id])) {
+        $muid = db_result(db_query('SELECT muid FROM {mail_ru_users} WHERE uid = %d', $uid));
+        if($muid) {
+          $ids['muids'][$uid] = $muid;
+          $ids['uids'][$muid] = $uid;
+        }
+        else {
+          $ids['muids'][$uid] = FALSE;
+        }
+      }
+    return $ids['muids'][$id];
+  }
+}
+
+
+/**
+ * Copy of user_authenticate() with extra features.
+ */
+function mail_ru_auth_authenticate($form_values = array()) {
+  global $user;
+
+  if($form_values['name'] && $form_values['pass']) {
+    $account = user_load(array('name' => $form_values['name'], 'pass' => trim($form_values['pass']), 'status' => 1));
+    if ($account && drupal_is_denied('mail', $account->mail)) {
+      form_set_error('name', t('The name %name is registered using a reserved e-mail address and therefore could not be logged in.', array('%name' => $account->name)));
+    }
+    if (!form_get_errors() && !empty($form_values['name']) && !empty($form_values['pass']) && $account) {
+      $user = $account;
+      user_authenticate_finalize($form_values);
+      watchdog('user', 'Session opened for %name via mail_ru.', array('%name' => $user->name));
+      return $user;
+    }
+    else {
+      watchdog('user', 'Login attempt failed for %user.', array('%user' => $form_values['name']));
+    }
+  }
+}
+
+function mail_ru_auth_authenticate_validate($form, &$form_state) {
+  mail_ru_auth_authenticate($form_state['values']);
+}
+
+function mail_ru_auth_name_validate($form, &$form_state) {
+  if (!empty($form_state['values']['name'])) {
+    if (user_is_blocked($form_state['values']['name'])) {
+      // blocked in user administration
+      form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
+    }
+    else if (drupal_is_denied('user', $form_state['values']['name'])) {
+      // denied by access controls
+      form_set_error('name', t('The name %name is a reserved username.', array('%name' => $form_state['values']['name'])));
+    }
+  }
+}
+
+function mail_ru_auth_final_validate($form, &$form_state) {
+  if (user_is_anonymous() && !empty($form_state['values']['name'])) {
+    form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password'))));
+  }
+}
+
+/**
+ * Implementation of hook_footer().
+ */
+function mail_ru_auth_footer($main = 0) {
+  global $user;
+
+  $mail_ru_app_id = variable_get('mail_ru_auth_app_id', 0);
+  $mail_ru_secret_key = variable_get('mail_ru_auth_secret_key', 0);
+  $mail_ru_private_key = variable_get('mail_ru_auth_private_key', 0);
+
+  if ($mail_ru_app_id && $mail_ru_secret_key && $mail_ru_private_key) {
+    if ($user->uid == 0 || isset($user->mailru['muid'])) {
+      return '<script type="text/javascript" src="http://connect.mail.ru/js/loader.js"></script>'. "
+        <script type=\"text/javascript\">
+          //<![CDATA[
+          $(document).ready(function(){
+            mailru.loader.require('api', function() {
+              // инициализирует внутренние переменные
+              mailru.connect.init(". $mail_ru_app_id .", '". $mail_ru_private_key ."');
+              // регистрируем обработчики событий, которые будут вызываться при логине и логауте
+              mailru.events.listen(mailru.connect.events.login, function(session){
+                  document.cookie = 'mail_ru_auth=login; path=/';
+                  window.location.reload();
+              });
+              mailru.events.listen(mailru.connect.events.logout, function(){
+                  document.cookie = 'mail_ru_auth=logout; path=/';
+                  window.location.reload();
+              });
+              $('<a class=\"mrc__connectButton\">вход@mail.ru</a>').appendTo('.mail_ru_auth_button');
+              mailru.connect.initButton();
+            });
+          });
+          //]]>
+        </script>";
+    }
+  }
+}
