Index: yandex_metrics.info
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP
<+>core            = \"7.x\"\ndescription     = \"Allows to install Yandex.Metrics counter on the site pages.\"\nname            = \"Yandex.Metrics Counter\"\npackage         = Yandex.Metrics\nconfigure       = admin/config/system/yandex_metrics\n
===================================================================
--- yandex_metrics.info	(revision e02c79e6df30b80f4de2e987044c3ec99cb3abf1)
+++ yandex_metrics.info	(revision )
@@ -3,3 +3,5 @@
 name            = "Yandex.Metrics Counter"
 package         = Yandex.Metrics
 configure       = admin/config/system/yandex_metrics
+
+
Index: yandex_metrics_reports/yandex_metrics_reports.info
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP
<+>core            = \"7.x\"\ndescription     = \"Allows to authorise application and display reports.\"\nname            = \"Yandex.Metrics Reports\"\n\ndependencies[]  = chart\ndependencies[]  = yandex_metrics\n\npackage         = Yandex.Metrics\n
===================================================================
--- yandex_metrics_reports/yandex_metrics_reports.info	(revision e02c79e6df30b80f4de2e987044c3ec99cb3abf1)
+++ yandex_metrics_reports/yandex_metrics_reports.info	(revision )
@@ -4,5 +4,14 @@
 
 dependencies[]  = chart
 dependencies[]  = yandex_metrics
+dependencies[]  = views
 
+files[] = views/yandex_metrics_reports.views.inc;
+; Views handlers
+files[] = views/handlers/views_handler_field_ym_title.inc
+
 package         = Yandex.Metrics
+
+
+
+
Index: yandex_metrics_reports/views/yandex_metrics_reports.views.inc
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- yandex_metrics_reports/views/yandex_metrics_reports.views.inc	(revision )
+++ yandex_metrics_reports/views/yandex_metrics_reports.views.inc	(revision )
@@ -0,0 +1,154 @@
+<?php
+/**
+ * @file
+ * Provides support for the Views module.
+ */
+
+/**
+ * Implementation hook_views_data()
+ */
+function yandex_metrics_reports_views_data() {
+  $data['yandex_metrics_reports_popular_content']['table']['group'] = t('Yandex.Metrics');
+
+  $data['yandex_metrics_reports_popular_content']['table']['base'] = array(
+    'field'       => 'yid',
+    'title'       => t('The data obtained from Yandex.metrika.') ,
+    'help'        => t('The data obtained from Yandex.metrika.'),
+    'weight'      => -10
+  );
+
+  $data['yandex_metrics_reports_popular_content']['url'] = array(
+    'title'       => t('Popular url'),
+    'help'        => t('The url obtained from Yandex.metrika.'),
+    'field'       => array(
+      'handler'         => 'views_handler_field',
+      'click sortable'  => TRUE, // This is use by the table display plugin.
+    ),
+    'sort'        => array(
+      'handler' => 'views_handler_sort',
+    ),
+    'filter'      => array(
+      'handler' => 'views_handler_filter_string',
+    ),
+    'argument'    => array(
+      'handler' => 'views_handler_argument_string',
+    ),
+  );
+
+  $data['yandex_metrics_reports_popular_content']['page_title'] = array(
+    'title'       => t('Title for url'),
+    'help'        => t('The page title of the url.'),
+    'field'       => array(
+      'handler'         => 'views_handler_field_ym_title',
+      'click sortable'  => TRUE, // This is use by the table display plugin.
+    ),
+    'sort'        => array(
+      'handler' => 'views_handler_sort',
+    ),
+    'filter'      => array(
+      'handler' => 'views_handler_filter_string',
+    ),
+    'argument'    => array(
+      'handler' => 'views_handler_argument_string',
+    ),
+  );
+
+  $data['yandex_metrics_reports_popular_content']['page_views'] = array(
+    'title'       => t('Count of views'),
+    'help'        => t('Page views of this url.'),
+    'field'       => array(
+      'handler'        => 'views_handler_field_numeric',
+      'click sortable' => TRUE,
+    ),
+    'sort'        => array(
+      'handler' => 'views_handler_sort',
+    ),
+    'filter'      => array(
+      'handler' => 'views_handler_filter_numeric'
+    ),
+    'argument'    => array(
+      'handler' => 'views_handler_argument_numeric'
+    ),
+  );
+ return $data;
+}
+
+/**
+ * Implementation hook_views_default_views
+ */
+function yandex_metrics_reports_views_default_views() {
+  $view = new view();
+  $view->name = 'popular_content';
+  $view->description = '';
+  $view->tag = 'Yandex.Metrics';
+  $view->base_table = 'yandex_metrics_reports_popular_content';
+  $view->human_name = 'Popular content';
+  $view->core = 7;
+  $view->api_version = '3.0';
+  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
+
+  /* Display: Master */
+  $handler = $view->new_display('default', 'Master', 'default');
+  $handler->display->display_options['title'] = 'Popular content from Yandex.Metrics';
+  $handler->display->display_options['use_ajax'] = TRUE;
+  $handler->display->display_options['use_more_always'] = FALSE;
+  $handler->display->display_options['access']['type'] = 'none';
+  $handler->display->display_options['cache']['type'] = 'none';
+  $handler->display->display_options['query']['type'] = 'views_query';
+  $handler->display->display_options['exposed_form']['type'] = 'basic';
+  $handler->display->display_options['pager']['type'] = 'some';
+  $handler->display->display_options['pager']['options']['items_per_page'] = '5';
+  $handler->display->display_options['style_plugin'] = 'table';
+  $handler->display->display_options['style_options']['columns'] = array(
+    'url' => 'url',
+    'page_views' => 'page_views',
+    'page_title' => 'page_title',
+  );
+  $handler->display->display_options['style_options']['default'] = '-1';
+  $handler->display->display_options['style_options']['info'] = array(
+    'url' => array(
+      'sortable' => 1,
+      'default_sort_order' => 'asc',
+      'align' => '',
+      'separator' => '',
+      'empty_column' => 0,
+    ),
+    'page_views' => array(
+      'sortable' => 1,
+      'default_sort_order' => 'asc',
+      'align' => '',
+      'separator' => '',
+      'empty_column' => 0,
+    ),
+    'page_title' => array(
+      'sortable' => 1,
+      'default_sort_order' => 'asc',
+      'align' => '',
+      'separator' => '',
+      'empty_column' => 0,
+    ),
+  );
+  /* Field: Yandex.Metrics: Title for url */
+  $handler->display->display_options['fields']['page_title']['id'] = 'page_title';
+  $handler->display->display_options['fields']['page_title']['table'] = 'yandex_metrics_reports_popular_content';
+  $handler->display->display_options['fields']['page_title']['field'] = 'page_title';
+  $handler->display->display_options['fields']['page_title']['link_to_ym_url'] = TRUE;
+  /* Field: Yandex.Metrics: Popular url */
+  $handler->display->display_options['fields']['url']['id'] = 'url';
+  $handler->display->display_options['fields']['url']['table'] = 'yandex_metrics_reports_popular_content';
+  $handler->display->display_options['fields']['url']['field'] = 'url';
+  /* Field: Yandex.Metrics: Count of views */
+  $handler->display->display_options['fields']['page_views']['id'] = 'page_views';
+  $handler->display->display_options['fields']['page_views']['table'] = 'yandex_metrics_reports_popular_content';
+  $handler->display->display_options['fields']['page_views']['field'] = 'page_views';
+  $handler->display->display_options['fields']['page_views']['separator'] = '';
+
+  /* Display: Block */
+  $handler = $view->new_display('block', 'Block', 'block');
+  $handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
+  $handler->display->display_options['block_description'] = 'Popular content(Yandex.Metrics)';
+
+  $views[$view->name] = $view;
+
+  return $views;
+}
\ No newline at end of file
Index: yandex_metrics_reports/yandex_metrics_reports.module
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP
<+><?php\n/**\n * @file\n *   The main code of Yandex.Metrics Reports module.\n */\n\n/**\n * Quantity of popular search phrases.\n */\ndefine('YANDEX_METRICS_SEARCH_PHRASES_QUANTITY', 12);\n\n\n/**\n * Quantity of popular content lines.\n */\ndefine('YANDEX_METRICS_POPULAR_CONTENT_COUNT', 30);\n\n/**\n * Max count of links in Popular Content block.\n */\ndefine('YANDEX_METRICS_POPULAR_CONTENT_BLOCK_LIMIT', 15);\n\n/**\n * Implementation of hook_permission().\n */\n\nfunction yandex_metrics_reports_permission() {\n  return array(\n    'access Yandex.Metrics report' => array(\n      'title' => t('Access Yandex.Metrics report')\n    ),\n  );\n}\n\n/**\n * Implementation of hook_menu().\n */\nfunction yandex_metrics_reports_menu() {\n\n  $items['yandex_metrics/oauth'] = array(\n    'access arguments' => array('administer Yandex.Metrics settings'),\n    'page callback'   => 'yandex_metrics_reports_oauth_callback',\n    'type' => MENU_CALLBACK,\n  );\n  $items['admin/config/system/yandex_metrics/authorization'] = array(\n    'access arguments' => array('administer Yandex.Metrics settings'),\n    'page callback'   => 'drupal_get_form',\n    'page arguments'  => array('yandex_metrics_reports_authorization'),\n    'title'           => 'Authorization',\n    'type' => MENU_LOCAL_TASK,\n    'weight' => 2\n  );\n  $items['admin/config/system/yandex_metrics/reports'] = array(\n    'access arguments' => array('administer Yandex.Metrics settings'),\n    'page callback'   => 'drupal_get_form',\n    'page arguments'  => array('yandex_metrics_reports_reports'),\n    'title'           => 'Reports',\n    'type' => MENU_LOCAL_TASK,\n    'weight' => 3\n  );\n  $items['admin/reports/yandex_metrics_summary'] = array(\n    'access arguments' => array('access Yandex.Metrics report'),\n    'page callback'   => 'yandex_metrics_reports_report',\n    'title'           => 'Yandex.Metrics Summary Report',\n    'type' => MENU_NORMAL_ITEM\n  );\n  $items['admin/reports/yandex_metrics_summary/%'] = array(\n    'access arguments' => array('access Yandex.Metrics report'),\n    'page callback'   => 'yandex_metrics_reports_report',\n    'page arguments' => array(3),\n    'title'           => 'Yandex.Metrics Summary Report',\n    'load arguments' => array(3),\n    'type' => MENU_CALLBACK\n  );\n  $items['admin/yandex_metrics_ajax/%/%/%'] = array(\n    'access arguments' => array('access Yandex.Metrics report'),\n    'page callback'   => 'yandex_metrics_reports_ajax',\n    'page arguments' => array(2, 3, 4),\n    'load arguments' => array(2, 3, 4),\n    'type' => MENU_CALLBACK\n  );\n\n  return $items;\n}\n\n/**\n * Implements hook_block_info().\n */\nfunction yandex_metrics_reports_block_info() {\n  $block['popular_content']['info'] = t('Popular content');\n  return $block;\n}\n\n/**\n * Implements hook_block_configure().\n */\nfunction yandex_metrics_reports_block_configure($delta = '') {\n  if ($delta == 'popular_content') {\n    $options = array(\n      'day' => t('Today'),\n      'yesterday' => t('Yesterday'),\n      'week' => t('Week'),\n      'month' => t('Month')\n    );\n    $form['yandex_metrics_reports_popular_content_date_period'] = array(\n      '#type' => 'select',\n      '#title' => t('Select date period'),\n      '#description' => t('This date period will be used to filter popular content.'),\n      '#options' => $options,\n      '#default_value' => variable_get('yandex_metrics_reports_popular_content_date_period', 'week'),\n    );\n    $form['yandex_metrics_reports_popular_content_links_count'] = array(\n      '#type' => 'select',\n      '#title' => t('Select count of links to show'),\n      '#description' => t('The count of links that shown in the block.'),\n      '#options' => drupal_map_assoc(array(5, 10, 15)),\n      '#default_value' => variable_get('yandex_metrics_reports_popular_content_links_count', 10),\n    );\n    return $form;\n  }\n}\n\n/**\n * Implements hook_block_save().\n */\nfunction yandex_metrics_reports_block_save($delta = '', $edit = array()) {\n  if ($delta == 'popular_content') {\n    variable_set('yandex_metrics_reports_popular_content_links_count', $edit['yandex_metrics_reports_popular_content_links_count']);\n    $previous_date_period = variable_get('yandex_metrics_reports_popular_content_date_period', 'week');\n    $new_date_period = $edit['yandex_metrics_reports_popular_content_date_period'];\n        \n    // Update already saved Popular content data if the date period has been changed.\n    if ($previous_date_period != $new_date_period) {\n      variable_set('yandex_metrics_reports_popular_content_date_period', $new_date_period);\n      yandex_metrics_reports_save_popular_content();\n    }\n  }\n}\n\n/**\n * Implements hook_block_view().\n *\n * Display the most popular pages.\n */\nfunction yandex_metrics_reports_block_view($delta = '') {\n  if (user_access('access content')) {\n    $check_links_count_variable = variable_get('yandex_metrics_reports_popular_content_links_count', 'undefined');\n    $check_date_period_variable = variable_get('yandex_metrics_reports_popular_content_date_period', 'undefined');\n    \n    // We can figure out that block is showing for the first time when config variables aren't defined\n    if ($check_links_count_variable == 'undefined' && $check_date_period_variable == 'undefined') {\n      // If the block is showing for the first time then fetch popular content from Yandex\n      yandex_metrics_reports_save_popular_content();\n      \n      variable_set('yandex_metrics_reports_popular_content_links_count', 10);\n      variable_set('yandex_metrics_reports_popular_content_date_period', 'week');\n    }\n\n    $links = array();\n    $links_count = variable_get('yandex_metrics_reports_popular_content_links_count', 10);\n    //$result = db_query_range(\"SELECT url, page_title FROM {yandex_metrics_popular_content} ORDER BY page_views DESC\", 0, YANDEX_METRICS_POPULAR_CONTENT_BLOCK_LIMIT);\n    $records = db_select('yandex_metrics_reports_popular_content', 'y')\n      ->fields('y', array('url', 'page_title'))\n      ->orderBy('page_views', 'DESC')\n      ->range(0, YANDEX_METRICS_POPULAR_CONTENT_BLOCK_LIMIT)\n      ->execute();\n\n    foreach ($records as $record) {\n      if (count($links) < $links_count) {\n        $links[] = array('title' => $record->page_title, 'href' => $record->url);\n      }\n    }\n\n    $block = array(); \n    if (!empty($links)) {\n      $block['subject'] = t('Popular content');\n      $block['content'] = theme('links__popular_content', array('links' => $links));\n    }\n\n    return $block;\n  }\n}\n\n/**\n * It is quick filter form for report page.\n * @return array\n */\nfunction yandex_metrics_reports_filter_form() {\n  $form = array();\n\n  $current_filter = arg(3) ? arg(3) : 'week';\n\n  $options = array(\n    'day' => t('Today'),\n    'yesterday' => t('Yesterday'),\n    'week' => t('Week'),\n    'month' => t('Month')\n  );\n  $form['filter'] = array(\n    '#type' => 'select',\n    '#title' => t('Quick filter'),\n    '#default_value' => $current_filter,\n    '#options' => $options,\n    '#attributes' => array('onchange' => 'this.form.submit();')\n  );\n  $form['submit'] = array(\n    '#type' => 'submit',\n    '#value' => t('Submit'),\n    '#attributes' => array('style' => 'display:none;')\n  );\n\n  return $form;\n}\n\n/**\n * Implementation of hook_submit for yandex_metrics_reports_time_interval_form form.\n * @param array $form\n * @param array $form_state\n */\nfunction yandex_metrics_reports_filter_form_submit($form, &$form_state) {\n\n  $filter = $form_state['values']['filter'];\n  if (!empty($filter)) {\n    drupal_goto('admin/reports/yandex_metrics_summary/' . $filter);\n  }\n}\n\n/**\n * Converts filter value to date range array:\n * array(\n *   'start_date' => 'YYYYMMDD',\n *   'end_date' => 'YYYYMMDD',\n *   'group' => 'week' // It is optional element.\n * );\n * \n * @param string $filter - (day, yesterday, week, month)\n * @return array\n */\nfunction _yandex_metrics_reports_filter_to_date_range($filter) {\n\n  switch ($filter) {\n    case 'day':\n      return array(\n        'start_date' => date('Ymd'),\n        'end_date' => date('Ymd')\n      );\n    case 'yesterday':\n      return array(\n        'start_date' => date('Ymd', time() - 60*60*24),\n        'end_date' => date('Ymd', time() - 60*60*24)\n      );\n    case 'week':\n    default:\n      return array(\n        'start_date' => date('Ymd', time() - 60*60*24*6),\n        'end_date' => date('Ymd')\n      );\n    case 'month':\n      return array(\n        'start_date' => date('Ymd', time() - 60*60*24*31),\n        'end_date' => date('Ymd'),\n        'group' => 'week'\n      );\n  }\n}\n\n/**\n * Menu callback; displays a Summary page containing reports and charts.\n */\nfunction yandex_metrics_reports_report($filter = 'week') {\n\n  $counter_id = yandex_metrics_reports_get_counter_for_current_site();\n\n  if (empty($counter_id)) {\n    drupal_set_message(\n      t('Please create Yandex.Metrics counter for the site first. See more details !link.', array('!link' => l(t('here'), 'admin/config/system/yandex_metrics'))),\n        'error'\n    );\n    return '';\n  }\n  \n  $counter_code = variable_get('yandex_metrics_counter_code', '');\n  if (empty($counter_code)) {\n    drupal_set_message(\n      t('Perhaps you have not yet placed Yandex.Metrics counter code on the site. You can do this !link.', array('!link' => l(t('here'), 'admin/config/system/yandex_metrics'))), \n      'notice'\n    );\n  }\n  \n  $authorisation_token = variable_get('yandex_metrics_reports_auth_token', '');\n  if (empty($authorisation_token)) {\n    drupal_set_message(\n      t('Please make sure that your application is authorized !link.', array('!link' => l(t('here'), 'admin/config/system/yandex_metrics/authorization'))), \n      'error'\n    );\n    return '';\n  }\n  \n  drupal_add_css(drupal_get_path('module', 'yandex_metrics_reports') . '/css/yandex_metrics_reports.css');\n  \n  $output = '';\n  \n  $output .= drupal_render(drupal_get_form('yandex_metrics_reports_filter_form'));\n  \n  $reports = yandex_metrics_reports_get_active_list();\n\n  $use_ajax = variable_get('yandex_metrics_reports_use_ajax', FALSE);\n  if ($use_ajax) {\n    $js_settings = array(\n      'modulePath' => drupal_get_path('module', 'yandex_metrics_reports'),\n      'cleanUrls' => variable_get('clean_url', 0),\n      'reportList' => array_keys($reports)\n    );\n\n    drupal_add_js(array('yandex_metrics_reports' => $js_settings), 'setting');\n    drupal_add_js(drupal_get_path('module', 'yandex_metrics_reports') . '/js/yandex_metrics_reports.js');\n    $output .= '<input type=\"hidden\" id=\"yandex_metrics_reports_counter_id\" value=\"' . $counter_id . '\" />';\n    $output .= '<input type=\"hidden\" id=\"yandex_metrics_reports_filter\" value=\"' . $filter . '\" />';\n\n    foreach ($reports as $report_name => $report_data) {\n      $output .= '<div class=\"yandex_metrics_reports-report\" id=\"yandex_metrics_reports_' . $report_name . '\"></div>';\n    }\n  }\n  else {\n    foreach ($reports as $report_name => $report_data) {\n      $output .= '<div class=\"yandex_metrics_reports-report\">' . call_user_func($report_data['callback'], $counter_id, $filter) . '</div>';\n    }\n  }\n  \n  return $output;\n}\n\n/**\n * The function generates content of search phrases table ordered by popularity.\n * @param string $counter_id\n * @param string $filter\n */\nfunction _yandex_metrics_reports_search_phrases($counter_id, $filter) {\n  $output = '';\n\n  $date_range = _yandex_metrics_reports_filter_to_date_range($filter);\n  \n  $parameters = array(\n    'id' => $counter_id,\n    'date1' => $date_range['start_date'], \n    'date2' => $date_range['end_date']\n  );\n  \n  $report_phrases = yandex_metrics_reports_retreive_data('/stat/sources/phrases', $parameters);\n  $phrases = json_decode($report_phrases->data);\n  \n  if (empty($phrases->data)) {\n    return t('There is no information about search phrases for the selected date range.');\n  }\n  \n  $phrases_totals_visits = $phrases->totals->visits;\n  \n  $header = array(t('Visits (%)'), t('Phrase'));\n  \n  $data = array();\n \n  $i = 1;\n  foreach ($phrases->data as $value) {\n    if ($i > YANDEX_METRICS_SEARCH_PHRASES_QUANTITY) {\n      break;\n    }\n    $percentage = round(100 * $value->visits / $phrases_totals_visits, 2);\n    $data[] = array($percentage, $value->phrase);\n    $i++;\n  }\n\n  return theme('table', array('header' => $header, 'rows' => $data, 'caption' => t(\"Popular Search Phrases\")));\n}\n\n/**\n * The function generates pie chart with traffic sources summary.\n * @param string $counter_id\n * @param string $filter\n */\nfunction _yandex_metrics_reports_sources_chart($counter_id, $filter) {\n\n  $output = '';\n\n  $date_range = _yandex_metrics_reports_filter_to_date_range($filter);\n  \n  $parameters = array(\n    'id' => $counter_id,\n    'date1' => $date_range['start_date'], \n    'date2' => $date_range['end_date']\n  );\n  \n  $results = yandex_metrics_reports_retreive_data('/stat/sources/summary', $parameters);\n  $summary = json_decode($results->data);\n  if (empty($summary->data)) {\n    return t('There is no information about traffic sources for the selected date range.');\n  }\n   \n  $chart = array(\n    '#chart_id' => 'chart_sources',\n    '#title' => chart_title(t('Traffic Sources'), '000000', 15),\n    '#type' => CHART_TYPE_PIE,\n    '#size' => chart_size(500, 200),\n    '#adjust_resolution' => TRUE,\n  );\n  \n  $sum = $summary->totals->visits;\n    \n  $i = 1;\n  foreach ($summary->data as $value) {\n    $chart['#data'][] = !empty($value->visits) ? $value->visits : 0;\n    $chart['#labels'][] = $i; \n    $chart['#legends'][] = $i . '. ' . $value->name . ' (' . round($value->visits * 100 / $sum) . '%' . ')';\n    $chart['#data_colors'][] = chart_unique_color('sources_' . $i, 'yandex_metrics_reports');\n    $i++;\n  }\n\n  return theme('chart', array('chart' => $chart));\n}\n\n/**\n * The function generates bar chart with information about page views, visitors and new visitors.\n * @param string $counter_id\n * @param string $filter\n */\nfunction _yandex_metrics_reports_visits_chart($counter_id, $filter) {\n  $output = '';\n\n  $date_range = _yandex_metrics_reports_filter_to_date_range($filter);\n  \n  $parameters = array(\n    'id' => $counter_id,\n    'date1' => $date_range['start_date'], \n    'date2' => $date_range['end_date']\n  );\n  \n  if (isset($date_range['group'])) {\n    $parameters['group'] = $date_range['group'];\n  }\n  \n  $results = yandex_metrics_reports_retreive_data('/stat/traffic/summary', $parameters);\n  $visits = json_decode($results->data);\n  if (empty($visits->data)) {\n    return t('There is no information about page views and visitors for the selected date range.');\n  }\n  \n  $dates = array();\n  $page_views = array();\n  $visitors = array();\n  $new_visitors = array();\n\n  foreach ($visits->data as $value) {\n    $dates[] = $value->date;\n    $page_views[] = !empty($value->page_views) ? $value->page_views : 0;\n    $visitors[] = !empty($value->visitors) ? $value->visitors : 0;\n    $new_visitors[] = !empty($value->new_visitors) ? $value->new_visitors : 0;\n  }\n  \n  $dates = array_reverse($dates);\n  $page_views = array_reverse($page_views);\n  $visitors = array_reverse($visitors);\n  $new_visitors = array_reverse($new_visitors);\n  \n  $chart = array(\n    '#chart_id' => 'chart_visits',\n    '#title' => chart_title(t('Page Views, Visitors, New Visitors'), '000000', 15),\n    '#type' => CHART_TYPE_BAR_V_GROUPED,\n    '#size' => chart_size(500, 250),\n    '#bar_size' => chart_bar_size(17, 3), \n    '#adjust_resolution' => TRUE,\n    '#legend_position' => CHART_LEGEND_BOTTOM,\n  );\n    \n  $chart['#data']['views'] = $page_views;\n  $chart['#data']['visitors'] = $visitors;\n  $chart['#data']['new_visitors'] = $new_visitors;\n  \n  $max = 0;\n  foreach ($chart['#data'] as $data) {\n    $max_new = max($data);\n    if ($max_new > $max) {\n      $max = $max_new;\n    }\n  }\n  \n  $chart['#data_colors']['views'] = '0000FF'; // Blue.\n  $chart['#data_colors']['visitors'] = '008000'; // Green.\n  $chart['#data_colors']['new_visitors'] = 'FF0000'; // Red.\n  \n  $chart['#legends']['views'] = t('Page Views');\n  $chart['#legends']['visitors'] = t('Visitors');\n  $chart['#legends']['new_visitors'] = t('New Visitors');\n  \n  $chart['#mixed_axis_labels'][CHART_AXIS_Y_LEFT][0][] = chart_mixed_axis_range_label(0, $max);\n\n  foreach ($dates as $date) {\n    $timestamp = strtotime($date);\n\n    $chart['#mixed_axis_labels'][CHART_AXIS_X_BOTTOM][1][] = chart_mixed_axis_label(date('d.m.y', $timestamp));\n  }\n\n  return theme('chart', array('chart' => $chart));\n}\n\n/**\n * The function generates the table of popular content.\n * @param string $counter_id\n * @param string $filter\n */\nfunction _yandex_metrics_reports_popular_content($counter_id, $filter) {\n  $output = '';\n\n  $date_range = _yandex_metrics_reports_filter_to_date_range($filter);\n  \n  $parameters = array(\n    'id' => $counter_id,\n    'date1' => $date_range['start_date'], \n    'date2' => $date_range['end_date']\n  );\n  \n  $report_content = yandex_metrics_reports_retreive_data('/stat/content/popular', $parameters);\n  $content = json_decode($report_content->data);\n  \n  if (empty($content->data)) {\n    return t('There is no information about popular content for the selected date range.');\n  }\n  \n  $header = array(t('URL'), t('Page Views'));\n  \n  $data = array();\n \n  $i = 1;\n  foreach ($content->data as $value) {\n    if ($i > YANDEX_METRICS_POPULAR_CONTENT_COUNT) {\n      break;\n    }\n    $data[] = array(l($value->url, $value->url, array('attributes' => array('target' => '_blank'))), $value->page_views);\n    $i++;\n  }\n\n  return theme('table', array('header' => $header, 'rows' => $data, 'caption' => t(\"Popular Content\")));\n}\n\n/**\n * Menu callback; the application authorization form.\n */\nfunction yandex_metrics_reports_authorization() {\n\n  $authorisation_token = variable_get('yandex_metrics_reports_auth_token', '');\n  if (!empty($authorisation_token)) {\n    $authorization_status_text = '<span style=\"color:green;\">' . t('The application is already authorized.') . '</span>';\n  } \n  else {\n    $authorization_status_text = '<span style=\"color:red;\">' . t('The application is not authorized yet.') . '</span>';\n  }\n  $form['yandex_metrics_reports_auth_text'] = array(\n      '#markup' => $authorization_status_text,\n      '#type' => 'item',\n  );\n\n  $form['yandex_metrics_reports_client_id'] = array(\n    '#default_value' => variable_get('yandex_metrics_reports_client_id', ''),\n    '#title' => t('Client ID'),\n    '#type' => 'textfield',\n    '#required' => TRUE,\n    '#description' => t('Enter your application client ID in this field.')\n    );\n\n  $form['yandex_metrics_reports_client_secret'] = array(\n    '#default_value' => variable_get('yandex_metrics_reports_client_secret', ''),\n    '#title' => t('Client Secret'),\n    '#type' => 'textfield',\n    '#description' => t('Enter your application secret in this field.')\n  );\n\n  $form['authorize'] = array(\n    '#type' => 'submit',\n    '#value' => !empty($authorisation_token) ? t('Re-Authorize Application') : t('Authorize Application'),\n  );\n\n  return $form;\n}\n\n/**\n * Implementation of hook_submit for yandex_metrics_reports_authorization form.\n * @param array $form\n * @param array $form_state\n */\nfunction yandex_metrics_reports_authorization_submit($form, &$form_state) {\n  variable_set('yandex_metrics_reports_client_id', $form_state['values']['yandex_metrics_reports_client_id']);\n  variable_set('yandex_metrics_reports_client_secret', $form_state['values']['yandex_metrics_reports_client_secret']);\n\n  $client_id = variable_get('yandex_metrics_reports_client_id', '');\n\n  if (empty($client_id)) {\n    drupal_set_message(t(\"Please set Client ID first.\"));\n    return;\n  }\n\n  $request_url = \"https://oauth.yandex.ru/authorize?response_type=code&client_id=\" . $client_id;\n\n  drupal_goto($request_url);\n}\n\n/**\n * Menu callback. Perform auth token request by code parameter from url.\n * More information at (Russian):\n * http://api.yandex.ru/oauth/doc/dg/reference/obtain-access-token.xml\n */\nfunction yandex_metrics_reports_oauth_callback() {\n\n  if (empty($_GET['code'])) {\n    watchdog('yandex_metrics_reports', 'The \"code\" parameter is empty.', array(), WATCHDOG_WARNING);\n    drupal_set_message(t('An error has occurred. Please try again.'), 'error');\n    drupal_goto('admin/config/system/yandex_metrics/authorization');\n  }\n\n  $client_secret = variable_get('yandex_metrics_reports_client_secret', '');\n  $client_id = variable_get('yandex_metrics_reports_client_id', '');\n\n  $data = 'grant_type=authorization_code&client_id=' . $client_id . '&code=' . $_GET['code'];\n\n  if (!empty($client_secret)) {\n    $data .= '&client_secret=' . $client_secret;\n  }\n\n  $result = drupal_http_request(\"https://oauth.yandex.ru/token\", array('method' => 'POST', 'data' => $data));\n\n  if (isset($result->error)) {\n    watchdog('yandex_metrics_reports', 'Token request seems to be fail, due to \"%error\".', array('%error' => $result->code . ' ' . $result->error), WATCHDOG_WARNING);\n    drupal_set_message(t('An error has occurred. Please try again.'), 'error');\n    drupal_goto('admin/config/system/yandex_metrics/authorization');\n  }\n\n  $response = json_decode($result->data);\n\n  variable_set('yandex_metrics_reports_auth_token', $response->access_token);\n\n  watchdog('yandex_metrics_reports', 'Token request is successful.');\n  drupal_set_message(t('Congratulations! Your application has been authorized by Yandex.Metrics service.'));\n  drupal_goto('admin/config/system/yandex_metrics/authorization');\n}\n\n/**\n * This is the helper function to retreive analytic information from Yandex.Metrics.\n * @param string $service_uri - short uri of service\n * @param array $parameters - associative array with parameters\n * @param string $result_type - result type (json, xml)\n */\nfunction yandex_metrics_reports_retreive_data($service_uri, $parameters = array(), $result_type = 'json') {\n\n  $parameters['oauth_token'] = variable_get('yandex_metrics_reports_auth_token', '');\n\n  $query_parts = array();\n  foreach ($parameters as $key => $value) {\n    $query_parts[] = $key . '=' . $value;\n  }\n\n  $parameter_string = implode('&', $query_parts);\n\n  $full_service_url = \"http://api-metrika.yandex.ru\" . $service_uri . \".\" . $result_type . \"?\" . $parameter_string;\n\n  return drupal_http_request($full_service_url);\n}\n\n/**\n * Gets counter ID for the current site from Yandex.Metrics.\n */\nfunction yandex_metrics_reports_get_counter_for_current_site() {\n\n  $counter_id = variable_get('yandex_metrics_reports_counter_id', '');\n  if (!empty($counter_id)) {\n    return $counter_id;\n  }\n\n  $result = yandex_metrics_reports_retreive_data('/counters', array('field' => 'mirrors'));\n\n  if (isset($result->error)) {\n    watchdog('yandex_metrics_reports', 'Counters request seems to be fail, due to \"%error\".', array('%error' => $result->code . ' ' . $result->error), WATCHDOG_WARNING);\n    return;\n  }\n\n  $counters = json_decode($result->data);\n\n  $current_host = $_SERVER['HTTP_HOST'];\n\n  // Try to decode national domain.\n  $decoded_domain = _yandex_metrics_reports_idna_decode($current_host);\n\n  if ($decoded_domain != FALSE && $decoded_domain != $current_host) {\n      $current_host = $decoded_domain;\n  }\n\n  foreach ($counters->counters as $key => $counter) {\n    if ($counter->site == $current_host) {\n      variable_set('yandex_metrics_reports_counter_id', $counter->id);\n      return $counter->id;\n    } \n    \n    // If current host is equal of any site mirror.\n    if (isset($counter->mirrors) && in_array($current_host, $counter->mirrors)) {\n      variable_set('yandex_metrics_reports_counter_id', $counter->id);\n      return $counter->id;\n    }\n  }\n\n  return FALSE;\n}\n\n/**\n * Fetch Popuplar content from Yandex.metrika and save it to the database.\n * @param bool $cron - Indicates that we run function in cron or another place.\n */\nfunction yandex_metrics_reports_save_popular_content($cron = FALSE) {\n  $counter_code = variable_get('yandex_metrics_counter_code', '');\n  if (empty($counter_code) && !$cron) {\n    drupal_set_message(\n      t('Perhaps you have not yet placed Yandex.Metrics counter code on the site. You can do this !link.', array('!link' => l(t('here'), 'admin/settings/yandex_metrics'))),\n      'notice'\n    );\n    return;\n  }\n\n  $counter_id = yandex_metrics_reports_get_counter_for_current_site();\n  if (empty($counter_id)) {\n    if ($cron) {\n      watchdog('yandex_metrics_reports', 'Cron: counter ID is not set.', array(), WATCHDOG_WARNING);\n    }\n    else {\n      drupal_set_message(\n        t('Please create Yandex.Metrics counter for the site first. See more details !link.', array('!link' => l(t('here'), 'admin/config/system/yandex_metrics'))),\n        'error'\n      );\n    }\n    return;\n  }\n  \n  $authorisation_token = variable_get('yandex_metrics_reports_auth_token', '');\n  if (empty($authorisation_token)) {\n    if ($cron) {\n      watchdog('yandex_metrics_reports', 'Cron: application is not authorised.', array(), WATCHDOG_WARNING);\n    }\n    else {\n      drupal_set_message(\n        t('Please make sure that your application is authorized !link.', array('!link' => l(t('here'), 'admin/settings/yandex_metrics/authorization'))),\n        'error'\n      );\n    }\n\n    return;\n  }  \n \n  $filter = variable_get('yandex_metrics_reports_popular_content_date_period', 'week');\n  $date_range = _yandex_metrics_reports_filter_to_date_range($filter);\n  \n  $parameters = array(\n    'id' => $counter_id,\n    'date1' => $date_range['start_date'], \n    'date2' => $date_range['end_date']\n  );\n  \n  // Fetch popular content urls.\n  $report_content = yandex_metrics_reports_retreive_data('/stat/content/popular', $parameters);\n  $content = json_decode($report_content->data);\n\n  if (!empty($content->data)) {\n    // Remove outdated data.\n    db_truncate('yandex_metrics_reports_popular_content')->execute();\n    \n    $counter = 1;\n    foreach ($content->data as $value) {\n      // Obtain page title for current url.\n      $page_title = '';\n      $parsed_url = parse_url($value->url);\n      \n      // Get rid of base_path(typically \"/\" symbol) from the url. \n      $pos = strpos($parsed_url['path'], base_path());\n      if ($pos !== FALSE) {\n        // Get path alias in order to obtain page title.\n        $path = substr_replace($parsed_url['path'], '', $pos, strlen(base_path()));\n\n        if ($path == '') {\n          // If path alias is empty than it's the Front page.\n          $page_title = variable_get('site_name', t('Front page'));\n        }\n        else {\n          // Convert path alias to internal Drupal path.\n          $internal_path = drupal_get_normal_path($path);\n          \n          if (strpos($internal_path, 'node/') === 0) {\n            $temp = explode('/', $internal_path);\n            $nid  = $temp[1];\n            $node = node_load($nid);\n            $page_title = empty($node->page_title) ? $node->title : $node->page_title;\n          }              \n          elseif (strpos($internal_path, 'taxonomy/term') === 0) {\n            $temp = explode('/', $internal_path);\n            $tid  = $temp[2];\n            $term = taxonomy_term_load($tid);\n            $page_title = $term->name;\n          }\n          else {\n            $page_title = $path;\n          }\n        }\n      }\n\n      db_insert('yandex_metrics_reports_popular_content')\n        ->fields(array(\n          'url' => $value->url,\n          'page_title' => $page_title,\n          'page_views' => $value->page_views,\n        ))\n        ->execute();\n\n      if ($counter++ >= YANDEX_METRICS_POPULAR_CONTENT_BLOCK_LIMIT) {\n        break;\n      }\n    }\n\n    watchdog('yandex_metrics_reports', 'Popular content for %filter has been saved.', array('%filter' => $filter), WATCHDOG_NOTICE);\n  }\n}\n\n/**\n * Implementation of hook_cron().\n */\nfunction yandex_metrics_reports_cron() {\n  // Skip cron execution if Popular Content block is not enabled.\n  if (!_yandex_metrics_reports_is_popular_content_enabled()) {\n    return;\n  }\n\n  yandex_metrics_reports_save_popular_content(TRUE);\n}\n\n/**\n * Menu callback; outputs content of one of the 4 reports.\n * It is intended for AJAX calls.\n * @param $counter_id\n * @param $filter\n * @param $type\n * @return void\n */\nfunction yandex_metrics_reports_ajax($counter_id, $filter, $type) {\n  $output = '';\n  $reports = yandex_metrics_reports_get_list();\n  if (isset($reports[$type]) && isset($reports[$type]['callback']) && function_exists($reports[$type]['callback'])) {\n    $output = call_user_func($reports[$type]['callback'], $counter_id, $filter);\n  }\n\n  print $output;\n  die;\n}\n\n/**\n * Menu callback. Reports setting form.\n * @return array\n */\nfunction yandex_metrics_reports_reports() {\n\n  $form = array();\n\n  $form['yandex_metrics_reports_use_ajax'] = array(\n    '#type' => 'checkbox',\n    '#title' => t('Load reports via AJAX'),\n    '#default_value' => variable_get('yandex_metrics_reports_use_ajax', TRUE)\n  );\n\n  $form['reports'] = array(\n      '#type' => 'fieldset',\n      '#title' => t('Reports visibility settings'),\n      '#description' => t('Choose reports to display on Yandex.Metrics Summary Report page.')\n  );\n\n  $reports = yandex_metrics_reports_get_list();\n\n  foreach ($reports as $report_name => $report_data) {\n    $form['reports']['yandex_metrics_reports_' . $report_name . '_visible'] = array(\n    '#type' => 'checkbox',\n      '#title' => $report_data['title'],\n      '#default_value' => variable_get('yandex_metrics_reports_' . $report_name . '_visible', TRUE),\n  );\n  }\n\n  return system_settings_form($form);\n}\n/**\n * The function generates pie chart with geographical information on visitors.\n * @param string $counter_id\n * @param string $filter\n */\nfunction _yandex_metrics_reports_geo_chart($counter_id, $filter) {\n\n  $output = '';\n\n  $date_range = _yandex_metrics_reports_filter_to_date_range($filter);\n\n  $parameters = array(\n    'id' => $counter_id,\n    'date1' => $date_range['start_date'],\n    'date2' => $date_range['end_date']\n  );\n\n  $results = yandex_metrics_reports_retreive_data('/stat/geo', $parameters);\n  $geo = json_decode($results->data);\n  if (empty($geo->data)) {\n    return t('There is no information about geography of visits for the selected date range.');\n  }\n\n  $chart = array(\n    '#chart_id' => 'chart_geo',\n    '#title' => chart_title(t('Geography of Visits'), '000000', 15),\n    '#type' => CHART_TYPE_PIE,\n    '#size' => chart_size(500, 230),\n    '#adjust_resolution' => TRUE,\n  );\n\n  $total_visits = $geo->totals->visits;\n\n  // Exclude unknown visits.\n  foreach ($geo->data as $key => $value) {\n    if ($value->name == \"Не определено\") {\n      $total_visits -= $value->visits;\n      unset($geo->data[$key]);\n      break;\n    }\n  }\n\n  $i = 1;\n  $sum_visits = 0;\n  foreach ($geo->data as $value) {\n\n    $visits = !empty($value->visits) ? $value->visits : 0;\n\n    if ($i > 10) {\n        $others_visits = $total_visits - $sum_visits;\n\n        $chart['#data'][] = $others_visits;\n        $chart['#labels'][] = t('Others') . ' (' . round($others_visits * 100 / $total_visits, 1) . '%' . ')';\n\n        $chart['#data_colors'][] = chart_unique_color('geo_' . $i, 'yandex_metrics_reports');\n\n        break;\n    }\n\n    $sum_visits += $visits;\n\n    $chart['#data'][] = $visits;\n    $chart['#labels'][] = $value->name . ' (' . round($visits * 100 / $total_visits, 1) . '%' . ')';\n\n    $chart['#data_colors'][] = chart_unique_color('geo_' . $i, 'yandex_metrics_reports');\n    $i++;\n  }\n\n  return theme('chart', array('chart' => $chart));\n}\n\n/**\n * Implementation of hook_chart_color_schemes of chart module.\n * @return void\n */\nfunction yandex_metrics_reports_chart_color_schemes() {\n  return array(\n    'yandex_metrics_reports' => array(\n      'ff3030',\n      'ff8800',\n      '00b6f7',\n      '95d900',\n      'ffea00',\n      'bb7bf1',\n      '0080ff',\n      'ff8888',\n      '87888e',\n      '457f51',\n      'b5b6be'\n    ),\n  );\n}\n\n/**\n * Returns path of idna_convert class.\n * @return bool|string\n */\nfunction _yandex_metrics_reports_get_idna_library_path() {\n  $file = 'idna_convert.class.php';\n  $library = 'idna_convert';\n  if (module_exists('libraries') && file_exists(libraries_get_path($library) . \"/$file\")) {\n    return libraries_get_path($library) . \"/$file\";\n  }\n  else {\n    $paths = array(\n      drupal_get_path('module', 'yandex_metrics'),\n      drupal_get_path('module', 'yandex_metrics') . \"/libraries\",\n      drupal_get_path('module', 'yandex_metrics_reports'),\n      drupal_get_path('module', 'yandex_metrics_reports') . \"/libraries\",\n      'profiles/' . variable_get('install_profile', 'default') . '/libraries',\n      'profiles/' . variable_get('install_profile', 'default') . '/libraries/' . $library,\n      'sites/all/libraries',\n      'sites/all/libraries/' . $library,\n    );\n    foreach ($paths as $library_path) {\n      $path = $library_path . \"/$file\";\n      if (file_exists($path)) {\n        return $path;\n      }\n    }\n  }\n  return FALSE;\n}\n\n/**\n * Decode ASCII 'xn--*' domain name to Unicode national domain name if it is possible.\n * Used idna_convert class created by Matthias Sommerfeld <mso@phlylabs.de> and licensed under LGPL.\n * @see http://www.phpclasses.org/package/1509-PHP-Convert-from-and-to-IDNA-Punycode-domain-names.html\n * @param $domain\n * @return string\n */\nfunction _yandex_metrics_reports_idna_decode($domain) {\n  $idna_library_path = _yandex_metrics_reports_get_idna_library_path();\n\n  // Library has not been found.\n  if ($idna_library_path == FALSE) {\n    return $domain;\n  }\n\n  require_once($idna_library_path);\n\n  $IDN = new idna_convert();\n\n  return $IDN->decode($domain);\n}\n\n/**\n * Implementation of hook_help.\n */\nfunction yandex_metrics_reports_help($path, $arg) {\n  switch ($path) {\n    case 'admin/help#yandex_metrics_reports':\n      $output = '';\n      $output .= '<h3>' . t('About the module') . '</h3>';\n      $output .= '<p>' . t('The <a href=\"@yandex_metrika\" target=\"_blank\">Yandex.Metrics</a> service is European alternative of Google Analytics. This is a free tool that helps you to increase the conversion rate of your site.', array('@yandex_metrika' => 'http://metrika.yandex.ru/')) . '</p>';\n      $output .= '<p>' . t('The Yandex.Metrics Reports module allows to authorize the site on Yandex and view basic reports by key effectiveness indicators.') . '</p>';\n      $output .= '<h3>' . t('Usage') . '</h3>';\n      $output .= '<dl>';\n      $output .= '<dt>' . t('Authorizing site') . '</dt>';\n      $output .= '<dd>' . t('To get access to the <a href=\"@reports-url\">reports</a> register Yandex application at !app_register_link. Then enter your application Client ID and Client Secret in the appropriate fields on the <a href=\"@authorization-page\">Authorization</a> page. The full list of your Yandex applications is located !app_list_link.', array('!app_register_link' => l('https://oauth.yandex.ru/client/new', 'https://oauth.yandex.ru/client/new', array('attributes' => array('target' => '_blank'))), '!app_list_link' => l(t('here'), 'https://oauth.yandex.ru/client/my', array('attributes' => array('target' => '_blank'))), '@reports-url' => url('admin/reports/yandex_metrics_summary'), '@authorization-page' => url('admin/config/system/yandex_metrics/authorization'))) . '</dd>';\n      $output .= '<dt>' . t('Configuring reports') . '</dt>';\n      $output .= '<dd>' . t('You can choose necessary reports <a href=\"@report-setting-page\">here</a> to display on <a href=\"@summary-report-page\">Yandex.Metrics Summary Report</a> page. Also, we recommend you to enable AJAX for reports by checking appropriate field on the <a href=\"@report-setting-page\">report settings page</a>.', array('@summary-report-page' => url('admin/reports/yandex_metrics_summary'), '@report-setting-page' => url('admin/config/system/yandex_metrics/reports'))) . '</dd>';\n      $output .= '</dl>';\n      return $output;\n    case 'admin/config/system/yandex_metrics/authorization':\n      $output = '<p>' . t('To get access to the <a href=\"@reports-url\">reports</a> register Yandex application at !app_register_link. Then enter your application Client ID and Client Secret in the appropriate fields on this page. The full list of your Yandex applications is located !app_list_link.', array('!app_register_link' => l('https://oauth.yandex.ru/client/new', 'https://oauth.yandex.ru/client/new', array('attributes' => array('target' => '_blank'))), '!app_list_link' => l(t('here'), 'https://oauth.yandex.ru/client/my', array('attributes' => array('target' => '_blank'))), '@reports-url' => url('admin/reports/yandex_metrics_summary'))) . '</p>';\n      $output .= '<p>' . t('Your Yandex application Callback URI: @callback-uri', array('@callback-uri' => url('yandex_metrics/oauth', array('absolute' => TRUE)))) . '</p>';\n      return $output;\n    case 'admin/config/system/yandex_metrics/reports':\n      return '<p>' . t('You can choose necessary reports to display on <a href=\"@summary-report-page\">Yandex.Metrics Summary Report</a> page. Also, we recommend you to enable AJAX for reports by checking the appropriate field on this page.', array('@summary-report-page' => url('admin/reports/yandex_metrics_summary'))) . '</p>';\n  }\n}\n\n/*\n * Check whether Popular Content block is enabled.\n */\nfunction _yandex_metrics_reports_is_popular_content_enabled() {\n  $result = db_select(\"block\")\n    ->condition(\"module\", \"yandex_metrics_reports\")\n    ->condition(\"delta\", \"popular_content\")\n    ->condition(\"status\", 1)\n    ->fields('block')\n    ->execute()->fetchField();;\n\n  return !empty($result);\n}\n/**\n * Implements hook_yandex_metrics_reports_list().\n *\n * @return array\n */\nfunction yandex_metrics_reports_yandex_metrics_reports_list() {\n  $reports = array();\n\n  $reports['visits_chart'] = array(\n    'title' => t('Page Views, Visitors, New Visitors'),\n    'callback' => '_yandex_metrics_reports_visits_chart',\n  );\n  $reports['sources_chart'] = array(\n    'title' => t('Traffic Sources'),\n    'callback' => '_yandex_metrics_reports_sources_chart',\n  );\n  $reports['search_phrases'] = array(\n    'title' => t('Popular Search Phrases'),\n    'callback' => '_yandex_metrics_reports_search_phrases',\n  );\n  $reports['popular_content'] = array(\n    'title' => t('Popular Content'),\n    'callback' => '_yandex_metrics_reports_popular_content',\n  );\n  $reports['geo_chart'] = array(\n    'title' => t('Geography of Visits'),\n    'callback' => '_yandex_metrics_reports_geo_chart',\n  );\n\n  return $reports;\n}\n\n/**\n * Returns list of all reports.\n *\n * @return array\n */\nfunction yandex_metrics_reports_get_list() {\n\n  $reports = array();\n\n  foreach (module_implements('yandex_metrics_reports_list') as $module) {\n    $module_report_list = module_invoke($module, 'yandex_metrics_reports_list');\n    if (isset($module_report_list) && is_array($module_report_list)) {\n      $reports = array_merge($reports, $module_report_list);\n    }\n  }\n\n  return $reports;\n}\n\n/**\n * Returns list of available and enabled reports only.\n *\n * @return array\n */\nfunction yandex_metrics_reports_get_active_list() {\n  $reports = yandex_metrics_reports_get_list();\n\n  foreach ($reports as $report_name => $report_data) {\n    if (\n      !variable_get('yandex_metrics_reports_' . $report_name . '_visible', TRUE) ||\n      !function_exists($report_data['callback'])\n    ) {\n      unset($reports[$report_name]);\n    }\n  }\n\n  return $reports;\n}\n
===================================================================
--- yandex_metrics_reports/yandex_metrics_reports.module	(revision e02c79e6df30b80f4de2e987044c3ec99cb3abf1)
+++ yandex_metrics_reports/yandex_metrics_reports.module	(revision )
@@ -182,6 +182,16 @@
 }
 
 /**
+ * Implementations hook_views_api
+ */
+function yandex_metrics_reports_views_api() {
+  return array(
+    'api' => 3,
+    'path' => drupal_get_path('module', 'yandex_metrics_reports') . '/views',
+  );
+}
+
+/**
  * It is quick filter form for report page.
  * @return array
  */
@@ -1067,6 +1077,12 @@
     ->condition("status", 1)
     ->fields('block')
     ->execute()->fetchField();;
+
+  $views = views_get_view('popular_content');
+  // if views is present and it`s enabled
+  if(!empty($views) && !$views->disabled) {
+    $result = 1;
+  }
 
   return !empty($result);
 }
Index: yandex_metrics_reports/views/handlers/views_handler_field_ym_title.inc
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- yandex_metrics_reports/views/handlers/views_handler_field_ym_title.inc	(revision )
+++ yandex_metrics_reports/views/handlers/views_handler_field_ym_title.inc	(revision )
@@ -0,0 +1,67 @@
+<?php
+
+/**
+ * @file
+ * Contains the basic 'page_title' field handler.
+ */
+
+/**
+ * Field handler to provide simple renderer that allows linking to a page title.
+ * Definition terms:
+ * - link_to_ym_url default: Should this field have the checkbox "link to url from Yandex.Metricks" enabled by default.
+ *
+ * @ingroup views_field_handlers
+ */
+class views_handler_field_ym_title extends views_handler_field {
+
+  function init(&$view, &$options) {
+    parent::init($view, $options);
+    // Don't add the additional fields to groupby
+    if (!empty($this->options['link_to_ym_url'])) {
+      $this->additional_fields['url'] = array('table' => 'yandex_metrics_reports_popular_content', 'field' => 'url');
+    }
+  }
+
+  function option_definition() {
+    $options = parent::option_definition();
+    $options['link_to_ym_url'] = array('default' => isset($this->definition['link_to_ym_url default']) ? $this->definition['link_to_ym_url default'] : FALSE, 'bool' => TRUE);
+    return $options;
+  }
+
+  /**
+   * Provide link to url
+   */
+  function options_form(&$form, &$form_state) {
+    $form['link_to_ym_url'] = array(
+      '#title' => t('Link this field to URL from Yandex.Metrics'),
+      '#description' => t("Enable to override this field's links."),
+      '#type' => 'checkbox',
+      '#default_value' => !empty($this->options['link_to_ym_url']),
+    );
+
+    parent::options_form($form, $form_state);
+  }
+
+  /**
+   * Render whatever the data is as a link to the node.
+   *
+   * Data should be made XSS safe prior to calling this function.
+   */
+  function render_link($data, $values) {
+    if (!empty($this->options['link_to_ym_url']) && !empty($this->additional_fields['url'])) {
+      if ($data !== NULL && $data !== '') {
+        $this->options['alter']['make_link'] = TRUE;
+        $this->options['alter']['path'] =  $this->get_value($values, 'url');
+      }
+      else {
+        $this->options['alter']['make_link'] = FALSE;
+      }
+    }
+    return $data;
+  }
+
+  function render($values) {
+    $value = $this->get_value($values);
+    return $this->render_link($this->sanitize_value($value), $values);
+  }
+}
Index: yandex_metrics_reports/yandex_metrics_reports.install
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
Subsystem: com.intellij.openapi.diff.impl.patch.BaseRevisionTextPatchEP
<+><?php\n/**\n * @file\n *   Install, uninstall and update the module.\n */\n\n/**\n * Implementation of hook_uninstall().\n */\nfunction yandex_metrics_reports_uninstall() {\n  // Delete module variables and clear variables cache.\n  db_delete('variable')\n    ->condition('name', 'yandex_metrics_reports_%', 'LIKE')\n    ->execute();\n  cache_clear_all('variables', 'cache_bootstrap');\n\n  // Remove block.\n  db_delete('block')\n    ->condition('module', 'yandex_metrics_reports')\n    ->execute();\n}\n\n/**\n * Implementation of hook_schema().\n */\nfunction yandex_metrics_reports_schema() {\n  $schema['yandex_metrics_reports_popular_content'] = array(\n    'description' => 'Stores the popular content.',\n    'fields' => array(\n      'url' => array(\n        'description' => 'The url obtained from Yandex.metrika.',\n        'type' => 'varchar',\n        'length' => 255,\n        'not null' => TRUE,\n        'default' => ''\n      ),\n      'page_title' => array(\n        'description' => 'The page title of the url.',\n        'type' => 'varchar',\n        'length' => 255,\n        'not null' => TRUE,\n        'default' => ''\n      ),\n      'page_views' => array(\n        'type' => 'int',\n        'unsigned' => TRUE,\n        'not null' => TRUE,\n        'default' => 0,\n        'description' => 'Page views of this url.',\n      )\n    ),\n    'unique keys' => array('url' => array('url')),\n  );\n\n  return $schema;\n}
===================================================================
--- yandex_metrics_reports/yandex_metrics_reports.install	(revision e02c79e6df30b80f4de2e987044c3ec99cb3abf1)
+++ yandex_metrics_reports/yandex_metrics_reports.install	(revision )
@@ -27,6 +27,12 @@
   $schema['yandex_metrics_reports_popular_content'] = array(
     'description' => 'Stores the popular content.',
     'fields' => array(
+      'yid' => array(
+        'description' => 'The id for url.',
+        'type' => 'serial',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
       'url' => array(
         'description' => 'The url obtained from Yandex.metrika.',
         'type' => 'varchar',
@@ -49,8 +55,22 @@
         'description' => 'Page views of this url.',
       )
     ),
+    'primary key' => array('yid'),
     'unique keys' => array('url' => array('url')),
   );
 
   return $schema;
+}
+
+/**
+ * Added primary key.
+ */
+function yandex_metrics_reports_update_7001() {
+  $spec = array(
+    'description' => 'The id for url.',
+    'type' => 'serial',
+    'unsigned' => TRUE,
+    'not null' => TRUE,
+  );
+  db_add_field('yandex_metrics_reports_popular_content', 'yid', $spec, array('primary key' => array('yid')));
 }
\ No newline at end of file
