-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevernote.module
More file actions
1153 lines (971 loc) · 34.7 KB
/
devernote.module
File metadata and controls
1153 lines (971 loc) · 34.7 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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Integration with Evernote cloud api.
*
* Provides functionality to retrieve notes and create nodes with them.
*
* @see https://github.com/evernote/evernote-cloud-sdk-php
*
* @author: Adam Kempler <akempler@gmail.com>
*/
/**
* Set to TRUE if testing the module against sandbox.evernote.com.
* @var boolean
*/
define('DEVERNOTE_SANDBOX', FALSE);
/**
* Notes in evernote with this tag will be imported.
* This can be overridden on the module's settings page.
* @var string
*/
define('DEVERNOTE_DEFAULT_TAG', 'drupalimport');
/**
* Implements hook_menu().
*/
function devernote_menu() {
$items = array();
$items['admin/config/content/devernote'] = array(
'title' => 'Devernote settings',
'description' => 'Configure the Devernote module',
'page callback' => 'drupal_get_form',
'page arguments' => array(
'devernote_settings_form',
),
'access arguments' => array('administer devernote'),
'file' => 'devernote.admin.inc',
'type' => MENU_NORMAL_ITEM,
);
$items['devernote_import'] = array(
'title' => 'Import from Evernote',
'description' => 'Import notes from evernote.',
'page callback' => 'devernote_import_by_tag',
'access arguments' => array('import notes'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
/**
* Implements hook_permission().
*/
function devernote_permission() {
return array(
'administer devernote' => array(
'title' => t('Administer the Devernote module'),
),
'import notes' => array(
'title' => t('Use Devernote to import notes.'),
),
);
}
/**
* Implements hook_node_delete().
*
* Delete the corresponding devernote_notes record if it exists.
*/
function devernote_node_delete($node) {
db_delete('devernote_notes')->condition('nid', $node->nid)->execute();
// Reset the updates field otherwise syncstate will say there are no new notes.
global $user;
$num_updated = db_update('devernote_user')
->fields(array(
'updates' => 0,
))
->condition('uid', $user->uid)
->execute();
}
/**
* Provide a form for importing notes from Evernote.
*/
function devernote_import_form($form, &$form_state) {
global $user;
$userinfo = $form_state['build_info']['args'][0];
// $import_tag = isset($userinfo['tag']) ? $userinfo['tag'] : variable_get('devernote_import_tag', DEVERNOTE_DEFAULT_TAG);
$form['devernote_import_tag'] = array(
'#type' => 'textfield',
'#title' => t('Import tag'),
'#default_value' => variable_get('devernote_import_tag', DEVERNOTE_DEFAULT_TAG),
'#description' => t('Notes with this tag name will be imported.'),
);
$options = array();
$types = node_type_get_types();
if (count($types)) {
foreach ($types as $type) {
$options[$type->type] = $type->name;
}
}
$form['devernote_import_type'] = array(
'#type' => 'select',
'#title' => t('Import as'),
'#options' => $options,
'#default_value' => variable_get('devernote_import_type', 'article'),
'#description' => t('The content type to create from the imported note.'),
);
$form['options'] = array(
'#type' => 'fieldset',
'#access' => user_access('administer nodes'),
'#title' => t('Publishing options'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#group' => 'additional_settings',
'#attributes' => array(
'class' => array('node-form-options'),
),
);
$form['options']['status'] = array(
'#type' => 'checkbox',
'#title' => t('Published'),
'#default_value' => variable_get('devernote_nodestatus', 0),
);
$form['options']['promote'] = array(
'#type' => 'checkbox',
'#title' => t('Promoted to front page'),
'#default_value' => variable_get('devernote_nodepromoted', 1),
);
$form['options']['comments'] = array(
'#type' => 'checkbox',
'#title' => t('Allow comments'),
'#default_value' => variable_get('devernote_nodecomments', 1),
);
global $user;
$formats = filter_formats($user);
$default_format = variable_get('devernote_inputformat', '');
if (!$default_format) {
$default_format = filter_default_format($user);
}
$options = array();
foreach ($formats as $format) {
$options[$format->format] = $format->name;
}
if (count($options)) {
$form['format']['input_format'] = array(
'#type' => 'select',
'#title' => t('Input Format'),
'#options' => $options,
'#default_value' => variable_get('devernote_inputformat', $default_format),
'#description' => t('Select an input format for the imported note.'),
);
}
$isloaded = extension_loaded('libxml');
if ($isloaded) {
$form['conversions'] = array(
'#type' => 'fieldset',
'#title' => t('Advanced HTML Conversions:'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#group' => 'html_conversions',
'#attributes' => array(
'class' => array('node-form-options'),
),
);
$form['conversions']['div2p'] = array(
'#type' => 'checkbox',
'#title' => t('Convert divs to p tags'),
'#default_value' => variable_get('devernote_div2p', 0),
'#description' => t('Check this to convert divs to p tags.'),
);
$form['conversions']['convertheadings_info'] = array(
'#markup' => '<strong>Font size to heading tag conversions</strong><br />
When you set different font sizes in Evernote, it uses the font-size attribute to style the text.
If you prefer to have your html rendered using html H tags instead, you can use the following text area
to specify conversions.<br />
Unfortunately you will not know what sizes Evernote will assign until you import it at least once.
You can then view the source and see what sizes it used. Then delete the node and import again.<br />
Enter font sizes followed by a comma with the corresponding html H tag you want it converted to.
One per line. For example:<br />
14, h4<br />
15, h3<br />
16, h2<br />
17, h2<br />
18, h1<br />
With the above settings, when the note gets imported any text wrapped with a <div style="font-size: 11px;"> would get wrapped in an h5 tag instead.<br />
Leave the field blank to use the note html as is.<br />
NOTE: these settings will be ignored if the input format is set to plain text when importing.',
);
$form['conversions']['convertheadings'] = array(
'#type' => 'textarea',
'#title' => t('H Tag Conversions:'),
'#default_value' => variable_get('devernote_convertheadings', ''),
'#description' => t('Convert font sizes to html h tags.'),
);
}
$form['#submit'][] = 'devernote_import_form_submit';
$form['submit'] = array(
'#value' => 'Import',
'#type' => 'submit',
);
return $form;
}
/**
* Submit handler for devernote_import_form().
*/
function devernote_import_form_submit($form, &$form_state) {
$form_state['rebuild'] = TRUE;
}
/**
* Menu callback to display a page for importing Evernote notes as nodes.
*
* @return string
* The html to display.
*
* @todo Move output to template.
*/
function devernote_import_by_tag() {
composer_manager_register_autoloader();
$Devernote = new Devernote();
$out = '';
if (isset($_POST['form_id']) && $_POST['form_id'] == 'devernote_import_form') {
// Check if there have been any updated or new content since the last check.
$updates = $Devernote->evernote_syncstate();
if ($updates) {
$tag_name = isset($_POST['devernote_import_tag']) ? $_POST['devernote_import_tag'] : DEVERNOTE_DEFAULT_TAG;
$tag_guid = $Devernote->get_tag_guid($tag_name);
if ($tag_guid) {
global $user;
$node_settings = array();
$node_settings['node_type'] = $_POST['devernote_import_type'];
$node_settings['status'] = isset($_POST['status']) ? $_POST['status'] : variable_get('devernote_nodestatus', 0);
$node_settings['promote'] = isset($_POST['promote']) ? $_POST['promote'] : variable_get('devernote_nodepromoted', 0);
$comments = isset($_POST['comments']) ? $_POST['comments'] : variable_get('devernote_nodecomments', 0);
$node_settings['comments'] = $comments === 0 ? 0 : 2;
// TODO use filter_fallback_format()?
$node_settings['input_format'] = isset($_POST['input_format']) ? $_POST['input_format'] : filter_default_format($user);
$conversions = get_conversions();
$notes = $Devernote->retrieve_tagged_notes($tag_guid, $conversions, $node_settings);
if (count($notes)) {
$out .= '<h3>The following notes were imported from Evernote:</h3>';
$out .= implode('', $notes);
} else {
$out = '<h3>There seems to have been an unknown problem importing the notes.</h3>';
}
// The supplied tag wasn't found in evernote.
} else {
$out = t("No matching tags in Evernote found that match: @tagname", array('@tagname' => $tag_name));
}
// Update count in evernote hasn't changed since last check.
} else {
$out = t('There are no new notes tagged for import.');
}
// Form hasn't been submitted yet.
} else {
$out = '<h3>Import Notes</h3>';
$form = drupal_get_form('devernote_import_form', $Devernote->userinfo);
$out .= drupal_render($form);
}
return $out;
}
/**
* Used to convert the conversions entered in the
* 'devernote_import_form' form. It converts them to an array
* usable by $Devernote->retrieve_tagged_notes().
*
* @return array
*/
function get_conversions() {
$cleanup = array();
// TODO remove using $_POST from here.
if (isset($_POST['convertheadings']) && !empty($_POST['convertheadings'])) {
$mappings = explode(PHP_EOL, $_POST['convertheadings']);
if (count($mappings)) {
$htags = array();
foreach ($mappings as $mapping) {
$pieces = explode(',', $mapping);
$htags[trim($pieces[0])] = trim($pieces[1]);
}
$cleanup['htags'] = $htags;
}
}
if (isset($_POST['div2p'])) {
$cleanup['div2p'] = $_POST['div2p'];
}
return $cleanup;
}
/**
* Save a resource (image).
*
* @param EDAM\Types\Resource $resource
* A Resource object.
* @param string $notestoreurl
* For example: https://sandbox.evernote.com/shard/s1/notestore
* @param string $auth_token
* For example:
* S=s1:U=802ed:E=1513e335e74:C=14ae6822eb8:P=185:A=jsmith-9647:V=2:H=94efbf7661da4dda35246ae3e6e228ea
*
* @return array
* array if successful otherwise FALSE.
* - 'filename' of the saved file if successful.
* - 'path_original'
* - 'path_imagestyle'
* - 'extension'
* - 'filename_md5'
*/
function _devernote_save_resource($resource, $notestoreurl, $auth_token) {
$fileinfo = array();
// TODO this assumes edam_webApiUrlPrefix
// is the same as the notestoreurl without "notestore".
$pieces = explode('/', $resource->mime);
$extension = array_pop($pieces);
$url = rtrim($notestoreurl, "notestore");
$url .= 'res/' . $resource->guid . '.' . $extension;
$dir = variable_get('file_public_path', conf_path() . '/files') . '/devernote';
file_prepare_directory($dir, FILE_CREATE_DIRECTORY);
$filename = $resource->attributes->fileName;
$extensions = array('jpg', 'jpeg', 'gif', 'png');
$filename = file_munge_filename($filename, implode(' ', $extensions));
$filepath = $dir . '/' . $filename;
$g = new GuzzleHttp\Client();
$request = $g->createRequest('GET', $url);
$request->setHeader('Cookie', 'auth=' . $auth_token);
$response = $g->send($request, ['stream' => TRUE]);
$length = $response->getHeader('Content-Length');
$size = file_put_contents($filepath, $response->getBody());
// TODO possibly compare length and size.
if ($size) {
$fileinfo['path_original'] = $filepath;
$fileinfo['filename'] = $filename;
// The sdk converts jpeg to jpg for the filename.
$fileinfo['extension'] = ($extension == 'jpeg') ? 'jpg' : $extension;
// The sdk converts the filename to an md5 hash of the body.
$fileinfo['filename_md5'] = md5($resource->data->body);
$imagestyle = variable_get('devernote_imagestyle', 'none');
// $errors = file_validate_is_image($filepath);
if (in_array($extension, $extensions) && $imagestyle != 'none') {
$styledef = image_style_load($imagestyle);
if (count($styledef)) {
$upload_uri = "public://devernote/" . $filename;
$success = image_style_create_derivative(
$styledef,
$upload_uri,
image_style_path($imagestyle, $upload_uri)
);
if ($success) {
$fileinfo['path_imagestyle'] = image_style_url($imagestyle, $upload_uri);
}
}
}
return $fileinfo;
}
return FALSE;
}
/**
* Load the secret and consumer api keys from the db.
*
* @return array
* An associative array of the keys with the keys 'secret' and 'consumer'
*/
function devernote_load_keys() {
global $user;
$keys = db_select('devernote_user')
->fields('devernote_user', array('secret_key', 'consumer_key'))
->condition('uid', $user->uid)
->execute()
->fetchAssoc();
if (($keys) && ($keys['secret_key'] != '0')) {
if (module_exists('aes')) {
$keys['secret_key'] = aes_decrypt($keys['secret_key']);
}
elseif (module_exists('encrypt')) {
$keys['secret_key'] = decrypt($keys['secret_key']);
}
}
return $keys;
}
class Devernote {
protected $client = NULL;
/**
* @var array
* An array of authorization information as well as if the data is valid.
*
* 'oauth_token' => 'S=s1:U=802ed:E=1513e335e74:C=14ae6822eb8:P=185:A=jsmith-9647:V=2:H=94efbf7661da4dda35246ae3e6e228ea';
* 'edam_noteStoreUrl' => 'https://sandbox.evernote.com/shard/s1/notestore'
* 'edam_expires' => '1452742499940'
* 'updates' => '25' - the count from syncstate
* 'tag' => 'drupalimport'
* 'tag_guid' => 'e669c090-d8b2-1323-9eae-56bd31c64'
* 'valid' => FALSE
*/
public $userinfo = array();
/**
* @var Exception
* Any exceptions thrown by the evernote api calls.
*/
protected $exception = NULL;
public $errors = array();
function __construct() {
$this->initialize_userinfo();
if ($this->userinfo['valid']) {
$this->client = new \Evernote\Client($this->userinfo['oauth_token'], DEVERNOTE_SANDBOX);
}
}
/**
* Set userinfo array using either local data or from authorization.
*/
public function initialize_userinfo() {
$this->userinfo['valid'] = FALSE;
$this->userinfo['tag'] = DEVERNOTE_DEFAULT_TAG;
$this->userinfo['tag_guid'] = 0;
$this->userinfo['updates'] = 0;
$userinfo = $this->load_userinfo();
if ($userinfo) {
$this->userinfo = array_merge($this->userinfo, $userinfo);
$this->userinfo['valid'] = $this->validate_userinfo();
if ($this->userinfo['valid']) {
// Only need to decrypt if it came from the db.
$this->userinfo['oauth_token'] = $this->decrypt_token($userinfo['oauth_token']);
}
}
if (!$userinfo || !$this->userinfo['valid']) {
$success = $this->authorize_user();
if ($success) {
$this->save_userinfo();
}
else {
// TODO check if we've already set an error.
$this->errors[] = t('There was an error authorizing the account');
}
}
}
/**
* Retrieve locally saved user/auth data from the database.
*
* @return mixed
* Arry of results if record exists otherwise FALSE.
*/
public function load_userinfo() {
global $user;
// Using "AS" to convert fields back to the same keys
// as we would receive in the $oauth_data array from Evernote.
$sql = "SELECT
uid,
oauth_token,
notestoreurl AS edam_noteStoreUrl,
expires AS edam_expires,
updates,
tag,
tag_guid
FROM {devernote_user}
WHERE uid = :uid";
$userinfo = db_query($sql, array(':uid' => $user->uid))->fetchAssoc();
return $userinfo;
}
/**
* Check if there are new or updated notes since the last check.
*
* Saves the new syncstate to the database.
* Getting the syncstate (updateCount) is a much less expensive call
* than searching the notes for tagged items.
*
* This will retrieve a SyncState object and check the updateCount:
* object \EDAM\NoteStore\SyncState
* public 'currentTime' => int 1421181104176
* public 'fullSyncBefore' => int 1421087557000
* public 'updateCount' => int 20
* public 'uploaded' => int 34066
*
* @return bool
* TRUE if there are new or updated items. Otherwise FALSE.
*
* @see https://dev.evernote.com/doc/articles/polling_notification.php
*/
public function evernote_syncstate() {
$noteStore = $this->client->getUserNotestore();
$syncState = $noteStore->getSyncState($this->userinfo['oauth_token']);
$currentcount = $syncState->updateCount;
if ($currentcount > $this->userinfo['updates']) {
// Save the current count to the db.
$this->update_user_updates($currentcount);
$this->userinfo['updates'] = $currentcount;
return TRUE;
}
return FALSE;
}
/**
* Update the 'updates' field in devernote_users.
*
* This contains the last update count from evernote.
*
* @param int $count
*/
public function update_user_updates($count) {
global $user;
$num_updated = db_update('devernote_user')
->fields(array(
'updates' => $count,
))
->condition('uid', $user->uid)
->execute();
}
/**
* Make sure the $userinfo is valid.
*
* For example, oauth_token is set and hasn't expired.
*
* @return boolean
* TRUE if valid, otherwise FALSE.
*/
public function validate_userinfo() {
$valid = FALSE;
if (isset($this->userinfo['oauth_token']) && (strval($this->userinfo['oauth_token']) != '0')) {
$valid = $this->validate_notestoreurl();
$valid = $this->validate_token_date();
}
return $valid;
}
/**
* Check if DEVERNOTE_SANDBOX is different from edam_noteStoreUrl in the db.
*
* In other words, did we start off using the sandbox, grant authorization
* which was saved to the db, and then change to production. If so,
* the if statement will be false and we'll assign an empty array to
* $userinfo so that we are forced to reauthorize.
*
* @return boolean
* TRUE if valid otherwise FALSE.
*/
public function validate_notestoreurl() {
$url = isset($this->userinfo['edam_noteStoreUrl']) ? $this->userinfo['edam_noteStoreUrl'] : '';
$sandboxurl = strstr($url, 'sandbox') ? TRUE : FALSE;
if ($sandboxurl === DEVERNOTE_SANDBOX) {
return TRUE;
}
else {
return FALSE;
}
}
/**
* Check if the oauth token has expired.
*
* By default these are good for one year.
*
* @return boolean
* TRUE if valid otherwise FALSE (expired).
*/
public function validate_token_date() {
$valid = FALSE;
if ((time() - (60 * 60 * 24)) < $this->userinfo['edam_expires']) {
$valid = TRUE;
}
return $valid;
}
/**
* Get the tag_guid to use for retrieving notes from Evernote.
*
* @return mixed
* String containing the guid if successful otherwise FALSE.
*/
public function get_tag_guid($tag_name) {
if (isset($this->userinfo['tag_guid']) && ($this->userinfo['tag_guid'])) {
return $this->userinfo['tag_guid'];
} else {
$notestore = $this->client->getUserNotestore();
$tags = $notestore->listTags($this->userinfo['oauth_token']);
$tag_guid = FALSE;
if (count($tags)) {
foreach ($tags as $tag) {
if ($tag->name == $tag_name) {
global $user;
$tag_guid = $tag->guid;
$num_updated = db_update('devernote_user')
->fields(array(
'tag_guid' => $tag_guid,
))
->condition('uid', $user->uid)
->execute();
}
}
}
return $tag_guid;
}
}
/**
* Decrypt the token.
*
* @param string $token
* The oauth token provided by Evernote.
*/
public function decrypt_token($token) {
$enc_method = variable_get('devernote_enc_method', '');
if (($enc_method) && $enc_method == 'aes') {
$token = aes_decrypt($token);
}
elseif (($enc_method) && $enc_method == 'encrypt') {
$token = decrypt($token);
}
return $token;
}
/**
* Get the encrypted token.
*
* @return string $token
* The oauth token provided by Evernote, encrypted if possible.
*/
public function encrypt_token($token) {
if (module_exists('aes')) {
$token = aes_encrypt($token);
variable_set('devernote_enc_method', 'aes');
}
elseif (module_exists('encrypt')) {
$token = encrypt($token);
variable_set('devernote_enc_method', 'encrypt');
}
else {
variable_set('devernote_enc_method', 'none');
}
return $token;
}
/**
* Authorize with Evernote.
*
* If successful, $oauth_data will be an array of:
* 'oauth_token' => string 'S=s1:U=8b7:E=26ab546123s:C=1535fb4e520:P=185:A=jsmith-5428:V=2:H=3bg2ef3deb26cz40b04c597f986cb2r0'
* 'oauth_token_secret' => string ''
* 'edam_shard' => string 's1'
* 'edam_userId' => string '5719'
* 'edam_expires' => string '1489135604302'
* 'edam_noteStoreUrl' => string 'https://www.evernote.com/shard/s1/notestore'
* 'edam_webApiUrlPrefix' => string 'https://www.evernote.com/shard/s1/'
*
* @return boolean
* TRUE if the user was authorized otherwise FALSE.
*/
public function authorize_user() {
$keys = devernote_load_keys();
if (!$keys) {
$this->errors[] = 'Missing api keys. Please set them on the devernote settings page.';
return FALSE;
}
$oauth_handler = new \Evernote\Auth\OauthHandler(DEVERNOTE_SANDBOX);
global $base_url;
$callback = $base_url . request_uri();
try {
// See above for contents of $oauth_data.
$oauth_data = $oauth_handler->authorize($keys['consumer_key'], $keys['secret_key'], $callback);
if ($oauth_data) {
$this->userinfo['oauth_token'] = $oauth_data['oauth_token'];
$this->userinfo['edam_userId'] = $oauth_data['edam_userId'];
$this->userinfo['edam_noteStoreUrl'] = $oauth_data['edam_noteStoreUrl'];
$this->userinfo['edam_expires'] = $oauth_data['edam_expires'];
return TRUE;
}
return FALSE;
}
catch (Evernote\Exception\AuthorizationDeniedException $e) {
// If the user declines the authorization, an exception is thrown.
$this->exception = $e;
$this->errors[] = 'Authorization declined.';
return FALSE;
}
}
/**
* Retrieve notes based on a supplied tag_guid.
*
* Retrieved notes will be processed via process_note().
* The processed notes will then be saved via save_node() and save_note().
*
* @param string $tag_guid
* Unique evernote guid fot the tag.
*
* @param array $conversions
* An associative array of cleanup options. Can contain:
* - mappings: array of font size => h tag. For example:
* array('11' => 'h4', '12' => 'h3')
* - 'div2p' => TRUE
* If set to TRUE divs will be converted to p tags.
* (Evernote exports each paragraph as a div).
*
* @param array $node_settings
* Settings to use when saving notes as nodes.
* These are provided by the import form and retrieved from the $_POST var.
* 'status' => 1 - the status to set for the node.
* 'promote' => 1 - promoted to front page or not.
* 'comments' => 1 - whether or not to allow comments.
* 'import_type' => 'article' - Node type to create.
* 'input_format' => 'full_html' - 'full_html', 'plain_text', etc.
*
* @return array
* An array of html links linking to the newly created nodes.
*/
public function retrieve_tagged_notes($tag_guid, $conversions, $node_settings) {
$notes = array();
$filter = new \EDAM\NoteStore\NoteFilter();
$filter->tagGuids = array($tag_guid);
$resultSpec = new \EDAM\NoteStore\NotesMetadataResultSpec();
$notesMetadataList = $this->client->getUserNotestore()->findNotesMetadata($this->userinfo['oauth_token'], $filter, 0, 100, $resultSpec);
$imported = FALSE;
if (count($notesMetadataList->notes)) {
// Load the guids of previously imported notes.
$guids = $this->load_imported_notes();
$nodes = array();
foreach ($notesMetadataList->notes as $noteMetadata) {
// Only import the node if we haven't already imported it.
if (!in_array($noteMetadata->guid, $guids)) {
$imported = TRUE;
$note = $this->client->getNote($noteMetadata->guid);
// Apply any selected conversions to the note/html.
$body = $this->process_note($note, $conversions);
$node_settings['title'] = $note->getTitle();
$node_settings['body'] = $body;
$node_settings['note_guid'] = $note->getGuid();
$nid = $this->save_node($node_settings);
$this->save_note($noteMetadata->guid, $nid);
// TODO move to theme layer.
$notes[] = '<p>' . l($node_settings['title'], 'node/' . $nid) . '</p>';
}
}
}
return $notes;
}
/**
* Process an incoming evernote Note so it can be saved as a node.
*
* Also processes any embedded images.
* For additional methods and attributes of a Note object see:
* /sites/all/libraries/composer/evernote/evernote-cloud-sdk-php/src/Evernote/Model/Note.php
*
* @param Note $note
* An evernote sdk Note object. See link path above.
*
* @param array $conversions
* See retrieve_tagged_notes() for details.
*
* @return string
* An html version of the note, useful for saving as the body of a node.
*/
public function process_note($note, $conversions) {
$body = $note->content->toHtml();
// TODO verify these are images.
$resources = $note->getResources();
if (count($resources)) {
foreach ($resources as $resource) {
// Retrieve the image from evernote and save it locally.
$fileinfo = _devernote_save_resource($resource, $this->userinfo['edam_noteStoreUrl'], $this->userinfo['oauth_token']);
if (($fileinfo) && isset($fileinfo['extension'])) {
$replace = '/images/' . $fileinfo['filename_md5'] . '.' . $fileinfo['extension'];
if (isset($fileinfo['path_imagestyle'])) {
$url = $fileinfo['path_imagestyle'];
}
else {
$path = file_stream_wrapper_get_instance_by_uri('public://')->getDirectoryPath() . DIRECTORY_SEPARATOR . 'devernote' . DIRECTORY_SEPARATOR . $fileinfo['filename'];
$url = file_create_url($path);
}
$body = str_ireplace($replace, $url, $body);
}
}
}
if (count($conversions)) {
$body = $this->cleanup_html($body, $conversions);
}
return $body;
}
/**
* Saves authorization information to the db.
*/
public function save_userinfo() {
global $user;
// Convert to seconds from milliseconds as provided by Evernote.
$digits = strlen((string) $this->userinfo['edam_expires']);
if ($digits == 13) {
$this->userinfo['edam_expires'] = (int) $this->userinfo['edam_expires'] / 1000;
}
$token = $this->encrypt_token($this->userinfo['oauth_token']);
// The tag_guid will be retrieved and saved during the import process.
$tag_guid = isset($this->userinfo['tag_guid']) ? $this->userinfo['tag_guid'] : 0;
db_merge('devernote_user')
->key(array('uid' => $user->uid))
->fields(array(
'oauth_token' => $token,
'notestoreurl' => $this->userinfo['edam_noteStoreUrl'],
'expires' => (int) $this->userinfo['edam_expires'],
'updates' => $this->userinfo['updates'],
'tag' => $this->userinfo['tag'],
'tag_guid' => $this->userinfo['tag_guid'],
))
->execute();
}
/**
* Load the guids of all previously imported notes.
*
* @return array
* Array of note guids. Used to check if a note has already been imported.
*/
public function load_imported_notes() {
$guids = db_select('devernote_notes')
->fields('devernote_notes', array('note_guid'))
->execute()
->fetchCol();
return $guids;
}
/**
* Cleanup html retrieved from Evernote.
*
* For example, convert divs to p tags.
* Also map font size attributes to h tags.
*
* @param string $html
* The html to cleanup.
* @param array $cleanup
* An associative array of cleanup options. Can contain:
* - mappings: array of font size => h tag. For example:
* array('11' => 'h4', '12' => 'h3')
* - 'div2p' => TRUE
* If set to TRUE divs will be converted to p tags.
*
* @return string
* cleaned up/converted html.
*/
public function cleanup_html($html, $cleanup) {
$htags = isset($cleanup['htags']) && count($cleanup['htags']) ? TRUE : FALSE;
$div2p = isset($cleanup['div2p']) ? TRUE : FALSE;
// Replace spans containing a font-size with an h tag
// based on the mappings provided in $cleanup['htags'].
if ($htags) {
$dom = new DOMDocument();
$dom->loadHTML($html);
$spans = $dom->getElementsByTagName("span");
$replacements = array();
for ($i = $spans->length - 1; $i >= 0; $i--) {
$spannode = $spans->item($i);
if ($spannode->hasAttribute('style')) {
$attribute = $spannode->getAttribute('style');
if (stristr($attribute, 'font-size')) {
$pattern = '/font-size\s*?:.*?(;|(?=""|\'|;))/';
preg_match($pattern, $attribute, $match);
$pieces = explode(':', $match[0]);
// Trimming for pt and px because both come out of Evernote.
$size = trim($pieces[1], " pt;");
$size = trim($size, "px;");
// Lookup the h tag to use in place of the font-size.
if (array_key_exists($size, $cleanup['htags'])) {
$htag = $cleanup['htags'][$size];