Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / modules / contrib / fontyourface / modules / typekit_api / typekit_api.module
1 <?php
2
3 /**
4  * @file
5  * Typekit API module file.
6  */
7
8 define('TYPEKIT_API_BASE_URL', 'https://typekit.com/api/v1/json/');
9
10 use Drupal\Core\Form\FormStateInterface;
11 use Drupal\Component\Utility\Unicode;
12 use Drupal\Core\Link;
13
14 /**
15  * Implements hook_fontyourface_api().
16  */
17 function typekit_api_fontyourface_api() {
18   return [
19     'version' => '3',
20     'name' => 'Typekit',
21   ];
22 }
23
24 /**
25  * Implements hook_modules_installed().
26  *
27  * Use this hook instead of hook_install, because the route "font.settings" is
28  * not defined otherwise.
29  */
30 function typekit_api_modules_installed($modules) {
31   if (in_array('typekit_api', $modules)) {
32     drupal_set_message(t('Typekit needs to be set up in order for fonts to be imported. Please use @link to import Typekit fonts.', ['@link' => Link::createFromRoute('@font-your-face settings', 'font.settings')->toString()]));
33   }
34 }
35
36 /**
37  * Implements hook_form_FORM_ID_alter().
38  */
39 function typekit_api_form_font_settings_alter(&$form, FormStateInterface $form_state) {
40   $config = \Drupal::config('typekit_api.settings');
41   $form['typekit_api'] = [
42     '#type' => 'fieldset',
43     '#title' => t('TYPEKIT SETTINGS'),
44   ];
45   $form['typekit_api']['typekit_token'] = [
46     '#type' => 'textfield',
47     '#title' => t('Typekit API Token'),
48     '#description' => t('Add your Typekit API token to import your kits. Available at <a target="_blank" href=":url">:url</a>', [':url' => 'https://typekit.com/account/tokens']),
49     '#default_value' => $config->get('token'),
50   ];
51   $form['#submit'][] = 'typekit_api_form_font_settings_submit';
52 }
53
54 /**
55  * Submits Font settings form data.
56  */
57 function typekit_api_form_font_settings_submit(&$form, FormStateInterface $form_state) {
58   $values = $form_state->getValues();
59   $config = \Drupal::configFactory()->getEditable('typekit_api.settings');
60   $config->set('token', $values['typekit_token'])->save();
61   drupal_set_message(t('Saved Typekit API token'));
62 }
63
64 /**
65  * Implements hook_page_attachments().
66  */
67 function typekit_api_page_attachments(&$page) {
68   $enabled_fonts = &drupal_static('fontyourface_fonts', []);
69   $kits = [];
70   foreach ($enabled_fonts as $font) {
71     if ($font->pid->value == 'typekit_api') {
72       $metadata = $font->getMetadata();
73       $kits[$metadata['kit']] = $metadata['kit'];
74     }
75   }
76   foreach ($kits as $kit) {
77     $page['#attached']['html_head'][] = [
78       [
79         '#type' => 'html_tag',
80         '#tag' => 'script',
81         '#attributes' => [
82           'src' => 'https://use.typekit.com/' . $kit . '.js',
83         ],
84       ], 'fontyourface-typekit-api-' . $kit,
85     ];
86     $page['#attached']['html_head'][] = [
87       [
88         '#type' => 'html_tag',
89         '#tag' => 'script',
90         '#value' => 'try{Typekit.load({ async: true });}catch(e){}',
91       ], 'fontyourface-typekit-api-inline',
92     ];
93   }
94 }
95
96 /**
97  * Implements hook_fontyourface_import().
98  */
99 function typekit_api_fontyourface_import($font_context = []) {
100   $config = \Drupal::config('typekit_api.settings');
101   if (empty($config->get('token'))) {
102     drupal_set_message(t('Typekit token not set. Cannot import typekit kits.'));
103     return $font_context;
104   }
105
106   $kits = typekit_api_get_kits($config->get('token'));
107   foreach ($kits as $kit_data) {
108     $kit = typekit_api_get_kit($kit_data->id, $config->get('token'));
109     if (typekit_api_kit_matches_domain($kit, $_SERVER['HTTP_HOST'])) {
110       foreach ($kit->families as $family) {
111         foreach ($family->variations as $variant_id) {
112           $variant = typekit_api_get_variant($family->id, $variant_id, $config->get('token'));
113           $metadata = [
114             'typekit_id' => $variant->id,
115             'variant' => $variant->font_variant,
116             'kit' => $kit->id,
117           ];
118           $font_data = new stdClass();
119           $font_data->name = $variant->name;
120           $font_data->url = 'https://typekit.com/fonts/' . $family->slug . '#' . $variant_id;
121           $font_data->provider = 'typekit_api';
122           $font_data->css_family = "'" . implode("', '", $family->css_names) . "'";
123           $font_data->css_style = $variant->font_style;
124           $font_data->css_weight = $variant->font_weight;
125           $font_data->foundry_url = 'https://typekit.com/foundries/' . $variant->foundry->slug;
126           $font_data->metadata = $metadata;
127           $font = fontyourface_save_font($font_data);
128           $font->activate();
129         }
130       }
131     }
132     else {
133       drupal_set_message(t('Typekit kit did not match current domain, @domain', ['@domain' => $_SERVER['HTTP_HOST']]));
134     }
135   }
136   drupal_set_message(t('Imported Typekit kits: @kits', ['@kits' => print_r($kits, TRUE)]));
137   return $font_context;
138 }
139
140 /**
141  * Returns kits based on typekit id.
142  *
143  * @param string $token
144  *   The typekit api token.
145  *
146  * @return array
147  *   Array of typekit font objects.
148  */
149 function typekit_api_get_kits($token = NULL) {
150   try {
151     $uri = TYPEKIT_API_BASE_URL . 'kits';
152     $response = \Drupal::httpClient()->get($uri, ['headers' => typekit_api_token_headers($token), 'verify' => FALSE]);
153     $data = json_decode((string) $response->getBody());
154   }
155   catch (RequestException $e) {
156     drupal_set_message(t('There was an error importing kit list from Typekit. Error: %error', ['%error' => $e->getMessage()]), 'error');
157     return FALSE;
158   }
159   return $data->kits;
160 }
161
162 /**
163  * Returns kit information.
164  *
165  * @param string $kit_id
166  *   The typekit kit id.
167  * @param string $token
168  *   The typekit api token.
169  *
170  * @return object
171  *   Typekit kit object.
172  */
173 function typekit_api_get_kit($kit_id, $token = NULL) {
174   try {
175     $uri = TYPEKIT_API_BASE_URL . 'kits/' . $kit_id;
176     $response = \Drupal::httpClient()->get($uri, ['headers' => typekit_api_token_headers($token), 'verify' => FALSE]);
177     $data = json_decode((string) $response->getBody());
178   }
179   catch (RequestException $e) {
180     drupal_set_message(t('There was an error importing kit list from Typekit. Error: %error', ['%error' => $e->getMessage()]), 'error');
181     return FALSE;
182   }
183   return $data->kit;
184 }
185
186 /**
187  * Get a specific variant from API based on family and variant IDs.
188  *
189  * @param string $family_id
190  *   The typekit font family id.
191  * @param string $variant_id
192  *   The typekit font variant id.
193  * @param string $token
194  *   The typekit api token.
195  *
196  * @return object
197  *   Typekit font family variant object.
198  */
199 function typekit_api_get_variant($family_id, $variant_id, $token = NULL) {
200   try {
201     $uri = TYPEKIT_API_BASE_URL . 'families/' . $family_id . '/' . $variant_id;
202     $response = \Drupal::httpClient()->get($uri, ['headers' => typekit_api_token_headers($token), 'verify' => FALSE]);
203     $data = json_decode((string) $response->getBody());
204   }
205   catch (RequestException $e) {
206     drupal_set_message(t('There was an error importing a variant (@kit, @variant) from Typekit: %error',
207       [
208         '@kit' => $family_id,
209         '@variant' => $variant_id,
210         '%error' => $e->getMessage(),
211       ]), 'error');
212     return FALSE;
213   }
214   return $data->variation;
215 }
216
217 /**
218  * Provides header with token.
219  *
220  * @param string $token
221  *   The typekit api token.
222  *
223  * @return array
224  *   Header with typekit token for API request.
225  */
226 function typekit_api_token_headers($token = NULL) {
227
228   if (empty($token)) {
229     $config = \Drupal::config('typekit_api.settings');
230     $token = $config->get('token');
231   }
232   return [
233     'X-Typekit-Token' => $token,
234   ];
235 }
236
237 /**
238  * Checks if a kit is valid against a particular domain.
239  *
240  * @param string $kit
241  *   Typekit font kit project id.
242  * @param string $domain
243  *   Site domain.
244  *
245  * @return bool
246  *   TRUE if kit is valid against domain. FALSE otherwise.
247  */
248 function typekit_api_kit_matches_domain($kit, $domain) {
249   $domain = Unicode::strtolower($domain);
250   $domains = array_filter($kit->domains, function ($kit_domain) use ($domain) {
251     if ($kit_domain == $domain) {
252       return TRUE;
253     }
254     return preg_match('#' . str_replace(['.', '*'], ['\.', '.*'], $kit_domain) . '#', $domain);
255   });
256   return !empty($domains);
257 }