-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFieldtypeOpenWeatherMap.module
More file actions
415 lines (318 loc) · 13.6 KB
/
FieldtypeOpenWeatherMap.module
File metadata and controls
415 lines (318 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
<?php namespace ProcessWire;
/**
* Fieldtype Open Weather Map
*
* This module fetches and stores current
* weather data from OpenWeatherMap.org and
* helps you manage icon markup.
*
* @license Public Domain
*
* ProcessWire 2.x
* Copyright (C) 2013 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://processwire.com
*/
class WeatherData extends WireData
{
public function __construct() {
$this->set('json', null);
$this->set('timestamp', null);
$this->set('city_id', null);
$this->set('sunrise', null);
$this->set('sunset', null);
$this->set('main', null);
$this->set('description', null);
$this->set('iconcode', null);
$this->set('temperature', null);
$this->set('min_temperature', null);
$this->set('max_temperature', null);
$this->set('wind_speed', null);
}
public function set($key, $value)
{
if ($key === 'json') {
$j = json_decode($value);
//Is this a valid OpenWeatherMap.org json response?
if (!$j) {
return $this;
}
if (!isset($j->id))
return $this;
//Set the actual json property to the raw json response
$old = isset($this->data['json']) ? $this->data['json'] : null;
if (!$this->isEqual('json', $old, $value))
$this->trackChange('json', $old, $value);
$this->data['json'] = $value;
//Set the derived properties according to the json
$this->set('city_id', $j->id);
$this->set('sunrise', $j->sys->sunrise);
$this->set('sunset', $j->sys->sunset);
$this->set('main', $j->weather[0]->main);
$this->set('description', $j->weather[0]->description);
$this->set('iconcode', $j->weather[0]->icon);
$this->set('temperature', $j->main->temp);
$this->set('min_temperature', $j->main->temp_min);
$this->set('max_temperature', $j->main->temp_max);
$this->set('wind_speed', $j->wind->speed);
return $this;
}
//Set all other keys through the parent WireData
return parent::set($key, $value);
}
/**
* Returns whatever markup was configured for
* the icon in $this->iconcode.
*
*/
public function renderIcon() {
$m = $this->wire('modules')->get('FieldtypeOpenWeatherMap');
$out = $m->get($this->iconcode);
//If there’s no markup for this icon code, perhaps
//the corresponding day/night code has something?
if (empty($out)) {
$swap = array('d'=>'n', 'n'=>'d');
$code = strtr($this->iconcode, $swap);
$out = $m->get($code);
}
return $out;
}
/**
* If accessed as a string, output the city_id.
* This is so the user can easily change the city_id via InputfieldText
* on the page edit form. (Otherwise the inputfield would say "WeatherData")
*/
public function __toString() {
return "{$this->city_id}";
}
}
class FieldtypeOpenWeatherMap extends Fieldtype
{
public static function getModuleInfo()
{
return array(
'title' => __('Weather from OpenWeatherMap.org'),
'version' => '0.7.0',
'requires' => ['PHP>=5.4',
'ProcessWire>=3.0.0'],
'summary' => __('Fetches and stores current weather data from OpenWeatherMap.org and helps you manage icon markup.'),
'author' => 'Jan Romero',
'icon' => 'cloud',
'href' => 'https://github.com/JanRomero/FieldtypeOpenWeatherMap',
);
}
public function ___wakeupValue(Page $page, Field $field, $value)
{
//If city is not set, there’s nothing we can do.
if ((int)$value['city_id'] <= 0) {
return null;
}
//If value is not fresh, solicit OpenWeatherMap for new data, save and return it.
$weathertime = strtotime($value['timestamp']);
$freshTime = date('U') - 60*60*($field->cachehours);
if ($weathertime < $freshTime)
{
$out = $this->fetchWeather($page, $field, $value['city_id']);
if ($out === null) {
//city_id must be invalid. Everything sucks.
return null;
}
//$out may not be complete, but should have city_id in any case.
//Only return and store $out if it’s fine:
if ($out->json !== null) {
$out->needsSave = true;
return $out;
}
//Otherwise, we might want to return null, or just continue below and
//serve the outdated database data and try again on the next request.
//I’m opting for the latter, so let’s check if we even have cached data:
if (!$value['data'])
return null;
}
//At this point, everything seems fine and up-to-date.
//Build the WakeUpValue and return it.
$out = new WeatherData();
$out->city_id = $value['city_id'];
$out->timestamp = $value['timestamp'];
$out->json = $value['data'];
return $out;
}
public function ___sleepValue(Page $page, Field $field, $value)
{
if($value instanceof WeatherData) {
return Array('data' => "$value->json",
'timestamp' => $value->timestamp,
'city_id' => "$value->city_id");
}
//If a user saves the field via the page edit form, they enter and save only the city_id.
//So if that’s what we have here, reset the stored data and save the new city_id.
$city_id = (int)$value;
if ($city_id > 0) {
return Array('data' => '',
'timestamp' => '0000-00-00 00:00:00',
'city_id' => "$city_id");
}
return null;
}
/**
* Sanitize value for runtime
*
*/
public function sanitizeValue(Page $page, Field $field, $value)
{
return $value;
if(!$value instanceof WeatherData);
return $this->getBlankValue($page, $field);
}
public function ___formatValue(Page $page, Field $field, $value)
{
//TODO: find a better way to save the field after fetching a new version???
//We’re doing it here because doing it inside wakeupValue() would break everything ¯\(ツ)/¯
if ($value->needsSave === true) {
$page->of(false);
$value->remove('needsSave');
$value->resetTrackChanges(true);
$page->save($field->name);
$page->of(true);
}
return $value;
}
public function getInputfield(Page $page, Field $field)
{
$inputfield = $this->wire('modules')->get('InputfieldText');
return $inputfield;
}
/**
* Return the default or if not set a blank value
*
*/
public function getBlankValue(Page $page, Field $field)
{
return null;
//return new WeatherData();
}
/**
* Return the database schema in specified format
*
*/
public function getDatabaseSchema(Field $field)
{
$schema = parent::getDatabaseSchema($field);
$schema['city_id'] = "int(10) UNSIGNED NOT NULL DEFAULT 0";
$schema['timestamp'] = "timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'";
$schema['data'] = "text NOT NULL";
unset($schema['keys']['data']); //Parent sets a data key, but our data field won’t work as one
$schema['keys']['citytime'] = "KEY citytime (city_id, timestamp)";
return $schema;
}
/**
* Usable for efficiency via the module’s API if you
* know you’re requesting for multiple pages’ fields.
* Fetches regardless of cache time (for now).
*
*/
public function multiRequest(PageArray $pages, $fieldname)
{
if (!($pages instanceof PageArray))
return null;
$pages_by_city_id = array();
$url = 'http://api.openweathermap.org/data/2.5/group?id=';
foreach ($pages as $p) {
$id = $p->get($fieldname)->city_id;
$pages_by_city_id[$id] = $p;
}
$url .= implode(',', array_keys($pages_by_city_id));
$field = $this->wire('fields')->get($fieldname);
$url .= ($field->language) ? '&lang=' . urlencode($field->language) : '';
$url .= ($field->units) ? '&units=' . urlencode($field->units) : '';
//We send the API key in the request header as specified here http://www.openweathermap.org/appid
//OpenWeatherMap also allows sending it in the GET parameter “APPID”
$http = new WireHttp();
$http->setHeader('x-api-key', $this->APIKey);
$rawJson = $http->get($url);
if ($rawJson === false) {
$this->error($this->_("Error fetching weather for multiple city IDs!"));
return null;
}
$json = json_decode($rawJson, true, 50);
if(empty($json['cnt']) || $json['cnt'] == '0') {
$this->error($this->_("Error response from OpenWeatherMap.org for multiple city IDs!"));
return null;
}
foreach ($json['list'] as $i)
{
$p = $pages_by_city_id[$i['id']];
$w = new WeatherData();
$w->timestamp = date('Y-m-d H:i:s');
$w->json = json_encode($i); //Encode individual cities to json again... oh well
$p->of(false);
$p->set($fieldname, $w);
$p->save($fieldname);
$p->of(true);
}
}
protected function fetchWeather(Page $page, Field $field, $city_id)
{
if ((int)$city_id <= 0)
return null;
$out = new WeatherData();
$out->city_id = (int)$city_id;
$get_id = 'id=' . urlencode($city_id);
$get_lang = ($field->language) ? '&lang=' . urlencode($field->language) : '';
$get_units = ($field->units) ? '&units=' . urlencode($field->units) : '';
$url = "https://api.openweathermap.org/data/2.5/weather?{$get_id}{$get_lang}{$get_units}";
//We send the API key in the request header as specified here http://www.openweathermap.org/appid
//OpenWeatherMap also allows sending it in the GET parameter “APPID”
$http = new WireHttp();
$http->setHeader('x-api-key', $this->APIKey);
$rawJson = $http->get($url);
if ($rawJson === false) {
$this->error($this->_("Error fetching weather for city ID {$city_id}!"));
return $out;
}
$json = json_decode($rawJson, true);
if(empty($json['cod']) || $json['cod'] != '200') {
$this->error($this->_("Error response from OpenWeatherMap.org for city ID {$city_id}!"));
return $out;
}
//city_id already set
$out->timestamp = date('Y-m-d H:i:s');
$out->json = $rawJson;
return $out;
}
public function ___getConfigInputfields(Field $field)
{
$inputfields = parent::___getConfigInputfields($field);
$f = $this->modules->get('InputfieldInteger');
$f->attr('name', 'cachehours');
$f->attr('required', true);
$f->set('value', ($field->cachehours !== null) ? $field->cachehours : 3);
$f->set('min', 0);
$f->set('max', PHP_INT_MAX); //ProcessWire won’t set the HTML5 min attribute if max is not defined.
$f->set('inputType', 'number');
$f->label = $this->_('Maximum Cache Age in Hours');
$f->description = $this->_("This field stores timestamped responses from OpenWeatherMap.org in the database. \nOnly if an entry is older than this many hours will fresh data be requested.");
$f->notes = $this->_("A value between 1 and 12 hours is advisable. Minimum is 0 hours. \nThis field is required. Default is 3 hours.");
$f->attr('icon', 'clock-o');
$inputfields->add($f);
$f = $this->modules->get('InputfieldText');
$f->attr('name', 'language');
$f->attr('required', true);
$f->set('value', ($field->language) ? $field->language : 'en');
$f->label = $this->_('Language Code');
$f->description = $this->_("Be aware that changes do not invalidate the cached responses in the database, so they may take some time to show up.");
$f->notes = $this->_("OpenWeatherMap.org supports the following language values: \nEnglish – en, Russian – ru, Italian – it, Spanish – es (or sp), Ukrainian – uk (or ua), German – de, Portuguese – pt, Romanian – ro, Polish – pl, Finnish – fi, Dutch – nl, French – fr, Bulgarian – bg, Swedish – sv (or se), Chinese Traditional – zh_tw, Chinese Simplified – zh (or zh_cn), Turkish – tr, Croatian – hr, Catalan – ca \nThis field is required. Default is “en”.");
$f->attr('icon', 'language');
$inputfields->add($f);
$f = $this->modules->get('InputfieldRadios');
$f->attr('name', 'units');
$f->set('value', ($field->units) ? $field->units : '');
//$f->set('optionColumns', 3);
$f->addOptions(Array('metric' => 'Metric (temperature in °C)', 'imperial' => 'Imperial (temperature in °F)', '' => 'Internal (temperature in K)'));
$f->label = $this->_('Units Format');
$f->description = $this->_("This sets the requested format. It is not a conversion within the module. Be aware that changes do not invalidate the cached responses in the database, so they may take some time to show up.");
$inputfields->add($f);
return $inputfields;
}
}