token = CFSP_Settings::get( 'gh_token' ); $this->repo = CFSP_Settings::get( 'gh_repo' ); $this->branch = CFSP_Settings::get( 'gh_branch' ); } private function repo_path( $suffix = '' ) { list( $owner, $name ) = array_pad( explode( '/', $this->repo, 2 ), 2, '' ); return '/repos/' . rawurlencode( $owner ) . '/' . rawurlencode( $name ) . $suffix; } private function branch_path() { return implode( '/', array_map( 'rawurlencode', explode( '/', $this->branch ) ) ); } /** * @return array|WP_Error Decoded JSON body. */ private function request( $method, $path, $body = null, $timeout = 60 ) { $args = array( 'method' => $method, 'timeout' => $timeout, 'headers' => array( 'Authorization' => 'Bearer ' . $this->token, 'Accept' => 'application/vnd.github+json', 'X-GitHub-Api-Version' => '2022-11-28', 'User-Agent' => 'Static-Push/' . CFSP_VERSION, ), ); if ( null !== $body ) { $args['body'] = wp_json_encode( $body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); $args['headers']['Content-Type'] = 'application/json'; if ( false === $args['body'] ) { return new WP_Error( 'cfsp_api', 'Could not encode request (invalid UTF-8 in a file?)' ); } } $response = wp_remote_request( self::API . $path, $args ); if ( is_wp_error( $response ) ) { return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); $data = json_decode( wp_remote_retrieve_body( $response ), true ); if ( $code >= 200 && $code < 300 ) { return is_array( $data ) ? $data : array(); } $message = 'GitHub API HTTP ' . $code . ( is_array( $data ) && ! empty( $data['message'] ) ? ': ' . $data['message'] : '' ); // Primary or secondary rate limit. $retry_after = (int) wp_remote_retrieve_header( $response, 'retry-after' ); $remaining = wp_remote_retrieve_header( $response, 'x-ratelimit-remaining' ); if ( 429 === $code || ( 403 === $code && ( $retry_after || '0' === $remaining || false !== stripos( $message, 'rate limit' ) ) ) ) { $wait = $retry_after; if ( ! $wait && '0' === $remaining ) { $wait = max( 1, (int) wp_remote_retrieve_header( $response, 'x-ratelimit-reset' ) - time() ); } return new WP_Error( 'cfsp_rate_limited', $message, array( 'status' => $code, 'wait' => max( 60, min( 3600, $wait ) ) ) ); } return new WP_Error( 'cfsp_api', $message, array( 'status' => $code ) ); } public function get_repo() { return $this->request( 'GET', $this->repo_path() ); } /** Repositories the connected account can push to, most recently updated first. */ const REPOS_CACHE = 'cfsp_gh_repos'; /** * Repositories the connected account can push to, newest first. Kept for 15 minutes. * * @param bool $refresh Ask GitHub again instead of using the saved list. * @return array|WP_Error */ public function list_repos( $refresh = false ) { $key = self::REPOS_CACHE; $cached = $refresh ? false : get_transient( $key ); if ( is_array( $cached ) && ( $cached['token'] ?? '' ) === md5( (string) $this->token ) ) { return $cached['repos']; } $repos = $this->list_repos_graphql(); if ( is_wp_error( $repos ) ) { $repos = $this->list_repos_rest(); } if ( ! is_wp_error( $repos ) ) { set_transient( $key, array( 'token' => md5( (string) $this->token ), 'repos' => $repos, ), 15 * MINUTE_IN_SECONDS ); } return $repos; } public static function forget_repos() { delete_transient( self::REPOS_CACHE ); } /** GraphQL: only the three fields we need, instead of every detail of every repository. */ private function list_repos_graphql() { $query = 'query($after: String) { viewer { repositories(first: 100, after: $after, affiliations: [OWNER, COLLABORATOR, ORGANIZATION_MEMBER], ownerAffiliations: [OWNER, COLLABORATOR, ORGANIZATION_MEMBER], orderBy: {field: UPDATED_AT, direction: DESC}) { nodes { nameWithOwner isPrivate viewerPermission defaultBranchRef { name } } pageInfo { hasNextPage endCursor } } } }'; $repos = array(); $after = null; for ( $page = 1; $page <= 10; $page++ ) { $data = $this->request( 'POST', '/graphql', array( 'query' => $query, 'variables' => array( 'after' => $after ), ), 30 ); if ( is_wp_error( $data ) ) { return $data; } $list = $data['data']['viewer']['repositories'] ?? null; if ( ! empty( $data['errors'] ) || ! is_array( $list ) ) { return new WP_Error( 'cfsp_api', 'GraphQL repository list unavailable.' ); } foreach ( (array) $list['nodes'] as $repo ) { if ( in_array( $repo['viewerPermission'] ?? '', array( 'ADMIN', 'MAINTAIN', 'WRITE' ), true ) ) { $repos[] = array( 'full_name' => $repo['nameWithOwner'], 'private' => ! empty( $repo['isPrivate'] ), 'default_branch' => $repo['defaultBranchRef']['name'] ?? 'main', ); } } if ( empty( $list['pageInfo']['hasNextPage'] ) ) { break; } $after = $list['pageInfo']['endCursor']; } return $repos; } /** REST fallback (full repository objects, so slower). */ private function list_repos_rest() { $repos = array(); for ( $page = 1; $page <= 5; $page++ ) { $batch = $this->request( 'GET', '/user/repos?per_page=100&sort=updated&affiliation=owner,collaborator,organization_member&page=' . $page ); if ( is_wp_error( $batch ) ) { return $batch; } foreach ( $batch as $repo ) { if ( ! empty( $repo['permissions']['push'] ) ) { $repos[] = array( 'full_name' => $repo['full_name'], 'private' => ! empty( $repo['private'] ), 'default_branch' => $repo['default_branch'] ?? 'main', ); } } if ( count( $batch ) < 100 ) { break; } } return $repos; } /** Create a repository under the connected account (with a README so the branch exists). */ public function create_repo( $name, $private = true ) { return $this->request( 'POST', '/user/repos', array( 'name' => $name, 'private' => (bool) $private, 'auto_init' => true, 'description' => 'Static copy of ' . ( CFSP_Settings::destination_url() ? CFSP_Settings::destination_url() : get_bloginfo( 'name' ) ) . ' (Static Push)', ) ); } /** * Current tip of the branch. * * @return array|null|WP_Error [ 'commit' => sha, 'tree' => sha ], null if the branch doesn't exist, * WP_Error 'cfsp_empty_repo' if the repository has no commits. */ public function get_head() { $ref = $this->request( 'GET', $this->repo_path( '/git/ref/heads/' . $this->branch_path() ) ); if ( is_wp_error( $ref ) ) { $status = $ref->get_error_data()['status'] ?? 0; if ( 409 === $status ) { return new WP_Error( 'cfsp_empty_repo', 'Repository is empty.' ); } return 404 === $status ? null : $ref; } if ( empty( $ref['object']['sha'] ) || 'commit' !== ( $ref['object']['type'] ?? '' ) ) { return null; } $commit = $this->request( 'GET', $this->repo_path( '/git/commits/' . $ref['object']['sha'] ) ); if ( is_wp_error( $commit ) ) { return $commit; } return array( 'commit' => $ref['object']['sha'], 'tree' => $commit['tree']['sha'], ); } /** Git Data endpoints don't work on an empty repository, so create a first commit. */ public function init_repo() { return $this->request( 'PUT', $this->repo_path( '/contents/README.md' ), array( 'message' => 'Initialize static site repository', 'content' => base64_encode( "# Static site\n\nGenerated from WordPress by Static Push.\n" ), 'branch' => $this->branch, ) ); } /** * @return array|WP_Error [ 'truncated' => bool, 'files' => [ path => sha ] ] */ public function get_tree( $sha ) { $tree = $this->request( 'GET', $this->repo_path( '/git/trees/' . $sha . '?recursive=1' ), null, 120 ); if ( is_wp_error( $tree ) ) { return $tree; } $files = array(); foreach ( $tree['tree'] ?? array() as $entry ) { if ( 'blob' === $entry['type'] ) { $files[ $entry['path'] ] = $entry['sha']; } } return array( 'truncated' => ! empty( $tree['truncated'] ), 'files' => $files, ); } /** @return string|WP_Error Blob sha. */ public function create_blob( $content ) { $result = $this->request( 'POST', $this->repo_path( '/git/blobs' ), array( 'content' => base64_encode( $content ), 'encoding' => 'base64', ), 120 ); return is_wp_error( $result ) ? $result : $result['sha']; } /** @return string|WP_Error Tree sha. */ public function create_tree( $base_tree, array $entries ) { $body = array( 'tree' => $entries ); if ( $base_tree ) { $body['base_tree'] = $base_tree; } $result = $this->request( 'POST', $this->repo_path( '/git/trees' ), $body, 180 ); return is_wp_error( $result ) ? $result : $result['sha']; } /** @return array|WP_Error Commit object (sha, html_url, ...). */ public function create_commit( $message, $tree, array $parents ) { $body = array( 'message' => $message, 'tree' => $tree, 'parents' => $parents, ); $name = CFSP_Settings::get( 'gh_author_name' ); $email = CFSP_Settings::get( 'gh_author_email' ); if ( $name && $email ) { $body['author'] = array( 'name' => $name, 'email' => $email, 'date' => gmdate( 'c' ), ); } return $this->request( 'POST', $this->repo_path( '/git/commits' ), $body ); } /** Fast-forward the branch. Fails with 422 if someone else pushed in the meantime. */ public function update_ref( $sha ) { return $this->request( 'PATCH', $this->repo_path( '/git/refs/heads/' . $this->branch_path() ), array( 'sha' => $sha, 'force' => false, ) ); } public function create_ref( $sha ) { return $this->request( 'POST', $this->repo_path( '/git/refs' ), array( 'ref' => 'refs/heads/' . $this->branch, 'sha' => $sha, ) ); } }