-
-
Notifications
You must be signed in to change notification settings - Fork 471
Expand file tree
/
Copy pathGitHub_API.php
More file actions
916 lines (802 loc) · 23.4 KB
/
GitHub_API.php
File metadata and controls
916 lines (802 loc) · 23.4 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
<?php
/**
* Git Updater
*
* @author Andy Fragen
* @license GPL-3.0-or-later
* @link https://github.com/afragen/git-updater
* @package git-updater
*
* @phpcs:disable Squiz.Commenting.InlineComment.InvalidEndChar
*/
namespace Fragen\Git_Updater\API;
use Fragen\Singleton;
use stdClass;
/*
* Exit if called directly.
*/
if ( ! defined( 'WPINC' ) ) {
die;
}
/**
* Class GitHub_API
*
* Get remote data from a GitHub repo.
*
* @author Andy Fragen
*/
class GitHub_API extends API implements API_Interface {
/**
* Constructor.
*
* @param stdClass $type plugin|theme.
*/
public function __construct( $type = null ) {
parent::__construct();
$this->type = $type;
$this->response = [];
add_action( 'admin_init', [ $this, 'maybe_handle_oauth_flow' ] );
$this->settings_hook( $this );
$this->add_settings_subtab();
$this->add_install_fields( $this );
}
/**
* Read the remote file and parse headers.
*
* @param string $file Filename.
*
* @return bool
*/
public function get_remote_info( $file ) {
return $this->get_remote_api_info( 'github', "/repos/:owner/:repo/contents/{$file}" );
}
/**
* Get remote info for tags.
*
* @return bool
*/
public function get_remote_tag() {
return $this->get_remote_api_tag( 'github', '/repos/:owner/:repo/tags' );
}
/**
* Read the remote CHANGES.md file.
*
* @param string $changes The changelog filename - deprecated.
*
* @return bool
*/
public function get_remote_changes( $changes ) {
return $this->get_remote_api_changes( 'github', $changes, '/repos/:owner/:repo/contents/:changelog' );
}
/**
* Read and parse remote readme.txt.
*
* @return bool|void
*/
public function get_remote_readme() {
$this->get_remote_api_readme( 'github', '/repos/:owner/:repo/contents/:readme' );
}
/**
* Read the repository meta from API.
*
* @return bool
*/
public function get_repo_meta() {
return $this->get_remote_api_repo_meta( 'github', '/repos/:owner/:repo' );
}
/**
* Create array of branches and download links as array.
*
* @return bool
*/
public function get_remote_branches() {
return $this->get_remote_api_branches( 'github', '/repos/:owner/:repo/branches' );
}
/**
* Return the latest GitHub release asset URL.
*
* @return string|bool|void
*/
public function get_release_asset() {
// return $this->get_api_release_asset( 'github', '/repos/:owner/:repo/releases/latest' );
}
/**
* Return array of release assets.
*
* @return array
*/
public function get_release_assets() {
return $this->get_api_release_assets( 'github', '/repos/:owner/:repo/releases' );
}
/**
* Return list of repository assets.
*
* @return array
*/
public function get_repo_assets() {
return $this->get_remote_api_assets( 'github', '/repos/:owner/:repo/contents/:path' );
}
/**
* Return list of files at repo root.
*
* @return array
*/
public function get_repo_contents() {
return $this->get_remote_api_contents( 'github', '/repos/:owner/:repo/contents' );
}
/**
* Construct $this->type->download_link using Repository Contents API.
*
* @url http://developer.github.com/v3/repos/contents/#get-archive-link
*
* @param boolean $branch_switch for direct branch changing.
*
* @return string $endpoint
*/
public function construct_download_link( $branch_switch = false ) {
self::$method = 'download_link';
$download_link_base = $this->get_api_url( '/repos/:owner/:repo/zipball/', true );
$endpoint = '';
// Release asset.
if ( $this->use_release_asset( $branch_switch ) ) {
$release_assets = $this->get_release_assets();
if ( ! $release_assets ) {
return '';
}
$release_assets['assets'] = $release_assets['assets'] ?? [];
$release_asset = reset( $release_assets['assets'] );
/*
* Check if dev release asset is newer than latest release asset.
*
* @param bool
* @param $this->type Repo type object.
*/
if ( apply_filters( 'gu_dev_release_asset', false, $this->type ) ) {
$current_asset_version = array_key_first( $release_assets['assets'] ) ?? '';
$current_dev_asset_version = array_key_first( $release_assets['dev_assets'] ) ?? '';
if ( version_compare( $current_asset_version, $current_dev_asset_version, '<' ) ) {
$release_asset = reset( $release_assets['dev_assets'] );
}
}
if ( empty( $this->response['release_asset_download'] ) ) {
$this->set_repo_cache( 'release_asset_download', $release_asset );
}
if ( ! empty( $this->response['release_asset_download'] ) ) {
return $this->response['release_asset_download'];
}
return $this->get_release_asset_redirect( $release_asset, true );
}
/*
* If a branch has been given, use branch.
* If branch is primary branch (default) and tags are used, use newest tag.
*/
if ( $this->type->primary_branch !== $this->type->branch || empty( $this->type->tags ) ) {
$endpoint .= $this->type->branch;
} else {
$endpoint .= $this->type->newest_tag;
}
// Create endpoint for branch switching.
if ( $branch_switch ) {
$endpoint = $branch_switch;
}
$download_link = $download_link_base . $endpoint;
$download_link = apply_filters( 'gu_post_construct_download_link', $download_link, $this->type, $branch_switch );
return $download_link;
}
/**
* Create GitHub API endpoints.
*
* @param GitHub_API|API $git Git host specific API object.
* @param string $endpoint Endpoint.
*
* @return string $endpoint
*/
public function add_endpoints( $git, $endpoint ) {
switch ( $git::$method ) {
case 'file':
case 'readme':
case 'assets':
case 'changes':
$endpoint = add_query_arg( 'ref', $git->type->branch, $endpoint );
break;
case 'meta':
case 'tags':
case 'download_link':
case 'release_asset':
case 'translation':
break;
case 'branches':
$endpoint = add_query_arg( 'per_page', '100', $endpoint );
break;
default:
break;
}
/*
* If GitHub Enterprise return this endpoint.
*/
if ( ! empty( $git->type->enterprise_api ) ) {
return $git->type->enterprise_api . $endpoint;
}
return $endpoint;
}
/**
* Calculate and store time until rate limit reset.
*
* @param array $response HTTP headers.
* @param string $repo Repo name.
*
* @return int
*/
public static function ratelimit_reset( $response, $repo ) {
$headers = wp_remote_retrieve_headers( $response );
if ( empty( $headers ) ) {
return 60;
}
$data = $headers->getAll();
if ( isset( $data['x-ratelimit-reset'] ) ) {
$reset = (int) $data['x-ratelimit-reset'];
//phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
$wait = date( 'i', $reset - time() );
static::$error_code[ $repo ] = static::$error_code[ $repo ] ?? [];
static::$error_code[ $repo ] = array_merge( static::$error_code[ $repo ], [ 'wait' => $wait ] );
return $wait;
}
}
/**
* Parse API response call and return only array of tag numbers.
*
* @param stdClass|array $response Response from API call.
*
* @return stdClass|array $arr Array of tag numbers, object is error.
*/
public function parse_tag_response( $response ) {
if ( $this->validate_response( $response ) ) {
return $response;
}
$arr = [];
array_map(
function ( $e ) use ( &$arr ) {
$arr[] = $e->name;
return $arr;
},
(array) $response
);
return $arr;
}
/**
* Parse API response and return array of meta variables.
*
* @param stdClass|array $response Response from API call.
*
* @return array $arr Array of meta variables.
*/
public function parse_meta_response( $response ) {
if ( $this->validate_response( $response ) ) {
return $response;
}
$arr = [];
$response = [ $response ];
array_filter(
$response,
function ( $e ) use ( &$arr ) {
$arr['private'] = $e->private ?? false;
$arr['last_updated'] = $e->pushed_at ?? '';
$arr['added'] = $e->created_at ?? '';
$arr['watchers'] = $e->watchers ?? 0;
$arr['forks'] = $e->forks ?? 0;
$arr['open_issues'] = $e->open_issues ?? 0;
}
);
return $arr;
}
/**
* Parse API response and return array with changelog in base64.
*
* @param stdClass|array $response Response from API call.
*
* @return array $arr Array of changes in base64.
*/
public function parse_changelog_response( $response ) {
if ( $this->validate_response( $response ) ) {
return $response;
}
$arr = [];
$response = [ $response ];
array_filter(
$response,
function ( $e ) use ( &$arr ) {
$arr['changes'] = $e->content;
}
);
return $arr;
}
/**
* Parse API response and return array of branch data.
*
* @param stdClass $response API response.
*
* @return array Array of branch data.
*/
public function parse_branch_response( $response ) {
if ( $this->validate_response( $response ) ) {
return $response;
}
$branches = [];
foreach ( $response as $branch ) {
$branches[ $branch->name ]['download'] = $this->construct_download_link( $branch->name );
$branches[ $branch->name ]['commit_hash'] = $branch->commit->sha;
$branches[ $branch->name ]['commit_api'] = $branch->commit->url;
}
return $branches;
}
/**
* Parse release asset API response.
*
* @param stdClass $response API response.
*
* @return void
*/
public function parse_release_asset_response( $response ) {
if ( $this->validate_response( $response ) ) {
return;
}
if ( property_exists( $response, 'url' ) ) {
$this->set_repo_cache( 'release_asset_download', $response->url );
}
}
/**
* Parse tags and create download links.
*
* @param stdClass|array $response Response from API call.
* @param array $repo_type Array of repo data.
*
* @return array
*/
protected function parse_tags( $response, $repo_type ) {
$tags = [];
$download_base = implode(
'/',
[
$repo_type['base_uri'],
'repos',
$this->type->owner,
$this->type->slug,
'zipball/',
]
);
foreach ( (array) $response as $tag ) {
// Ignore leading 'v' and skip anything with dash or words.
if ( ! preg_match( '/[^v]+[-a-z]+/', $tag ) ) {
$tags[ $tag ] = $download_base . $tag;
}
}
uksort( $tags, fn ( $a, $b ) => version_compare( ltrim( $b, 'v' ), ltrim( $a, 'v' ) ) );
return $tags;
}
/**
* Parse remote root files/dirs.
*
* @param stdClass|array $response Response from API call.
*
* @return array
*/
protected function parse_contents_response( $response ) {
$files = [];
$dirs = [];
foreach ( $response as $content ) {
$content = (object) $content;
if ( property_exists( $content, 'type' ) && 'file' === $content->type ) {
$files[] = $content->name;
}
if ( property_exists( $content, 'type' ) && 'dir' === $content->type ) {
$dirs[] = $content->name;
}
}
return [
'files' => $files,
'dirs' => $dirs,
];
}
/**
* Parse remote assets directory.
*
* @param stdClass|array $response Response from API call.
*
* @return stdClass|array
*/
protected function parse_asset_dir_response( $response ) {
$assets = [];
if ( isset( $response->message ) || is_wp_error( $response ) ) {
return $response;
}
foreach ( $response as $asset ) {
if ( 'file' === $asset->type ) {
$assets[ $asset->name ] = $asset->download_url;
}
}
if ( empty( $assets ) ) {
$assets['message'] = 'No assets found';
$assets = (object) $assets;
}
return $assets;
}
/**
* Add settings for GitHub Personal Access Token.
*
* @param array $auth_required Array of authentication data.
*
* @return void
*/
public function add_settings( $auth_required ) {
add_settings_section(
'github_access_token',
esc_html__( 'GitHub Personal Access Token', 'git-updater' ),
[ $this, 'print_section_github_access_token' ],
'git_updater_github_install_settings'
);
add_settings_field(
'github_access_token',
esc_html__( 'GitHub.com Access Token', 'git-updater' ),
[ Singleton::get_instance( 'Settings', $this ), 'token_callback_text' ],
'git_updater_github_install_settings',
'github_access_token',
[
'id' => 'github_access_token',
'token' => true,
]
);
/*
* Show section for private GitHub repositories.
*/
if ( $auth_required['github_private'] || $auth_required['github_enterprise'] ) {
add_settings_section(
'github_id',
esc_html__( 'GitHub Private Settings', 'git-updater' ),
[ $this, 'print_section_github_info' ],
'git_updater_github_install_settings'
);
}
}
/**
* Add values for individual repo add_setting_field().
*
* @return mixed
*/
public function add_repo_setting_field() {
$setting_field['page'] = 'git_updater_github_install_settings';
$setting_field['section'] = 'github_id';
$setting_field['callback_method'] = [
Singleton::get_instance( 'Settings', $this ),
'token_callback_text',
];
return $setting_field;
}
/**
* Print the GitHub text.
*/
public function print_section_github_info() {
esc_html_e( 'Enter your GitHub Access Token. Leave empty for public repositories.', 'git-updater' );
}
/**
* Print the GitHub Personal Access Token text.
*/
public function print_section_github_access_token() {
esc_html_e( 'Enter your personal GitHub.com or GitHub Enterprise Access Token to avoid API access limits.', 'git-updater' );
$this->render_oauth_controls();
$icon = plugin_dir_url( dirname( __DIR__, 2 ) ) . 'assets/github-logo.svg';
printf( '<img class="git-oauth-icon" src="%s" alt="GitHub logo" />', esc_attr( $icon ) );
}
/**
* Output OAuth controls and status messages.
*/
private function render_oauth_controls() {
$credentials = $this->get_oauth_credentials();
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only status query arg for UI message only.
$status = isset( $_GET['gu_github_oauth'] ) ? sanitize_key( wp_unslash( $_GET['gu_github_oauth'] ) ) : '';
if ( 'success' === $status ) {
echo '<p><strong>' . esc_html__( 'OAuth token updated from GitHub.', 'git-updater' ) . '</strong></p>';
}
if ( str_starts_with( $status, 'error-' ) ) {
echo '<p><strong>' . esc_html__( 'GitHub OAuth was not completed. You can retry below.', 'git-updater' ) . '</strong></p>';
}
if ( empty( $credentials['client_id'] ) ) {
echo '<p>' . esc_html__( 'To enable OAuth login, set GU_GITHUB_OAUTH_CLIENT_ID in wp-config.php or filter gu_github_oauth_credentials.', 'git-updater' ) . '</p>';
return;
}
printf(
'<p><a class="button button-secondary" href="%s">%s</a></p>',
esc_url( $this->get_oauth_start_url() ),
esc_html__( 'Authorize via GitHub OAuth', 'git-updater' )
);
}
/**
* Start OAuth flow and process callback.
*/
public function maybe_handle_oauth_flow() {
if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
return;
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce is validated in start_oauth_flow().
if ( isset( $_GET['gu_github_oauth_start'] ) ) {
$this->start_oauth_flow();
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth state+PKCE verifier validation is used on callback.
if ( isset( $_GET['gu_github_oauth_callback'] ) ) {
$this->complete_oauth_flow();
}
}
/**
* Build start URL for OAuth flow.
*
* @return string
*/
private function get_oauth_start_url() {
$redirect = $this->get_settings_redirect_url();
return add_query_arg(
[
'gu_github_oauth_start' => 1,
'_wpnonce' => wp_create_nonce( 'gu-github-oauth-start' ),
],
$redirect
);
}
/**
* Start GitHub OAuth redirect.
*/
private function start_oauth_flow() {
if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ), 'gu-github-oauth-start' ) ) {
$this->oauth_redirect_with_status( 'error-nonce' );
return;
}
$credentials = $this->get_oauth_credentials();
if ( empty( $credentials['client_id'] ) ) {
$this->oauth_redirect_with_status( 'error-client-id' );
return;
}
$state = wp_generate_password( 48, false, false );
$verifier = wp_generate_password( 96, false, false );
$key = $this->get_oauth_transient_key( $state );
set_transient(
$key,
[
'code_verifier' => $verifier,
],
15 * MINUTE_IN_SECONDS
);
$authorize_url = add_query_arg(
[
'client_id' => $credentials['client_id'],
'redirect_uri' => $this->get_oauth_callback_url(),
'scope' => $credentials['scope'],
'state' => $state,
'code_challenge' => $this->get_oauth_code_challenge( $verifier ),
'code_challenge_method' => 'S256',
],
'https://github.com/login/oauth/authorize'
);
wp_safe_redirect( $authorize_url );
exit;
}
/**
* Process GitHub callback and save token.
*/
private function complete_oauth_flow() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth callback is validated through state and PKCE verifier.
$state = isset( $_GET['state'] ) ? sanitize_text_field( wp_unslash( $_GET['state'] ) ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- OAuth callback is validated through state and PKCE verifier.
$code = isset( $_GET['code'] ) ? sanitize_text_field( wp_unslash( $_GET['code'] ) ) : '';
if ( empty( $state ) || empty( $code ) ) {
$this->oauth_redirect_with_status( 'error-callback' );
return;
}
$key = $this->get_oauth_transient_key( $state );
$flow = get_transient( $key );
$verifier = is_array( $flow ) && ! empty( $flow['code_verifier'] ) ? $flow['code_verifier'] : '';
delete_transient( $key );
if ( empty( $verifier ) ) {
$this->oauth_redirect_with_status( 'error-state' );
return;
}
$credentials = $this->get_oauth_credentials();
$token = $this->exchange_code_for_token( $credentials, $code, $verifier );
if ( empty( $token ) ) {
$this->oauth_redirect_with_status( 'error-token' );
return;
}
$options = get_site_option( 'git_updater', [] );
$options['github_access_token'] = $token;
update_site_option( 'git_updater', $options );
static::$options['github_access_token'] = $token;
$this->oauth_redirect_with_status( 'success' );
}
/**
* Exchange callback code for access token.
*
* @param array $credentials OAuth credentials.
* @param string $code Callback code.
* @param string $verifier PKCE verifier.
*
* @return string
*/
private function exchange_code_for_token( $credentials, $code, $verifier ) {
$body = [
'client_id' => $credentials['client_id'],
'code' => $code,
'redirect_uri' => $this->get_oauth_callback_url(),
'code_verifier' => $verifier,
];
if ( ! empty( $credentials['client_secret'] ) ) {
$body['client_secret'] = $credentials['client_secret'];
}
$response = wp_remote_post(
'https://github.com/login/oauth/access_token',
[
'timeout' => 15,
'headers' => [
'Accept' => 'application/json',
],
'body' => $body,
]
);
if ( is_wp_error( $response ) ) {
return '';
}
$payload = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $payload ) || empty( $payload['access_token'] ) ) {
return '';
}
return sanitize_text_field( $payload['access_token'] );
}
/**
* Build callback URL for GitHub OAuth.
*
* @return string
*/
private function get_oauth_callback_url() {
return add_query_arg( 'gu_github_oauth_callback', 1, $this->get_settings_redirect_url() );
}
/**
* Build redirect URL to GitHub subtab.
*
* @return string
*/
private function get_settings_redirect_url() {
$base = is_multisite() ? network_admin_url( 'settings.php' ) : admin_url( 'options-general.php' );
return add_query_arg(
[
'page' => 'git-updater',
'tab' => 'git_updater_settings',
'subtab' => 'github',
],
$base
);
}
/**
* Redirect to GitHub settings with flow status.
*
* @param string $status OAuth status value.
*/
private function oauth_redirect_with_status( $status ) {
wp_safe_redirect(
add_query_arg(
'gu_github_oauth',
$status,
$this->get_settings_redirect_url()
)
);
exit;
}
/**
* Return GitHub OAuth credentials.
*
* @return array
*/
private function get_oauth_credentials() {
$client_id = defined( 'GU_GITHUB_OAUTH_CLIENT_ID' ) ? GU_GITHUB_OAUTH_CLIENT_ID : '';
$client_secret = defined( 'GU_GITHUB_OAUTH_CLIENT_SECRET' ) ? GU_GITHUB_OAUTH_CLIENT_SECRET : '';
$scope = defined( 'GU_GITHUB_OAUTH_SCOPE' ) ? GU_GITHUB_OAUTH_SCOPE : 'repo';
$credentials = [
'client_id' => $client_id,
'client_secret' => $client_secret,
'scope' => $scope,
];
/**
* Filter OAuth credentials for GitHub auth flow.
*
* @since 13.4.0
*
* @param array $credentials OAuth configuration.
*/
return apply_filters( 'gu_github_oauth_credentials', $credentials );
}
/**
* Build transient key for OAuth flow state.
*
* @param string $state OAuth state.
*
* @return string
*/
private function get_oauth_transient_key( $state ) {
return 'gu_github_oauth_' . md5( $state );
}
/**
* Build S256 PKCE challenge.
*
* @param string $verifier PKCE verifier.
*
* @return string
*/
private function get_oauth_code_challenge( $verifier ) {
$hash = hash( 'sha256', $verifier, true );
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Required for RFC7636 base64url PKCE encoding.
return rtrim( strtr( base64_encode( $hash ), '+/', '-_' ), '=' );
}
/**
* Add remote install settings fields.
*
* @param string $type plugin|theme.
*/
public function add_install_settings_fields( $type ) {
add_settings_field(
'github_access_token',
esc_html__( 'GitHub Access Token', 'git-updater' ),
[ $this, 'github_access_token' ],
'git_updater_install_' . $type,
$type
);
}
/**
* Add subtab to Settings page.
*/
private function add_settings_subtab() {
add_filter(
'gu_add_settings_subtabs',
function ( $subtabs ) {
return array_merge( $subtabs, [ 'github' => esc_html__( 'GitHub', 'git-updater' ) ] );
}
);
}
/**
* GitHub Access Token for remote install.
*/
public function github_access_token() {
?>
<label for="github_access_token">
<input class="github_setting" type="password" style="width:50%;" id="github_access_token" name="github_access_token" value="" autocomplete="new-password">
<br>
<span class="description">
<?php esc_html_e( 'Enter GitHub Access Token for private GitHub repositories.', 'git-updater' ); ?>
</span>
</label>
<?php
}
/**
* Add remote install feature, create endpoint.
*
* @param array $headers Array of headers.
* @param array $install Array of install data.
*
* @return mixed
*/
public function remote_install( $headers, $install ) {
$options['github_access_token'] = static::$options['github_access_token'] ?? null;
if ( 'github.com' === $headers['host'] || empty( $headers['host'] ) ) {
$base = 'https://api.github.com';
$headers['host'] = 'github.com';
} else {
$base = $headers['base_uri'] . '/api/v3';
}
$install['download_link'] = "{$base}/repos/{$install['git_updater_repo']}/zipball/{$install['git_updater_branch']}";
// If asset is entered install it.
if ( false !== stripos( $headers['uri'], 'releases/download' ) ) {
$install['download_link'] = $headers['uri'];
}
/*
* Add/Save access token if present.
*/
if ( ! empty( $install['github_access_token'] ) ) {
$install['options'][ $install['repo'] ] = $install['github_access_token'];
}
return $install;
}
}