<?php

/**
 * @file
 *
 */

function incubator_social_incubator_settings_menu() {
  return array(
    'description' => 'Settings for social site integration.',
    'title' => 'Social Integration',
  );
}

function incubator_social_incubator_settings() {
  
  $form = $form_state = array();
  
  // =============================
  // SHARING
  
  $form['sharing'] = array(
    '#type' => 'fieldset',
    '#title' => t('Sharing'),
  );
  
  // Social widgets: Socialite.js
  $form['sharing']['incubator_social_widgets'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use social sharing buttons'),
    '#description' => t('Enables buttons for Facebook like, Twitter share, Google +1.'),
    '#default_value' => variable_get('incubator_social_widgets', FALSE),
  );
  $form['sharing']['incubator_social_widgets_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Widget settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#states' => array(
      'invisible' => array(
        ':input[name="incubator_social_widgets"]' => array('checked' => FALSE),
      ),
    ),
  );
  $form['sharing']['incubator_social_widgets_settings']['incubator_social_widgets_node_full'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show social buttons on full node display'),
    '#default_value' => variable_get('incubator_social_widgets_node_full', TRUE),
  );
  $form['sharing']['incubator_social_widgets_settings']['incubator_social_widgets_node_teaser'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show social buttons on teasers'),
    '#default_value' => variable_get('incubator_social_widgets_node_teaser', TRUE),
  );
  $form['sharing']['incubator_social_widgets_settings']['incubator_social_widgets_services'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Buttons to implement'),
    '#options' => array(
      'tw' => t('Twitter'),
      'go' => t('Google+'),
      'li' => t('LinkedIn'),
      'fb' => t('Facebook'),
    ),
    '#default_value' => variable_get('incubator_social_widgets_services', array('tw', 'go', 'fb')),
  );
  
    
  // =============================
  // METATAGS : DESCRIPTIONS & LOGO
  
  $form['metatags'] = array(
    '#type' => 'fieldset',
    '#title' => t('Meta tags'),
  );
  
  $form['metatags']['descriptions'] = array(
    '#type' => 'fieldset',
    '#title' => t('Page descriptions for views'),
    '#description' => t('Page descriptions appear on social networks and search engine results as supplementary text to a shared page. '
        . 'Most descriptions use a summary of the page content; but for views, there is no content, so the view description can be set here.'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  
  $views = views_get_all_views();
  foreach ($views as $name => $view) {
    if (!$view->disabled && !empty($view->human_name)) {
      foreach ($view->display as $display) {
        if ($display->display_plugin == 'page') {
          $form['metatags']['descriptions']["incubator_social_views_descriptions_$name"] = array(
            '#type' => 'textarea',
            '#title' => check_plain($view->human_name),
            '#default_value' => variable_get("incubator_social_views_descriptions_$name", $view->description),
            '#rows' => 2,
          );
          continue;
        }
      }
    }
  }
  
  $points = array(
    t('The default image should be like a logo that represents your entire site.'),
    t('The default image should not usually have transparency.'),
    t('Small images (less than 600 x 315px) should be square.'),
    t('Larger images should have a wide aspect of 1.91:1, and will appear large on Facebook.'),
  );
  $form['metatags']['social_logo'] = array(
    '#type' => 'fieldset',
    '#title' => t('Sharing image'),
    '#description' => t('The default social sharing image will show in social news feeds for pages that do not have a page-specific image. It is important to specify this because otherwise Facebook can choose any picture from the page!') . 
      '<ul><li>' . implode('</li><li>', $points) . '</li></ul>',
  );
  if ($img_uri = variable_get('incubator_social_image_path', '')) {
    if ($img = image_load($img_uri)) {
      $img_path = file_create_url($img_uri);
      $height = $img->info['height'];
      $width = $img->info['width'];
      $ratio = $width / $height;
      $size = ($height > 599 && $width > 314) ? 'large' : 'small';
      $aspect = ($ratio >= 1 && $size = 'small') || ($ratio >= 1.91 && $size == 'large') ? 'wide' : 'tall';
      $class = "image $size $aspect";
      $img_markup = "background-image:url($img_path)";
    }
  }
  if (empty($img_markup)) {
    $img_markup = '';
    $class = 'no-image';
  }
  global $base_url;
  $title = t('Example of how a shared page might look on Facebook');
  $text = t('This is an example of how a page shared from your site might look on Facebook. If you upload an image as the default, it will appear here.');
  $text .= '<span class="no-image-warning"> ' . t('If no default image is specified, Facebook will choose which image to share!') . '</span>';
  $form['metatags']['social_logo']['demonstration'] = array(
    '#markup' => "<div class='incubator-social-demo $class'><div class='social-image-wrapper' style='$img_markup'></div><div class='social-text-wrapper'><h3>$title</h3>$base_url<br/><p>$text</p></div></div>",
  );
  $form['metatags']['social_logo']['incubator_social_image_path'] = array(
    '#type' => 'textfield',
    '#title' => t('Default social sharing image path'),
    '#default_value' => $img_uri,
  );
  $form['metatags']['social_logo']['incubator_social_image_upload'] = array(
    '#type' => 'file',
    '#title' => t('Upload custom image'),
    '#description' => t('Upload a custom image here. Allowed extensions: jpg, jpeg, png, gif. Uploaded images will be renamed.'),
  );
  
  // =============================
  // SOCIAL ACCOUNTS
  
//  $form['incubator_social_accounts'] = array(
//    '#type' => 'fieldset',
//    '#title' => t('Accounts'),
//    '#description' => t('If your organization maintains public accounts on '
//        . 'social media services, enter the information here.'),
//    '#collapsible' => FALSE,
//    '#collapsed' => FALSE,
//  );
  
  // =============================
  // SOCIAL LOGIN
  
  $form['social_login'] = array(
    '#type' => 'fieldset',
    '#title' => t('Social login'),
  );
  $hybridauth_exists = module_exists('hybridauth');
  $form['social_login']['incubator_social_hybridauth'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable login through social services'),
    '#description' => t('Allow people to login to your site using social network accounts.') . 
      ($hybridauth_exists ? '' : '<br/><b>' . t('Note that this requires advanced setup before it will work.') . '</b>'),
    '#default_value' => $hybridauth_exists,
  );
  $form['social_login']['incubator_social_hybridauth_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Social login settings'),
    '#collapsible' => $hybridauth_exists,
    '#collapsed' => $hybridauth_exists,
    '#states' => array(
      'invisible' => array(
        ':input[name="incubator_social_hybridauth"]' => array('checked' => FALSE),
      ),
    ),
  );
  
  $hybridauth_markup = module_exists('hybridauth') ? 
      t('Social login is handled by the Hybridauth library; the full settings are available at !link.', array('!link' => l('/admin/config/people/hybridauth', '/admin/config/people/hybridauth'))) :
      t('Save the configuration to see social login settings.');
  $form['social_login']['incubator_social_hybridauth_settings']['explanation'] = array(
    '#markup' => '<p>' . $hybridauth_markup . '</p>',
  );

  if (module_exists('hybridauth')) {
    if ($path = libraries_get_path('hybridauth')) {
      module_load_include('inc', 'hybridauth', 'hybridauth.admin');

      $core_settings = array(
        USER_REGISTER_ADMINISTRATORS_ONLY => t('Administrators only'),
        USER_REGISTER_VISITORS => t('Visitors'),
        USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL => t('Visitors, but administrator approval is required'),
      );
      $form['social_login']['incubator_social_hybridauth_settings']['hybridauth_register'] = array(
        '#type' => 'radios',
        '#title' => t('Who can register accounts?'),
        '#options' => array(
          0 => t('Follow core') . ': ' . $core_settings[variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)],
          1 => t('Visitors'),
          2 => t('Visitors, but administrator approval is required'),
        ),
        '#description' => t('Select who can register accounts through HybridAuth.') . ' '
          . t('The core settings are available at <a href="!link">Account settings</a>.',
            array('!link' => url('admin/config/people/accounts'))),
        '#default_value' => variable_get('hybridauth_register', 0),
      );
      $core_settings = array(
        0 => t("Don't require e-mail verification"),
        1 => t('Require e-mail verification'),
      );
      $form['social_login']['incubator_social_hybridauth_settings']['hybridauth_email_verification'] = array(
        '#type' => 'radios',
        '#title' => t('E-mail verification'),
        '#options' => array(
          0 => t('Follow core') . ': ' . $core_settings[variable_get('user_email_verification', TRUE)],
          1 => t('Require e-mail verification'),
          2 => t("Don't require e-mail verification"),
        ),
        '#description' => t('Select how to handle not verified e-mail addresses (authentication provider gives non-verified e-mail address).') . ' '
          . t('The core settings are available at <a href="!link">Account settings</a>.',
            array('!link' => url('admin/config/people/accounts'))),
        '#default_value' => variable_get('hybridauth_email_verification', 0),
      );
      foreach(incubator_social_preferred_providers() as $provider_id) {
        $keys_form = hybridauth_admin_provider_settings($form, $form_state, $provider_id);
        $enabled = variable_get("hybridauth_provider_{$provider_id}_enabled", FALSE);
        $form['social_login']['incubator_social_hybridauth_settings']['keys'][$provider_id] = $keys_form['vtabs']['application'];
        $form['social_login']['incubator_social_hybridauth_settings']['keys'][$provider_id]['hybridauth_provider_' . $provider_id . '_window_type'] = $keys_form['vtabs']['window_settings']['hybridauth_provider_' . $provider_id . '_window_type'];
        $form['social_login']['incubator_social_hybridauth_settings']['keys'][$provider_id]['#title'] = $provider_id . ($enabled ? ' <span class="provider-enabled">' . t('Enabled') . '</span>' : '');
        $form['social_login']['incubator_social_hybridauth_settings']['keys'][$provider_id]['#collapsible'] = TRUE;
        $form['social_login']['incubator_social_hybridauth_settings']['keys'][$provider_id]['#collapsed'] = TRUE;
      }
    }
    else {
      $form['social_login']['incubator_social_hybridauth_settings']['download_hybridauth'] = array(
        '#markup' => '<p class="error">' . t('You must download the hybridauth library in order to use this feature. '
            . 'You can download it from !link, unzip it, make sure the folder name is just "hybridauth" and not "hybridauth-2.1.2", '
            . 'and place the hybridauth folder in your Drupal installation at sites/all/libraries/hybridauth', 
            array('!link' => l('sourceforge.net', 'http://downloads.sourceforge.net/project/hybridauth/hybridauth-2.1.2.zip'))) . '</p>',
      );
    }
  }
  
  $form = system_settings_form($form);
  $form['#submit'][] = 'incubator_social_incubator_settings_submit';
  $form['#validate'][] = 'incubator_social_incubator_settings_validate';
  drupal_add_css(drupal_get_path('module', 'incubator_social') . '/incubator_social.admin.css');
  
  return $form;
  
}

function incubator_social_incubator_settings_validate($form, &$form_state) {
  $file = file_save_upload('incubator_social_image_upload', array(
    // Validates file is really an image.
    'file_validate_is_image' => array(),
    // Validate extensions.
    'file_validate_extensions' => array('png gif jpg jpeg'),
  ));
  // If the file passed validation:
  if (isset($file)) {
    if ($file) {
      // Save the file for use in the submit handler.
      $form_state['storage']['incubator_social_file'] = $file;
      if ($form_state['values']['incubator_social_image_path']) {
        drupal_set_message(t('Your image has been uploaded; you may need to refresh the page if you still see the old image.'), 'warning');
        $form_state['values']['incubator_social_image_path'] = '';
      }
    }
    else {
      form_set_error('incubator_social_image_upload', t('The image could not be uploaded.'));
    }
  }
  if ($form_state['values']['incubator_social_image_path']) {
    module_load_include('inc', 'system', 'system.admin');
    $path = _system_theme_settings_validate_path($form_state['values']['incubator_social_image_path']);
    if (!$path) {
      form_set_error('incubator_social_image_path', t('The image path is not valid.'));
    }
    else {
      $form_state['values']['incubator_social_image_path'] = $path;
    }
  }
}

function incubator_social_incubator_settings_submit(&$form, &$form_state) {

  // SHARING
  
  variable_set('incubator_social_widgets_services', array_filter($form_state['values']['incubator_social_widgets_services']));
  
  if (!empty($form_state['storage']['incubator_social_file'])) {
    $file = $form_state['storage']['incubator_social_file'];
    unset($form_state['storage']['incubator_social_file']);
    $ext = array();
    preg_match('/(\.[^.]+)$/', $file->filename, $ext);
    if ($new_path = file_unmanaged_copy($file->uri, 'public://site-social-logo' . $ext[1], FILE_EXISTS_REPLACE)) {
      variable_set('incubator_social_image_path', $new_path);
    }
  }
    
  // SOCIAL LOGIN
  
  if (!empty($form_state['values']['incubator_social_hybridauth'])) {
    if (!module_exists('hybridauth')) {
      // Enable the module if it is not already enabled
      module_enable(array('hybridauth'));
      
      // Add hybridauth permissions for anonymous and authenticated users
      if (!variable_get('incubator_disable_site', TRUE)) {
        user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('use hybridauth'));
      }
      user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, array('use hybridauth'));

      // Limit hybridauth facebook scope requested
      variable_set('hybridauth_provider_Facebook_scope', array('email' => 'email'));

      // Set hybridauth on all forms
      variable_set('hybridauth_forms', array(
        'user_login' => 'user_login',
        'user_login_block' => 'user_login_block',
        'user_register_form' => 'user_register_form',
        'comment_form' => 'comment_form',
      ));

      // Remove hybridauth identities field from user profile display
      $user_settings = variable_get('field_bundle_settings_user__user', array());
      $user_settings['extra_fields']['display']['hybridauth_identities']['default']['visible'] = 0;
      $user_settings['extra_fields']['display']['hybridauth_identities']['default']['weight'] = 0;
      variable_set('field_bundle_settings_user__user', $user_settings);

    }
    else {
      // if Hybridauth is already enabled, set the settings
      foreach(incubator_social_preferred_providers() as $provider_id) {
        if ($form_state['values']["hybridauth_provider_{$provider_id}_keys_secret"] && (
            $form_state['values']["hybridauth_provider_{$provider_id}_keys_id"] ||
            $form_state['values']["hybridauth_provider_{$provider_id}_keys_key"]
          )) {
          variable_set("hybridauth_provider_{$provider_id}_enabled", TRUE);
        }
        else {
          variable_set("hybridauth_provider_{$provider_id}_enabled", FALSE);
        }
      }
    }
  }
  else {
    if (module_exists('hybridauth')) {
      module_disable(array('hybridauth'));
    }
  }
  
  drupal_flush_all_caches();
  
}
