Skip to content
This repository was archived by the owner on Jun 19, 2023. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ version: 2
jobs:
build:
docker:
- image: circleci/node:9
- image: cimg/node:12.22
working_directory: ~/shifter-support-plugin
steps:
- checkout
Expand Down
74 changes: 74 additions & 0 deletions api/shifter_api.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

class Shifter {
private $site_id = '';
private $generate_url = '';
private $terminate_url = '';
private $access_token = '';
private $refresh_token = '';
private static $token_update_date;

public function __construct() {
$this->site_id = getenv("SITE_ID");
$this->access_token = getenv("SHIFTER_ACCESS_TOKEN");
$this->refresh_token = getenv("SHIFTER_REFRESH_TOKEN");

$shifte_api = getenv("SHIFTER_API_URL");
$this->terminate_url = "$shifte_api/sites/$this->site_id/wordpress_site/stop";
$this->generate_url = "$shifte_api/sites/$this->site_id/artifacts";
$this->refresh_url = "$shifte_api/login";
$this->shifter_dashboard_url = "https://go.getshifter.io/sites/$this->site_id";

$bootup_unixtimestamp = file_get_contents(ABSPATH."/.bootup");
$bootup_date = new DateTime();
self::$token_update_date = $bootup_date->setTimestamp($bootup_unixtimestamp);
}

public function terminate_wp_app() {
if ($this->access_token_is_expired()) {
$this->refresh_token();
}
wp_remote_request($this->terminate_url, $this->build_args());
}

public function generate_wp_app() {
if ($this->access_token_is_expired()) {
$this->refresh_token();
}
return wp_remote_request($this->generate_url, $this->build_args());
}

private function build_args() {
$headers = array(
"authorization" => $this->access_token,
"content-Type" => "application/json"
);
return array("method" => "POST", "headers" => $headers, "blocking" => false);
}

private function refresh_token() {
$headers = array("content-type" => "application/json");
$args = array(
"method" => "PUT",
"headers" => $headers,
"body" => json_encode(array("refreshToken" => $this->refresh_token))
);
$response = wp_remote_request($this->refresh_url, $args);
$body = $response[body];
$body_array = json_decode($body);
$this->access_token = $body_array->AccessToken;
putenv("SHIFTER_ACCESS_TOKEN=$this->access_token");
}

private function access_token_is_expired() {
$now = new DateTime;
$elapsed = self::$token_update_date->diff($now, true);
if ($elapsed->h > 1) {
self::$token_update_date = $now;
return true;
}
return false;
}
}

?>