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