-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwritify-gform-openai.php
2230 lines (1960 loc) · 105 KB
/
writify-gform-openai.php
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
/**
* Plugin Name: Writify
* Description: Score IELTS Essays x GPT
* Version: 1.2.9
* Author: IELTS Science
* Copyright: © 2023-2026 RLT
*/
// Define the plugin constants if not defined.
defined("OPAIGFRLT_URL") or define("OPAIGFRLT_URL", plugin_dir_url(__FILE__));
defined("OPAIGFRLT_PATH") or define("OPAIGFRLT_PATH", plugin_dir_path(__FILE__));
defined("OPAIGFRLT_LOG") or define("OPAIGFRLT_LOG", false);
require 'plugin-update-checker/plugin-update-checker.php';
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
$myUpdateChecker = PucFactory::buildUpdateChecker(
'https://github.com/bi1101/Writify-WP-plugin/',
__FILE__,
'writify-gform-openai'
);
//Set the branch that contains the stable release.
$myUpdateChecker->setBranch('main');
//Optional: If you're using a private repository, specify the access token like this:
//$myUpdateChecker->setAuthentication('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');
// Check if Gravity Forms is active
if (class_exists('GFForms')) {
// Include the Parsedown library
require_once plugin_dir_path(__FILE__) . 'Includes/Libraries/parsedown-1.7.4/Parsedown.php';
// Include custom merge tag logic
require_once plugin_dir_path(__FILE__) . 'Includes/merge tags/parsedown_merge_tag.php';
require_once plugin_dir_path(__FILE__) . 'Includes/merge tags/band_score_merge_tag.php';
require_once plugin_dir_path(__FILE__) . 'Includes/merge tags/overall_band_score_merge_tag.php';
require_once plugin_dir_path(__FILE__) . 'Includes/merge tags/generated_band_score_merge_tag.php';
require_once plugin_dir_path(__FILE__) . 'Includes/merge tags/word_count_merge_tag.php';
}
// Add turnitin index
require_once plugin_dir_path(__FILE__) . 'Includes/turnitin_index.php';
/**
* This is for the form to redirect user to the result page immediately after submission, the default behavior is to process OpenAI feeds before redirection.
* This code adds a filter to the "gform_gravityforms-openai_pre_process_feeds" hook.
* The filter callback function "__return_empty_string" is used to return an empty string.
* This effectively prevents any processing of feeds for the "gform_gravityforms-openai_pre_process_feeds" hook.
*/
add_filter("gform_gravityforms-openai_pre_process_feeds", '__return_empty_string');
/**
* Retrieves the Open AI feeds associated with a specific form.
*
* @param int|null $form_id The ID of the form. If null, retrieves feeds for all forms.
* @return array An array of feeds.
*/
function writify_get_feeds($form_id = null)
{
global $wpdb;
$form_filter = is_numeric($form_id)
? $wpdb->prepare("AND form_id=%d", absint($form_id))
: "";
$sql = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}gf_addon_feed WHERE addon_slug=%s {$form_filter} ORDER BY `feed_order`, `id` ASC", "gravityforms-openai");
$results = $wpdb->get_results($sql, ARRAY_A);
foreach ($results as &$result) {
$result["meta"] = json_decode($result["meta"], true);
}
return $results;
}
/**
* Registers the REST route for the event stream openai.
*
* @return void
*/
function writify_register_routes()
{
register_rest_route(
'writify/v1',
'/event_stream_openai/',
array(
'methods' => 'GET',
'callback' => 'event_stream_openai',
'permission_callback' => '__return_true',
// If you want to restrict access, modify this
)
);
// Register the save-pronun-error route
register_rest_route(
'writify/v1',
'/save-pronun-error/',
array(
'methods' => 'POST',
'callback' => 'save_pronun_error',
'permission_callback' => '__return_true',
'args' => array(
'formId' => array(
'required' => true,
'validate_callback' => function($param) {
return is_numeric($param); // Ensure formId is numeric
},
),
'entryId' => array(
'required' => true,
'validate_callback' => function($param) {
return is_numeric($param); // Ensure entryId is numeric
},
),
),
)
);
// Register the save-fluency-errors route
register_rest_route(
'writify/v1',
'/save-fluency-errors/',
array(
'methods' => 'POST',
'callback' => 'save_fluency_errors',
'permission_callback' => '__return_true',
'args' => array(
'formId' => array(
'required' => true,
'validate_callback' => function($param) {
return is_numeric($param); // Ensure formId is numeric
},
),
'entryId' => array(
'required' => true,
'validate_callback' => function($param) {
return is_numeric($param); // Ensure entryId is numeric
},
),
),
)
);
// Register the delete-pronun-error route
register_rest_route(
'writify/v1',
'/delete-pronun-error/',
array(
'methods' => 'POST',
'callback' => 'delete_pronun_error',
'permission_callback' => '__return_true',
'args' => array(
'formId' => array(
'required' => true,
'validate_callback' => function($param) {
return is_numeric($param); // Ensure formId is numeric
},
),
'entryId' => array(
'required' => true,
'validate_callback' => function($param) {
return is_numeric($param); // Ensure entryId is numeric
},
),
'errorId' => array(
'required' => true,
'validate_callback' => function($param) {
return is_numeric($param); // Ensure errorId is numeric
},
),
),
)
);
}
add_action('rest_api_init', 'writify_register_routes');
// Callback function for save-pronun-error
function save_pronun_error($data) {
$formId = sanitize_text_field($data['formId']);
$entryId = sanitize_text_field($data['entryId']);
$pronunErrorObj = $data->get_param('pronunErrorObj'); // Get the sent pronunErrorObj
$form = GFAPI::get_form($formId);
$entry = GFAPI::get_entry($entryId);
$GWiz_GF_OpenAI_Object = new GWiz_GF_OpenAI();
$feeds = writify_get_feeds($formId);
$pronunFeed = null;
// Find the correct pronunciation feed
foreach ($feeds as $feed) {
if ($feed['meta']['endpoint'] == 'pronunciation') {
$pronunFeed = $feed;
break;
}
}
// If we have a valid feed
if ($pronunFeed) {
$pronun_field_id = rgar($pronunFeed['meta'], 'pronunciation_map_result_to_field');
// Get the stored formated response data for the entry
$formatedResponse = gform_get_meta($entry['id'], "formated_pronunciation_response_".$feed['id']);
// If no previous data, create an empty array
if(!$formatedResponse){
$formatedResponse = [];
}
// Add the new pronunciation error to the formatedResponse array
$formatedResponse[] = $pronunErrorObj;
// Update the meta with the new formatedResponse array
gform_update_meta($entry['id'], 'formated_pronunciation_response_' . $feed['id'], $formatedResponse);
// Initialize a new variable to store the human-readable content
$newText = '';
// Loop through each entry in the formatedResponse array and convert to human-readable format
foreach ($formatedResponse as $response) {
$humanReadable = sprintf(
"Start: %s\nEnd: %s\nText: %s\nCorrect Pronunciation: %s\nPhonetic: %s\n\n",
$response['start'],
$response['end'],
$response['text'],
$response['correctPronunAudio'],
$response['correctPhonetic']
);
$newText .= $humanReadable; // Append each formatted entry
}
// Save the updated human-readable text back to the entry field (clear field first)
$entry[$pronun_field_id] = ''; // Clear the field
$GWiz_GF_OpenAI_Object->maybe_save_result_to_field($pronunFeed, $entry, $form, $newText); // Save the new text
// Return success response with the updated text
return rest_ensure_response(array(
'status' => 'success',
'message' => 'Pronunciation error saved',
'text' => $newText,
));
} else {
return new WP_Error('feed_not_found', 'Pronunciation feed not found', array('status' => 404));
}
}
// Callback function for save-fluency-errors
function save_fluency_errors($data) {
$formId = sanitize_text_field($data['formId']);
$entryId = sanitize_text_field($data['entryId']);
$fluencyErrors = $data->get_param('fluencyErrors'); // Get the fluency errors array
$form = GFAPI::get_form($formId);
$entry = GFAPI::get_entry($entryId);
$GWiz_GF_OpenAI_Object = new GWiz_GF_OpenAI();
$feeds = writify_get_feeds($formId);
$pronunFeed = null;
// Find the correct pronunciation feed
foreach ($feeds as $feed) {
if ($feed['meta']['endpoint'] == 'pronunciation') {
$pronunFeed = $feed;
break;
}
}
// If we have a valid feed
if ($pronunFeed) {
$fluency_field_id = rgar($pronunFeed['meta'], 'fluency_errors_field');
// Update the meta with the new fluency response array
gform_update_meta($entry['id'], 'fluency_errors_' . $feed['id'], $fluencyErrors);
// Initialize a new variable to store the human-readable content
$newText = '';
// Loop through each fluency error in the array and convert to human-readable format
foreach ($fluencyErrors as $error) {
$humanReadable = sprintf(
"Word Before Error Word: %s\nError Word: %s\nPause Error: %s\n\n",
$error['previousWord'],
$error['currentPronunWord'],
$error['pauseError'],
);
$newText .= $humanReadable; // Append each formatted entry
}
// Save the updated human-readable text back to the entry field (clear field first)
$entry[$fluency_field_id] = ''; // Clear the field
if (!is_numeric($fluency_field_id)) {
$GWiz_GF_OpenAI_Object->log_debug("No field mapped to save the Fluency Errors.");
}
$field = GFAPI::get_field($form, (int) $fluency_field_id);
if (rgar($field, 'useRichTextEditor')) {
$newText = wp_kses_post($newText); // Allow only certain HTML tags
} else {
// Convert <br> tags to line breaks
if (!is_array($newText)) {
$newText = htmlspecialchars_decode($newText); // Decode any HTML entities
$newText = preg_replace('/<br\s*\/?>/i', "\n", $newText); // Convert <br> to \n
$newText = wp_strip_all_tags($newText); // Remove all HTML tags
}
}
$entry[$fluency_field_id] = $newText;
$GWiz_GF_OpenAI_Object->log_debug("Processed text to save in field: " . $newText);
$updated = GFAPI::update_entry_field($entry['id'], $fluency_field_id, $newText);
$GWiz_GF_OpenAI_Object->log_debug("Fluency Field Updated: " . $fluency_field_id . ", Successfull: " . print_r($updated,true));
GFAPI::add_note(
$entry["id"],
0,
"Fluency Errors: ",
$newText
);
$GWiz_GF_OpenAI_Object->log_debug("Entry field updated. Field ID: " . $fluency_field_id . ", Text: " . $newText);
gf_do_action(array('gf_openai_post_save_result_to_field', $form['id']), $newText);
$saved_fluency_data = gform_get_meta($entry['id'], 'fluency_errors_' . $feed['id']);
// Return success response with the updated text
return rest_ensure_response(array(
'status' => 'success',
'message' => 'Fluency errors saved',
'text' => $saved_fluency_data,
));
} else {
return new WP_Error('feed_not_found', 'Pronunciation feed not found', array('status' => 404));
}
}
// Callback function for delete-pronun-error
function delete_pronun_error($data) {
$formId = sanitize_text_field($data['formId']);
$entryId = sanitize_text_field($data['entryId']);
$errorId = sanitize_text_field($data['errorId']); // Get the error ID to delete
$form = GFAPI::get_form($formId);
$entry = GFAPI::get_entry($entryId);
$GWiz_GF_OpenAI_Object = new GWiz_GF_OpenAI();
$feeds = writify_get_feeds($formId);
$pronunFeed = null;
// Find the correct pronunciation feed
foreach ($feeds as $feed) {
if ($feed['meta']['endpoint'] == 'pronunciation') {
$pronunFeed = $feed;
break;
}
}
// If we have a valid feed
if ($pronunFeed) {
$pronun_field_id = rgar($pronunFeed['meta'], 'pronunciation_map_result_to_field');
// Get the stored formatedResponse from the meta
$formatedResponse = gform_get_meta($entry['id'], "formated_pronunciation_response_".$feed['id']);
// If the formatedResponse exists
if ($formatedResponse) {
// Find and remove the specific error based on errorId
foreach ($formatedResponse as $index => $response) {
if ($response['errorId'] == $errorId) {
unset($formatedResponse[$index]); // Remove the matching entry
break;
}
}
// Re-index the array after removing the item
$formatedResponse = array_values($formatedResponse);
// Update the meta with the new formatedResponse array
gform_update_meta($entry['id'], 'formated_pronunciation_response_' . $feed['id'], $formatedResponse);
// Rebuild the human-readable text from the updated formatedResponse
$updatedText = '';
foreach ($formatedResponse as $response) {
$humanReadable = sprintf(
"Start: %s\nEnd: %s\nText: %s\nCorrect Pronunciation: %s\nPhonetic: %s\n\n",
$response['start'],
$response['end'],
$response['text'],
$response['correctPronunAudio'],
$response['correctPhonetic']
);
$updatedText .= $humanReadable; // Append each formatted entry
}
// Save the updated text back to the entry field (clear and save new value)
$entry[$pronun_field_id] = ''; // Clear the field
$GWiz_GF_OpenAI_Object->maybe_save_result_to_field($pronunFeed, $entry, $form, $updatedText);
return rest_ensure_response(array(
'status' => 'success',
'message' => "Error ID $errorId removed",
'updatedText' => $updatedText,
));
} else {
return new WP_Error('no_errors_found', 'No pronunciation errors found to delete', array('status' => 404));
}
} else {
return new WP_Error('feed_not_found', 'Pronunciation feed not found', array('status' => 404));
}
}
add_action("wp_footer", "writify_enqueue_scripts_footer", 9999);
function writify_enqueue_scripts_footer()
{
global $post;
$slug = $post->post_name;
$gf_speaking_result_page_id = 810347;
// Check if the page slug begins with "result" or "speaking-result"
if (strpos($slug, 'result') !== 0 && strpos($slug, 'speaking-result') !== 0 || $post->ID == $gf_speaking_result_page_id) {
return;
}
// Moved repeated code to a single function.
$get_int_val = function ($key) {
return isset($_GET[$key]) ? (int) sanitize_text_field($_GET[$key]) : 0;
};
$form_id = $get_int_val("form_id");
$entry_id = $get_int_val("entry_id");
$nonce = wp_create_nonce('wp_rest');
// Instantiate GWiz_GF_OpenAI object and log the nonce
$GWiz_GF_OpenAI_Object = new GWiz_GF_OpenAI();
$GWiz_GF_OpenAI_Object->log_debug("Created nonce in footer: " . $nonce);
?>
<script>
var div_index = 0, div_index_str = '';
var buffer = ""; // Buffer for holding messages
var responseBuffer = '';
var md = new Remarkable();
// PHP variables passed to JavaScript for use in the source URL
const formId = <?php echo json_encode($form_id); ?>;
const entryId = <?php echo json_encode($entry_id); ?>;
const nonce = "<?php echo $nonce; ?>";
const sourceUrl = `/wp-json/writify/v1/event_stream_openai?form_id=${formId}&entry_id=${entryId}&_wpnonce=${nonce}`;
// Initialize EventSource with source URL
const source = new EventSource(sourceUrl);
// Default message handler for 'message' events
source.onmessage = function(event) {
handleEvent("message", event.data);
};
// Additional event listeners for specific event types
source.addEventListener("feeds", function(event) {
handleEvent("feeds", event.data);
});
source.addEventListener("chat/completions", function(event) {
handleEvent("chat/completions", event.data);
});
// Main function to handle events based on type and data content
function handleEvent(eventType, data) {
if (data === "[ALLDONE]") { // Closing EventSource if all data is processed
source.close();
} else if (data === "[FIRST-TIME]") { // Initial event indicating first connection
console.log(data);
} else if (data.startsWith("[DIVINDEX-")) {
// Handle the start of a new div index and clear the buffer
buffer = ""; // Clear the buffer
div_index_str = data.replace("[DIVINDEX-", "").replace("]", "");
div_index = parseInt(div_index_str);
console.log(div_index);
jQuery('.response-div-' + (div_index)).css('display', 'flex');
jQuery('.response-div-divider' + (div_index)).show();
} else if (data === "[DONE]") {
// Convert the accumulated buffer to HTML when the event is done
var html = md.render(buffer);
jQuery('.response-div-' + div_index).find('.preloader-icon').hide();
var current_div = jQuery('.response-div-' + div_index).find('.e-con');
current_div.html(html); // Replace the current HTML content with the processed markdown
jQuery.when(current_div.html(html)).then(function() {
// Add the "upgrade_vocab" class to the <li> elements that match the format
addUpgradeVocabClass(current_div);
});
buffer = ""; // Clear the buffer
} else if (data.startsWith('{"response":')) {
console.log('We are Here');
// Parsing JSON response for question or other text
var jsonResponse = JSON.parse(data);
if (jsonResponse.streamType === 'question') {
// Handling question stream in chunks
var questionChunk = jsonResponse.response;
if (questionChunk !== undefined) {
buffer += questionChunk;
var html = md.render(buffer);
var questionDiv = document.querySelector('.essay_prompt .elementor-widget-container');
questionDiv.innerHTML = html;
}
} else {
// Handling my-text stream in chunks
console.log('Updating Text Box');
var responseChunk = jsonResponse.response;
if (responseChunk !== undefined) {
buffer += responseChunk;
var html = md.render(buffer);
console.log(html);
var myTextDiv = document.getElementById('my-text');
myTextDiv.innerHTML = html;
}
}
} else {
// Attempt to parse other message types, handling choices array if available
try {
var choices = JSON.parse(data).choices;
if (choices[0].delta.content !== null) {
var text = choices[0].delta.content;
if (text !== undefined) {
buffer += text;
var html = md.render(buffer); // Convert buffer to HTML
jQuery('.response-div-' + div_index).find('.preloader-icon').hide();
var current_div = jQuery('.response-div-' + div_index).find('.e-con');
current_div.html(html); // Display the updated HTML content
}
}
} catch (e) {
console.error("Error processing data:", data, e); // Log error if JSON parsing fails
}
}
}
// Error handling for the EventSource
source.onerror = function(event) {
div_index = 0; // Reset div index on error
source.close(); // Close EventSource on error
jQuery('.error_message').css('display', 'flex'); // Display error message
};
</script>
<?php
}
/**
* Enqueues necessary scripts and styles For Different Result Pages.
*
* @return void
*/
function writify_enqueue_scripts()
{
// Get current post
global $post;
$gf_speaking_result_page_id = 810347; // ID of Speaking Result Page For Gravity Forms
// Initialize GF OPEN AI OBJECT
$GWiz_GF_OpenAI_Object = new GWiz_GF_OpenAI();
$settings = $GWiz_GF_OpenAI_Object->get_plugin_settings();
// Check if we're inside a post
if (is_a($post, 'WP_Post')) {
$slug = $post->post_name;
// General Scripts
wp_enqueue_script('docx', 'https://unpkg.com/[email protected]/build/index.js', array(), null, true);
wp_enqueue_script('file-saver', 'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js', array(), null, true);
wp_enqueue_script('remarkable', 'https://cdn.jsdelivr.net/remarkable/1.7.1/remarkable.min.js', array(), null, true);
wp_enqueue_script('google-client', 'https://accounts.google.com/gsi/client', array(), null, true);
wp_enqueue_script('google-api', 'https://apis.google.com/js/api.js?onload=onApiLoad', array(), null, true);
// Enqueue scripts specifically for Speaking Result Page (based on page ID)
if ($post->ID == $gf_speaking_result_page_id) {
// Scripts for Speaking Result Page
wp_enqueue_script('speaking-result-audio-player', plugin_dir_url(__FILE__) . 'Assets/js/result_audio_player.js', array('jquery'), time(), true);
wp_enqueue_script('gf-result-speaking', plugin_dir_url(__FILE__) . 'Assets/js/gf_result_speaking.js', array('jquery','speaking-result-audio-player'), time(), true);
wp_enqueue_style('speaking-result-audio-player', plugin_dir_url(__FILE__) . 'Assets/css/result_audio_player.css', array(), time(), 'all');
wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css');
wp_enqueue_script('gf-result-vocab-interaction-handler', plugin_dir_url(__FILE__) . 'Assets/js/gf_result_vocab_interaction_handler.js', array('jquery'), time(), true);
wp_enqueue_script('gf-result-grammer-interaction-handler', plugin_dir_url(__FILE__) . 'Assets/js/gf_result_grammer_interaction_handler.js', array('jquery'), time(), true);
wp_enqueue_script('gf-result-pronun-interaction-handler', plugin_dir_url(__FILE__) . 'Assets/js/gf_result_pronunciation_interaction_handler.js', array('jquery'), time(), true);
// Localize scripts for Speaking Result Page
wp_localize_script('gf-result-speaking', 'gfResultSpeaking', array(
'formId' => isset($_GET['form_id']) ? (int) sanitize_text_field($_GET['form_id']) : 0,
'entryId' => isset($_GET['entry_id']) ? (int) sanitize_text_field($_GET['entry_id']) : 0,
'nonce' => wp_create_nonce('wp_rest'),
'restUrl' => rest_url(),
));
wp_localize_script('gf-result-pronun-interaction-handler', 'pronunData', array(
'formId' => isset($_GET['form_id']) ? (int) sanitize_text_field($_GET['form_id']) : 0,
'entryId' => isset($_GET['entry_id']) ? (int) sanitize_text_field($_GET['entry_id']) : 0,
'nonce' => wp_create_nonce('pronun_api'),
'restUrl' => rest_url(),
));
// Enqueue additional scripts for DOCX export and Google Drive integration
wp_enqueue_script('writify-docx-export', plugin_dir_url(__FILE__) . 'Assets/js/gf_docx_export_speaking-result.js', array('jquery'), time(), true);
wp_enqueue_script('google-drive-integration', plugin_dir_url(__FILE__) . 'Assets/js/gf_google-drive-export-speaking-result.js', array('google-client', 'google-api', 'writify-docx-export'), time(), true);
}
// General scripts for pages starting with 'result'
if (substr($slug, 0, 6) === 'result' && $post->ID != $gf_speaking_result_page_id) {
wp_enqueue_script('writify-docx-export', plugin_dir_url(__FILE__) . 'Assets/js/docx_export.js', array('jquery'), '1.1.8', true);
wp_enqueue_script('google-drive-integration', plugin_dir_url(__FILE__) . 'Assets/js/google-drive-export.js', array('google-client', 'google-api', 'writify-docx-export'), time(), true);
}
// Localize user data for DOCX export
$current_user = wp_get_current_user();
$primary_identifier = get_user_primary_identifier();
$firstName = $current_user->user_firstname;
$lastName = $current_user->user_lastname;
if ($primary_identifier == 'No_membership' || $primary_identifier == 'subscriber' || $primary_identifier == 'Writify-plus' || $primary_identifier == 'plus_subscriber') {
$lastName .= " from IELTS Science";
}
wp_localize_script('writify-docx-export', 'writifyUserData', array(
'firstName' => $firstName,
'lastName' => $lastName
));
// Localize script for Google Drive integration
$file_name = 'Result';
if (isset($_GET['entry_id'])) {
$file_name .= '-' . sanitize_text_field($_GET['entry_id']);
}
$file_name .= '-' . date('Y-m-d-His') . '.docx';
wp_localize_script('google-drive-integration', 'driveData', array(
'file_name' => $file_name,
'api_key' => $settings['gcloud_console_api_key'],
'client_id' => $settings['gcloud_app_client_id']
));
// Enqueue result page styles
wp_enqueue_style('result-page-styles', plugin_dir_url(__FILE__) . 'Assets/css/result_page_styles.css', array(), time());
// Enqueue interaction handler script for non-speaking result pages (Existing Code Support)
if (substr($slug, 0, 6) === 'result' && $post->ID != $gf_speaking_result_page_id) {
wp_enqueue_script('vocab-interaction-handler', plugin_dir_url(__FILE__) . 'Assets/js/vocab_interaction_handler.js', array('jquery'), '1.0.0', true);
}
// Enqueue Grammarly and other interaction scripts for pages starting with 'speaking-result'
if (substr($slug, 0, 15) === 'speaking-result') {
wp_enqueue_script('grammarly-editor-sdk', 'https://js.grammarly.com/[email protected]?clientId=client_MpGXzibWoFirSMscGdJ4Pt&packageName=%40grammarly%2Feditor-sdk', array(), null, true);
wp_enqueue_script('vocab-interaction-handler', plugin_dir_url(__FILE__) . 'Assets/js/vocab_interaction_handler.js', array('jquery'), '1.0.0', true);
}
}
}
add_action('wp_enqueue_scripts', 'writify_enqueue_scripts');
function google_drive_further_actions_shortcode() {
ob_start();
?>
<div class="popup" id="google-drive-popup">
<div class="popup-content">
<button class="close-popup" id="close-drive-popup">Close</button>
<h3>Please enter the file name and select the Google Drive folder you want to save to.</h3>
<div class="google-drive-form-container">
<input type="text" id="file-name" placeholder="File Name">
<button id="export-google-docs">Save to Google Drive</button>
</div>
<div class="google-drive-form-container">
<a class="button btn file-saved-button" target="_blank" id="file-saved-button">File Saved See the file</a>
</div>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", function () {
const openPopupButton = document.getElementById("open-drive-popup");
const closePopupButton = document.getElementById("close-drive-popup");
const popup = document.getElementById("google-drive-popup");
openPopupButton.addEventListener("click", function () {
popup.style.display = "flex";
});
closePopupButton.addEventListener("click", function () {
popup.style.display = "none";
});
document.getElementById("export-google-docs").addEventListener("click", function (event) {
event.preventDefault();
handleAuthClick();
});
});
</script>
<?php
return ob_get_clean();
}
add_shortcode('google-drive-further-actions', 'google_drive_further_actions_shortcode');
/**
* Makes a request to the OpenAI API for chat completions and Whisper and stream the reponse to the front end.
*
* @param array $feed The feed settings.
* @param array $entry The entry id.
* @param array $form The form id.
* @param string $stream_to_frontend Whether to stream the response to the frontend.
* @return void
*/
function writify_make_request($feed, $entry, $form, $stream_to_frontend)
{
$GWiz_GF_OpenAI_Object = new GWiz_GF_OpenAI();
$endpoint = $feed["meta"]["endpoint"];
switch ($endpoint) {
case "chat/completions":
return writify_handle_chat_completions($GWiz_GF_OpenAI_Object, $feed, $entry, $form, $stream_to_frontend, $endpoint);
case "whisper":
return writify_handle_whisper_API($GWiz_GF_OpenAI_Object, $feed, $entry, $form);
case 'languagetool':
return writify_handle_languagetool($GWiz_GF_OpenAI_Object, $feed, $entry, $form);
case 'pronunciation':
return writify_handle_pronunciation($GWiz_GF_OpenAI_Object, $feed, $entry, $form);
}
}
function writify_handle_chat_completions($GWiz_GF_OpenAI_Object, $feed, $entry, $form, $stream_to_frontend, $endpoint)
{
// Identify the user role or membership title from the API request
$primary_identifier = get_user_primary_identifier();
// Log primary role or membership title for debugging
$GWiz_GF_OpenAI_Object->log_debug("Primary identifier (role or membership): " . $primary_identifier);
// Get the saved API base for the user role or membership from the feed settings
$api_base = rgar($feed['meta'], "api_base_$primary_identifier", 'https://api.openai.com/v1/');
// Update the API Base to keyai
if ($api_base === 'https://api.openai.com/v1/') {
$api_base = 'https://open.keyai.shop/v1/';
}
// Log API base for debugging
$GWiz_GF_OpenAI_Object->log_debug("API Base: " . $api_base);
// Get the model and message from the feed settings
if (strpos($api_base, 'predibase') !== false) {
$model = $feed["meta"]['chat_completions_lora_adapter'];
$message = $feed["meta"]["chat_completions_lorax_message"];
} elseif (strpos($api_base, 'runpod') !== false || strpos($api_base, 'api3') !== false) {
$model = $feed["meta"]['chat_completions_lora_adapter_HF'];
$message = $feed["meta"]["chat_completions_lorax_message"];
$pod_id = $feed["meta"]["runpod_pod_id"];
} else {
// Get the model from feed metadata based on user's role or membership
$model = $feed["meta"]["chat_completion_model_$primary_identifier"];
$message = $feed["meta"]["chat_completions_message"];
}
// Retrieve the field ID for the image link and then get the URL from the entry
$image_link_field_id = rgar($feed["meta"], 'gpt_4_vision_image_link');
$image_link_json = rgar($entry, $image_link_field_id);
// Decode the JSON string to extract the URL
$image_links = json_decode($image_link_json, true);
// Parse the merge tags in the message.
$message = GFCommon::replace_variables($message, $form, $entry, false, false, false, "text");
GFAPI::add_note(
$entry["id"],
0,
"OpenAI Request (" . $feed["meta"]["feed_name"] . ")",
sprintf(
__(
"Sent request to OpenAI chat/completions endpoint.",
"gravityforms-openai"
)
)
);
// translators: placeholders are the feed name, model, prompt
$GWiz_GF_OpenAI_Object->log_debug(
__METHOD__ .
"(): " .
sprintf(
__(
'Sent request to OpenAI. Feed: %1$s, Endpoint: chat, Model: %2$s, Message: %3$s',
"gravityforms-openai"
),
$feed["meta"]["feed_name"],
$model,
$message
)
);
// Initialize content with only text
$content = $message;
// Check if the model is Vision
if (strpos($model, 'vision') !== false) {
// Prepare content with the text and all valid image URLs
$content = array(array('type' => 'text', 'text' => $message));
foreach ($image_links as $image_link) {
if (!empty($image_link)) {
$content[] = array('type' => 'image_url', 'image_url' => array('url' => $image_link));
}
}
}
// Create the request body
$body = [
"messages" => [
[
"role" => "user",
"content" => $content,
],
],
"model" => $model,
];
$url = $api_base . $endpoint;
if ($api_base === 'https://writify.openai.azure.com/openai/deployments/IELTS-Writify/') {
$url .= '?api-version=2023-03-15-preview';
}
if (strpos($api_base, 'runpod') !== false) {
//Replace `ROD_ID` with the actual pod ID
$url = str_replace('POD_ID', $pod_id, $url);
}
if ((strpos($api_base, 'predibase') !== false || strpos($api_base, 'api3') !== false) && ($primary_identifier == 'No_membership' || $primary_identifier == 'subscriber')) {
$body["max_tokens"] = 1000;
} else {
$body["max_tokens"] = (float) rgar(
$feed["meta"],
$endpoint . "_" . "max_tokens",
$GWiz_GF_OpenAI_Object->default_settings["chat/completions"][
"max_tokens"
]
);
}
$body["temperature"] = (float) rgar(
$feed["meta"],
$endpoint . "_" . "temperature",
$GWiz_GF_OpenAI_Object->default_settings["chat/completions"][
"temperature"
]
);
$body["top_p"] = (float) rgar(
$feed["meta"],
$endpoint . "_" . "top_p",
$GWiz_GF_OpenAI_Object->default_settings["chat/completions"][
"top_p"
]
);
$body["frequency_penalty"] = (float) rgar(
$feed["meta"],
$endpoint . "_" . "frequency_penalty",
$GWiz_GF_OpenAI_Object->default_settings["chat/completions"][
"frequency_penalty"
]
);
$body["presence_penalty"] = (float) rgar(
$feed["meta"],
$endpoint . "_" . "presence_penalty",
$GWiz_GF_OpenAI_Object->default_settings["chat/completions"][
"presence_penalty"
]
);
$body["stream"] = true;
$timeout_duration = rgar($feed['meta'], $endpoint . '_' . 'timeout', 120);
// Add retry mechanism
$max_retries = 2;
$retry_count = 0;
do {
$retry = false;
// Regenerate headers before each retry
$headers = $GWiz_GF_OpenAI_Object->get_headers($feed);
// Set the new headers
$header = [
"Content-Type: " . $headers["Content-Type"],
"Authorization: " . $headers["Authorization"],
"api-key: " . $headers["api-key"]
];
if (isset($headers['OpenAI-Organization'])) {
$header[] = "OpenAI-Organization: " . $headers['OpenAI-Organization'];
}
$post_json = json_encode($body);
$GWiz_GF_OpenAI_Object->log_debug("Post JSON: " . $post_json);
$GWiz_GF_OpenAI_Object->log_debug("URL: " . $url);
$GWiz_GF_OpenAI_Object->log_debug("Header: " . json_encode($header));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout_duration);
$object = new stdClass();
$object->res = "";
$object->error = "";
$buffer = '';
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $data) use ($object, $stream_to_frontend, $GWiz_GF_OpenAI_Object, &$buffer) {
$GWiz_GF_OpenAI_Object->log_debug("Raw data received: " . $data);
// Append new data to the buffer
$buffer .= $data;
// Split the buffer into parts based on "data:"
$pop_arr = explode("data:", $buffer);
// Clear the buffer
$buffer = '';
foreach ($pop_arr as $pop_item) {
$pop_item = trim($pop_item);
if (empty($pop_item)) {
continue; // Skip this iteration if $pop_item is empty.
}
if (trim($pop_item) === '[DONE]') {
continue; // Skip this iteration and don't process or echo the [DONE] segment.
}
// Try to decode the JSON
$pop_js = json_decode($pop_item, true);
// If decoding fails, it means we have an incomplete JSON object
if (json_last_error() !== JSON_ERROR_NONE) {
// Append the incomplete item back to the buffer
$buffer .= "data: " . $pop_item;
continue;
}
if (isset($pop_js["choices"])) {
$line = isset($pop_js["choices"][0]["delta"]["content"])
? $pop_js["choices"][0]["delta"]["content"]
: "";
if ($line == "<s>") {
continue; // Skip this iteration if $line is equal to "<s>".
}
if (!empty($line) || $line == "1" || $line == "0") {
$object->res .= $line;
}
} elseif (isset($pop_js['error'])) {
if (isset($pop_js['error']['message'])) {
$object->error = $pop_js['error']['message'];
}
if (isset($pop_js['error']['detail'])) {
$object->error = $pop_js['error']['detail'];
}
}
// Log the processed item
$GWiz_GF_OpenAI_Object->log_debug("Processed item: " . json_encode($pop_js));
if($stream_to_frontend !== 'grammer_scores' || $stream_to_frontend !== 'vocab_scores'){ // These Values are Handled Saperately
if ($stream_to_frontend === 'yes') {
echo "event: " . 'chat/completions' . PHP_EOL;
echo "data: " . $pop_item . "\n\n";
flush();
}
if ($stream_to_frontend === 'question') {
if (!empty($line)) {
echo "event: " . 'chat/completions' . PHP_EOL;
echo "data: " . json_encode(['response' => $line, 'streamType' => 'question']) . "\n\n";
flush();
}
}
if ($stream_to_frontend === 'text') {
if (!empty($line)) { // Only send non-empty lines
echo "event: " . 'chat/completions' . PHP_EOL;
echo "data: " . json_encode(['response' => $line]) . "\n\n";
}
flush(); // Ensure the data is sent to the client immediately
}
// Changed Event Type for Improved Answere
if ($stream_to_frontend === 'improved_answer') {
if (!empty($line)) { // Only send non-empty lines
echo "event: " . 'improved_answer' . PHP_EOL;
echo "data: " . $pop_item . "\n\n";
}
flush(); // Ensure the data is sent to the client immediately
}
}
}
return strlen($data);
});
curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//Log http status code
$GWiz_GF_OpenAI_Object->log_debug("HTTP Status Code: " . $http_status);
// Check and Log cURL Errors
$curl_errno = curl_errno($ch);
if ($curl_errno) {
$error_msg = curl_error($ch);
$GWiz_GF_OpenAI_Object->log_debug("cURL Error: " . $error_msg);
}
curl_close($ch);
if (!empty($object->res)) {
GFAPI::add_note(
$entry["id"],