From 57ec625fde5375fde881818bbb9d117215e051f5 Mon Sep 17 00:00:00 2001
From: Drave Robber <DraveRobber@984338.no-reply.drupal.org>
Date: Tue, 12 Feb 2013 14:17:02 +0200
Subject: [PATCH] Add webink.com submodule

---
 modules/webink/README.txt     |   35 +++++
 modules/webink/webink.info    |    5 +
 modules/webink/webink.install |   49 +++++++
 modules/webink/webink.module  |  306 +++++++++++++++++++++++++++++++++++++++++
 4 files changed, 395 insertions(+)
 create mode 100644 modules/webink/README.txt
 create mode 100644 modules/webink/webink.info
 create mode 100644 modules/webink/webink.install
 create mode 100644 modules/webink/webink.module

diff --git a/modules/webink/README.txt b/modules/webink/README.txt
new file mode 100644
index 0000000..08267fb
--- /dev/null
+++ b/modules/webink/README.txt
@@ -0,0 +1,35 @@
+WebINK module
+
+SUMMARY
+
+This module lets you use web fonts from WebINK (http://www.webink.com).
+
+PREREQUISITES
+
+WebINK depends on @font-your-face (http://drupal.org/project/fontyourface).
+It also requires PHP SoapClient library to connect to the WebINK server.
+
+MISCELLANOUS INFORMATION
+
+-- PROJECTS (a.k.a. 'TYPEDRAWERS')
+
+Fonts are imported only from those projects that are detected to match current
+domain.
+
+-- DUPLICATE FONTS
+
+WebINK allows you to add the same font to several projects; this module would
+however import it only once.
+
+ROADMAP
+
+- Look into whether fonts in our database but not found in API anymore should
+  be removed. Other submodules do not do this, however.
+
+- Look into parsing more information about projects. It does not really fit
+  anywhere in the browsing interface, but we could display a small overview
+  table on the settings page, with project names, font counts and domains, and
+  probably in a collapsible fieldset.
+
+- Look into possibilities of more aggressive synchronizing - e.g. check whether
+  API results are up-to-date before enabling a font.
diff --git a/modules/webink/webink.info b/modules/webink/webink.info
new file mode 100644
index 0000000..87a5294
--- /dev/null
+++ b/modules/webink/webink.info
@@ -0,0 +1,5 @@
+name = WebINK
+description = @font-your-face provider for WebINK.
+dependencies[] = fontyourface
+package = @font-your-face
+core = 7.x
diff --git a/modules/webink/webink.install b/modules/webink/webink.install
new file mode 100644
index 0000000..512eb05
--- /dev/null
+++ b/modules/webink/webink.install
@@ -0,0 +1,49 @@
+<?php
+
+/**
+ * @file
+ * Install/uninstall tasks for the WebINK module.
+ */
+
+/**
+ * Implements hook_requirements().
+ */
+function webink_requirements($phase) {
+  $requirements = array();
+  $t = get_t();
+  if ($phase == 'install' && !class_exists('SoapClient')) {
+    $requirements['webink_soap'] = array(
+      'description' => $t('WebINK module needs SoapClient library. Contact your server administrator if unsure.'),
+      'severity' => REQUIREMENT_ERROR,
+    );
+  }
+  return $requirements;
+}
+
+/**
+ * Implements hook_enable().
+ */
+function webink_enable() {
+  // Set weight to 1 to ensure webink_preprocess_html() is executed after
+  // fontyourface_preprocess_html(), which has weight of 0.
+  db_update('system')
+    ->fields(array('weight' => 1))
+    ->condition('name', 'webink')
+    ->execute();
+  // Do not import/update fonts - WebINK credentials are not likely set yet.
+}
+
+/**
+ * Implements hook_disable().
+ */
+function webink_disable() {
+  fontyourface_provider_disable('webink');
+}
+
+/**
+ * Implements hook_uninstall().
+ */
+function webink_uninstall() {
+  variable_del('webink_email');
+  variable_del('webink_password_hash');
+}
diff --git a/modules/webink/webink.module b/modules/webink/webink.module
new file mode 100644
index 0000000..d20ebf6
--- /dev/null
+++ b/modules/webink/webink.module
@@ -0,0 +1,306 @@
+<?php
+
+/**
+ * @file
+ * WebINK module main file.
+ */
+
+/**
+ * Implements hook_fontyourface_info().
+ */
+function webink_fontyourface_info() {
+  return array(
+    'name' => 'WebINK',
+    'url' => 'http://www.webink.com/',
+    'base_path' => 'http://www.webink.com/font/',
+  );
+}
+
+/**
+ * Implements hook_fontyourface_import().
+ */
+function webink_fontyourface_import() {
+  $api_results = webink_get_api_results();
+
+  // Bail out if got no response from API. This is the last line of defense as
+  // another error has likely been caught earlier.
+  if (!$api_results) {
+    drupal_set_message(t('No response from WebINK API.'), 'error');
+    return;
+  }
+
+  // Parse what we have got.
+  foreach ($api_results->item as $item) {
+    if ($item->entityDef == 'extensis.type-drawer') {
+      $projects[] = webink_parse_project($item);
+    }
+    elseif ($item->entityDef == 'extensis.webfont') {
+      $fonts[] = webink_parse_font($item);
+    }
+  }
+
+  // Filter fonts - save only those that belong to a project with a matching
+  // domain.
+  $imported = 0;
+  $out_of_scope = 0;
+  foreach ($fonts as $font) {
+    if (in_array($font->project, $projects)) {
+      fontyourface_save_font($font);
+      $imported++;
+    }
+    else {
+      $out_of_scope++;
+    }
+  }
+
+  // Report results.
+  drupal_set_message(t(
+    'Imported %fonts fonts from WebINK.',
+    array('%fonts' => $imported)
+  ));
+  if ($out_of_scope > 0) {
+    drupal_set_message(t(
+      'Note: there are %fonts more fonts in projects not matching current domain (%domain).',
+      array('%fonts' => $out_of_scope, '%domain' => $_SERVER['HTTP_HOST'])
+    ));
+  }
+
+  return TRUE;
+}
+
+/**
+ * Implements template_preprocess_html().
+ */
+function webink_preprocess_html(&$vars) {
+  if (!empty($vars['fontyourface'])) {
+
+    $projects = array();
+    foreach ($vars['fontyourface'] as $active_font) {
+      if ($active_font->provider == 'webink') {
+        $metadata = unserialize($active_font->metadata);
+        $projects[$metadata['project_guid']][$metadata['font_guid']] = $active_font->css_family;
+      }
+    }
+
+    if (count($projects) > 0) {
+      $base = 'http://fnt.webink.com/wfs/webink.css?';
+      foreach ($projects as $project => $items) {
+        $fonts = array();
+        foreach ($items as $guid => $css_family) {
+          $fonts[] = $guid . ':family=' . $css_family;
+        }
+        $css = $base . 'project=' . $project . '&fonts=' . implode(',', $fonts);
+        fontyourface_add_css_in_preprocess($vars, $css, 'remote');
+      }
+    }
+
+  }
+}
+
+/**
+ * Implements hook_fontyourface_preview().
+ */
+function webink_fontyourface_preview($font, $text = NULL, $size = 18) {
+  $output = '';
+  if ($text == NULL) {
+    $text = $font->name;
+  }
+  if ($size == 'all') {
+    // Display variety of sizes.
+    $sizes = array(32, 24, 18, 14, 12, 10);
+    foreach ($sizes as $size) {
+      $output .= '<div style="' . fontyourface_font_css($font) . ' font-size: ' . $size . 'px; line-height: ' . $size . 'px;">' . $text . '</div>';
+    }
+  }
+  else {
+    // Display single size.
+    $output = '<span style="' . fontyourface_font_css($font) . ' font-size: ' . $size . 'px; line-height: ' . $size . 'px;">' . $text . '</span>';
+  }
+  return $output;
+}
+
+/**
+ * Implements hook_form_FORM_ID_alter() for fontyourface_ui_settings_form().
+ */
+function webink_form_fontyourface_ui_settings_form_alter(&$form, &$form_state, $form_id) {
+  // Get credentials.
+  $email = variable_get('webink_email', '');
+  $password_hash = variable_get('webink_password_hash', '');
+
+  // Add 'WebINK' fieldset.
+  $form['webink'] = array(
+    '#type' => 'fieldset',
+    '#title' => 'WebINK',
+    '#weight' => -1,
+    'webink_email' => array(
+      '#type' => 'textfield',
+      '#title' => t('Email'),
+      '#description' => t('The email address you registered with your account.'),
+      '#default_value' => $email,
+    ),
+    'webink_password' => array(
+      '#type' => 'password',
+      '#title' => t('Password'),
+      '#description' => t(
+        'No worries, this is not saved as plain text. !link',
+        array(
+          '!link' => l(
+            t('Forgot password?'),
+            'https://www.webink.com/forgot-password',
+            array('attributes' => array('target' => '_blank'))
+          ),
+        )
+      ),
+    ),
+    'webink_save_settings' => array(
+      '#type' => 'submit',
+      '#value' => t('Save WebINK credentials'),
+    ),
+  );
+  $form['#submit'][] = 'webink_save_settings';
+
+  // Move the default update/import button to the WebINK fieldset.
+  if (isset($form['providers']['webink_import'])) {
+    $form['webink']['webink_import'] = $form['providers']['webink_import'];
+    unset($form['providers']['webink_import']);
+  }
+
+  // Disable import button and add warnings if credentials not set or SOAP not
+  // available.
+  $warnings = array();
+  if (!class_exists('SoapClient')) {
+    $warnings[] = t('SoapClient library not available.');
+  }
+  if (empty($email) || empty($password_hash)) {
+    $warnings[] = t('WebINK credentials not set.');
+  }
+  if (count($warnings) > 0) {
+    $form['webink']['webink_import']['#disabled'] = TRUE;
+    $form['webink']['warnings'] = array(
+      '#type' => 'markup',
+      '#markup' => theme('item_list', array('items' => $warnings)),
+      '#prefix' => '<div class="messages warning">',
+      '#suffix' => '</div>',
+      '#weight' => 99,
+    );
+  }
+}
+
+/**
+ * Custom submit handler for fontyourface_ui_settings_form.
+ */
+function webink_save_settings($form, &$form_state) {
+  if ($form_state['clicked_button']['#parents'][0] == 'webink_save_settings') {
+    variable_set('webink_email', $form_state['values']['webink_email']);
+    variable_set('webink_password_hash', md5($form_state['values']['webink_password']));
+  }
+}
+
+/**
+ * Helper function - get API results.
+ */
+function webink_get_api_results() {
+  try {
+    $url = 'http://acl.webink.com/ws/DrawerManager?wsdl';
+    $email = variable_get('webink_email', '');
+    $password_hash = variable_get('webink_password_hash', '');
+
+    // Bail out if missing credentials or SOAP. Normally we would not get this
+    // far if missing something, but double-check. Double-check.
+    if (empty($email) || empty($password_hash) || !class_exists('SoapClient')) {
+      return FALSE;
+    }
+
+    $credentials = array(
+      array('name' => 'extensis.customer.accountlogin', 'value' => $email),
+      array('name' => 'credentials.esp.password', 'value' => $password_hash),
+    );
+
+    $client = new SoapClient($url, array('trace' => 1, 'exception' => 0));
+    $client->login($credentials);
+    $return = $client->getTypeDrawers($credentials, array(), TRUE);
+
+    fontyourface_log('WebINK API response:<pre>@response</pre>', array('@response' => print_r($return, TRUE)));
+
+    return $return;
+  }
+  catch (SoapFault $e) {
+    drupal_set_message(t('SOAP error: %error', array('%error' => $e->getMessage())), 'error');
+    fontyourface_log('SOAP error while getting API results: @error', array('@error' => $e->getMessage()));
+  }
+}
+
+/**
+ * Helper function - parse a project and check it for matching domains.
+ *
+ * @param object $item
+ *   Data for a single project as contained in API results.
+ *
+ * @return string|false
+ *   Project GUID if it matches current domain, or FALSE if not.
+ */
+function webink_parse_project($item) {
+  foreach ($item->attributes as $attribute) {
+    if ($attribute->name == 'extensis.type-drawer.referrers') {
+      $domains = explode(',', $attribute->value);
+      break;
+    }
+  }
+  foreach ($domains as $domain) {
+    if (substr($_SERVER['HTTP_HOST'], -1 * strlen($domain)) === $domain) {
+      // Found a matching domain, go home.
+      return $item->guid;
+    }
+  }
+  return FALSE;
+}
+
+/**
+ * Helper function - parse a font.
+ *
+ * @param object $item
+ *   Data for a single font as contained in API results.
+ *
+ * @return object
+ *   Font as used by @font-your-face, with some extra info for easier
+ *   processing.
+ */
+function webink_parse_font($item) {
+  $font = new stdClass();
+  $metadata = array();
+  $family = '';
+
+  foreach ($item->attributes as $attribute) {
+    switch ($attribute->name) {
+      case 'extensis.webfont.master-name':
+        $font->name = $attribute->value;
+        break;
+
+      case 'extensis.webfont.master-psname':
+        $font->css_family = $attribute->value;
+        break;
+
+      case 'extensis.webfont.master-family':
+        $family = $attribute->value;
+        break;
+
+      case 'extensis.webfont.master-guid':
+        $metadata['font_guid'] = $attribute->value;
+        break;
+    }
+  }
+
+  $font->provider = 'webink';
+  $metadata['project_guid'] = $item->relations->targetEntityGuid;
+  $font->url = 'http://www.webink.com/font/' . drupal_html_class($family) . '#' . $font->css_family;
+  $font->metadata = serialize($metadata);
+  $font->license = 'Terms of Service';
+  $font->license_url = 'http://www.webink.com/terms';
+
+  // Add project GUID at the top level. This will not be saved into the
+  // database and is meant to facilitate filtering (so that we would not have
+  // to unserialize metadata).
+  $font->project = $item->relations->targetEntityGuid;
+
+  return $font;
+}
-- 
1.7.9.5

