<?php
/**
 * @file
 * Module file for diy_meta_alternate
 */

function diy_meta_alternate_preprocess_page(&$vars) {
  
  $languages = language_list();

  // process frontpage
  if (drupal_is_front_page()) {

    $domainIds = domain_domains();
    $domainIds = array_map(function($obj) { return $obj['domain_id']; }, $domainIds);

    foreach ($domainIds as $domainId) {
      $countrycode = diy_meta_alternate_get_country_code_for_domain_id($domainId);

      if ($countrycode === false) {
        continue;
      }

      $domain = domain_load($domainId);

      $language = $vars['language']->language;

      $languagePart = '';
      if (
          language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_URL) &&
          variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
      ) {
          $languagePart = '/' . $language;
      }
      drupal_add_html_head_link(array(
          'rel' => 'alternate',
          'hreflang' => $language.(empty($countrycode) ? '' : '-'.$countrycode),
          'href' => $domain['scheme'].'://'.$domain['subdomain'].$languagePart
      ));

    }
    return;
  }

  // process on node-pages for article, video, werkzeug, pages,...
  if ($node = _diy_meta_alternate_check_for_canonical()) {
    
    // only use domains where current node is published to
    $domainIds = $node->domains;
    if ($node->domain_site) {
      $domainIds = domain_domains();
      $domainIds = array_map(function($obj) { return $obj['domain_id']; }, $domainIds);
    }

    // iterate all domains
    foreach ($domainIds as $domainId) {
      $countrycode = diy_meta_alternate_get_country_code_for_domain_id($domainId);
  
      if ($countrycode === false) {
        continue;
      }
  
      $language = $node->language; //current(explode('-', $countrycode));
  
      // check if domain main language exists in languages
      if (empty($languages[$language])) {
        continue;
      }
  
      $path = drupal_lookup_path('alias', 'node/' . $node->nid, $language);
  
      // check if domain has an alias for this language
      if (empty($path)) {
        continue;
      }
  
      // add link to head
      $domain = domain_load($domainId);

      $languagePart = '';
      if (
        language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_URL) &&
        variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX &&
        isset($languages[$language]) &&
        $languages[$language]->prefix != ''
       ) {
        $languagePart = $languages[$language]->prefix . '/';
      }

      drupal_add_html_head_link(array(
        'rel' => 'alternate',
        'hreflang' => $language.(empty($countrycode) ? '' : '-'.$countrycode),
        'href' => $domain['scheme'].'://'.$domain['subdomain'].'/'.$languagePart.$path
      ));

    }
  }

  // process on channel pages
  if(arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $term = taxonomy_term_load(arg(2));
 
    // use all active domains
    $domainIds = domain_domains();
    $domainIds = array_map(function($obj) { return $obj['domain_id']; }, $domainIds);
    
    // iterate all domains
    foreach ($domainIds as $domainId) {
      $countrycode = diy_meta_alternate_get_country_code_for_domain_id($domainId);
  
      if ($countrycode === false) {
        continue;
      }
  
      $language = $term->language;
  
      // check if domain main language exists in languages
      if (empty($languages[$language])) {
        continue;
      }

      $path = drupal_lookup_path('alias', 'taxonomy/term/' . $term->tid, $language);
  
      // check if domain has an alias for this language
      if (empty($path)) {
        continue;
      }
  
      // add link to head
      $domain = domain_load($domainId);

      $languagePart = '';
      if (
        language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_URL) &&
        variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX
      ) {
        $languagePart = $language . '/';
      }
      drupal_add_html_head_link(array(
        'rel' => 'alternate',
        'hreflang' => $language.(empty($countrycode) ? '' : '-'.$countrycode),
        'href' => $domain['scheme'].'://'.$domain['subdomain'].'/'.$languagePart.$path
      ));
    }
  }


  if ($node = _diy_meta_alternate_check_for_canonical()) {
    if (isset($node->tnid) && drupal_multilingual() && $translations = translation_node_get_translations($node->tnid)) {
    
      // iterate all available translations
      foreach ($translations as $langcode => $translation) {
        /*if ($translation->nid == $node->nid) {
          continue;
        }*/
  
        // get domains where node is published
        $domains = domain_get_node_domains($translation->nid);
  
        if (empty($domains['domain_id'])) {
          continue;
        }
  
        // iterate all domains
        foreach ($domains['domain_id'] as $domainId) {
          $countrycode = diy_meta_alternate_get_country_code_for_domain_id($domainId);
  
          if ($countrycode === false) {
            continue;
          }
  
          $language = $translation->language; //current(explode('-', $countrycode));
  
          if (empty($languages[$language]) || $language != $langcode) {
            continue;
          }

          $languagePart = '';
          if (
            language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_URL) &&
            variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX &&
            isset($languages[$language]) &&
            $languages[$language]->prefix != ''
          ) {
            $languagePart = $languages[$language]->prefix . '/';
          }
          $domain = domain_load($domainId);
          drupal_add_html_head_link(array(
            'rel' => 'alternate',
            'hreflang' => $language.(empty($countrycode) ? '' : '-'.$countrycode),
            'href' => $domain['scheme'].'://'.$domain['subdomain'].'/'.$languagePart.
              drupal_lookup_path('alias', 'node/' . $translation->nid, $language)
          ));
        }
      }
    }
  }
}

function diy_meta_alternate_html_head_alter(&$head_elements) {

  // remove current canonical link if required
  if(_diy_meta_alternate_check_for_canonical()) {
    foreach (preg_grep('/^drupal_add_html_head_link:canonical:</', array_keys($head_elements)) as $key) {
      unset($head_elements[$key]);
    }
  }
}


function diy_meta_alternate_menu() {
  $items = array();
  $admin = user_access('administer domains');
  $items['admin/structure/diy_meta_alternate'] = array(
    'title' => 'Domain Country Codes',
    'access arguments' => array('administer domain country codes'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('diy_meta_alternate_overview_form'),
    'file' => 'diy_meta_alternate.admin.inc',
    'description' => 'Manage and configure country codes of domains.',
  );
  $items['admin/structure/diy_meta_alternate/view'] = array(
    'title' => 'Domain country code list',
    'access arguments' => array('administer domains'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('diy_meta_alternate_overview_form'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'file' => 'diy_meta_alternate.admin.inc',
    'description' => 'View country codes of domains for the site.',
    'weight' => -50,
  );

  return $items;
}

/**
 * Implements hook_theme().
 */
function diy_meta_alternate_theme($existing, $type, $theme, $path) {
  $themes = array(
    'diy_meta_alternate_overview_form' => array(
      'render element' => 'form',
      'file' => 'diy_meta_alternate.admin.inc',
    ),
  );
  return $themes;
}

/**
 * Custom function to detect if current page requires canonical rewrite
 */
function _diy_meta_alternate_check_for_canonical() {

  if(arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));

    if($node && _diy_meta_alternate_check_node_types($node->type)) {
      return $node;
    }
  }

  return false;
}

/**
 * Helper function for making meta-changes
 */
function _diy_meta_alternate_check_node_types($type) {
  $supported = array('article', 'material', 'ct_werkzeug', 'video', 'page', 'product', 'news', 'how_to', 'topic');

  if(in_array($type, $supported)) {
    return true;
  }

  return false;
}

function diy_meta_alternate_get_country_code_for_domain_id($domain_id) {
  $res = db_query("SELECT countrycode FROM {diy_domain_countrycode} WHERE domain_id=".((int)$domain_id))->fetchField();
  if ($res !== false) return $res;
  return false;
}

function diy_meta_alternate_is_enabled_domain_id($domain_id) {
  $res = db_query("SELECT enabled FROM {diy_domain_countrycode} WHERE domain_id=".((int)$domain_id))->fetchField();
  if ($res !== false) return $res;
  return false;
}

function diy_meta_alternate_is_enabled_view_name($view_name) {
    $res = db_query("SELECT enabled FROM {diy_domain_view} WHERE view_id LIKE '".$view_name."'")->fetchField();
    if ($res !== false) return $res;
    return false;
}

/**
 * Implements HOOK_metatag_metatags_view_alter().
 */
function diy_meta_alternate_metatag_metatags_view_alter(&$output, $instance) {
  // alter metatag for anbieterprofil
  if($instance == 'global' && arg(0) == 'anbieterprofil' && is_numeric(arg(1)) && is_numeric(arg(2))) {
    if(isset($output['canonical']['#attached']['drupal_add_html_head'][0][0]['#value'])) {

      $branche = node_load(arg(1));
      $domain = domain_load($branche->domain_source);

      $languagePart = '';
      if (
        language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_URL) &&
        variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX &&
        $branche->language != ''
      ) {
        $languagePart = $branche->language . '/';
      }

      $new_canonical = $domain['scheme'].'://'.$domain['subdomain'].'/'. $languagePart .
        drupal_lookup_path('alias', 'node/' . $branche->nid, $branche->language);

      $output['canonical']['#attached']['drupal_add_html_head'][0][0]['#value'] = $new_canonical;
    }
  }
}


/**
 * Implementation of hook_preprocess_views_view().
 */
function diy_meta_alternate_preprocess_views_view(&$vars) {
    global $language;

    if (drupal_is_front_page()) {
        return;
    }

    // adds alternate meta links if enabled
    if (is_callable('diy_meta_alternate_is_enabled_view_name')
        && diy_meta_alternate_is_enabled_view_name($vars['view']->name)
    ) {

        // iterate all domains
        $domainIds = domain_domains();
        $domainIds = array_map(function($obj) { return $obj['domain_id']; }, $domainIds);

        foreach ($domainIds as $domainId) {
            $countrycode = diy_meta_alternate_get_country_code_for_domain_id($domainId);

            if ($countrycode === false) {
                continue;
            }

            $view = views_get_view($vars['view']->name);

            if (!$view) {
                continue;
            }

            $args = array();
            if (isset($_GET['q'])) {
                $keys = explode('/', $_GET['q']);
                foreach ($keys as $i => $val) {
                    if (is_numeric($val)) {
                        continue;
                    }
                    if (count($keys) >= $i && isset($keys[$i+1]) && is_numeric($keys[$i+1])) {
                        $args[$val] = $keys[$i+1];
                    }
                }
            }


            $langCode = $language->language;

            $languagePart = '';
            if (
                language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_URL) &&
                variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX &&
                $language->prefix != ''
            ) {
                $languagePart = $language->prefix . '/';
            }

            $domain = domain_load($domainId);
            drupal_add_html_head_link(array(
                'rel' => 'alternate',
                'hreflang' => $langCode.(empty($countrycode) ? '' : '-'.$countrycode),
                'href' => $domain['scheme'].'://'.$domain['subdomain'].'/'.$languagePart.
                    drupal_get_path_alias($view->get_url($args))
            ));
        }
    }
}
