';
}
public function description() {
return __( 'Upload the entry\'s files (and the entry as JSON/CSV) to a Drive folder.', 'fieldwren' );
}
public function help() {
$email = $this->client_email();
$share = $email ? '' . esc_html__( 'Share the target folder (or shared drive) with:', 'fieldwren' ) . ' ' . esc_html( $email ) . '
' : '';
return $share . '- ' . esc_html__( 'Google Cloud console → enable the Google Drive API → IAM & Admin → Service accounts → Create → Keys → Add key → JSON. Paste the whole file here.', 'fieldwren' ) . '
- ' . esc_html__( 'Service accounts have no storage quota of their own: use a folder in a shared drive and add the service account as Content manager. Uploading into a personal My Drive folder fails with "storageQuotaExceeded".', 'fieldwren' ) . '
- ' . esc_html__( 'The drive.file scope only reaches folders the service account can see through sharing; if uploads answer "File not found", switch the scope to full Drive.', 'fieldwren' ) . '
';
}
public function credential_fields() {
return array(
'key_json' => array( 'label' => __( 'Service account key (JSON)', 'fieldwren' ), 'type' => 'textarea', 'secret' => true, 'raw' => true, 'required' => true, 'placeholder' => '{ "type": "service_account", "client_email": "…", "private_key": "-----BEGIN PRIVATE KEY-----…" }' ),
'scope' => array( 'label' => __( 'Scope', 'fieldwren' ), 'type' => 'select', 'default' => 'drive.file', 'options' => array( 'drive.file' => 'drive.file (recommended)', 'drive' => __( 'drive (full access)', 'fieldwren' ) ) ),
);
}
/** @return array|null Decoded key. */
private function key( array $creds = null ) {
$c = null === $creds ? $this->creds() : $creds;
$key = json_decode( (string) ( $c['key_json'] ?? '' ), true );
return is_array( $key ) && ! empty( $key['client_email'] ) && ! empty( $key['private_key'] ) ? $key : null;
}
/** @return string Service account email (not secret; shown in the UI). */
public function client_email() {
$k = $this->key();
return $k ? sanitize_email( $k['client_email'] ) : '';
}
public function before_save_credentials( array $creds, array $old ) {
if ( '' === (string) ( $creds['key_json'] ?? '' ) || ( $old['key_json'] ?? '' ) === $creds['key_json'] ) {
return $creds;
}
$key = json_decode( (string) $creds['key_json'], true );
if ( ! is_array( $key ) || 'service_account' !== ( $key['type'] ?? '' ) || empty( $key['client_email'] ) || empty( $key['private_key'] ) ) {
return new \WP_Error( 'fwren_gdrive_key', __( 'That is not a service account JSON key (type "service_account" with client_email and private_key).', 'fieldwren' ) );
}
if ( ! function_exists( 'openssl_pkey_get_private' ) || ! openssl_pkey_get_private( (string) $key['private_key'] ) ) {
return new \WP_Error( 'fwren_gdrive_key', __( 'The private key in the JSON could not be read (OpenSSL is required).', 'fieldwren' ) );
}
// Keep only what the token flow needs.
$creds['key_json'] = (string) wp_json_encode(
array(
'type' => 'service_account',
'project_id' => (string) ( $key['project_id'] ?? '' ),
'private_key_id' => (string) ( $key['private_key_id'] ?? '' ),
'private_key' => (string) $key['private_key'],
'client_email' => (string) $key['client_email'],
'token_uri' => (string) ( $key['token_uri'] ?? 'https://oauth2.googleapis.com/token' ),
)
);
return $creds;
}
/** @return string Base64url. */
private static function b64( $s ) {
return rtrim( strtr( base64_encode( $s ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions
}
/** @return string|\WP_Error Access token (JWT bearer flow, cached ~55 min). */
private function token( array $creds = null ) {
$c = null === $creds ? $this->creds() : $creds;
$key = $this->key( $c );
if ( ! $key ) {
return new \WP_Error( 'fwren_gdrive_key', __( 'No valid service account key is saved.', 'fieldwren' ) );
}
$this->secrets[] = (string) $key['private_key'];
$scope = 'drive' === ( $c['scope'] ?? '' ) ? 'https://www.googleapis.com/auth/drive' : 'https://www.googleapis.com/auth/drive.file';
$tkey = 'fwren_gdrive_at_' . md5( $key['client_email'] . '|' . ( $key['private_key_id'] ?? '' ) . '|' . $scope );
$hit = get_transient( $tkey );
if ( is_string( $hit ) && '' !== $hit ) {
$this->secrets[] = $hit;
return $hit;
}
if ( ! function_exists( 'openssl_sign' ) ) {
return new \WP_Error( 'fwren_openssl', __( 'The PHP OpenSSL extension is required for Google Drive.', 'fieldwren' ) );
}
$aud = ! empty( $key['token_uri'] ) ? (string) $key['token_uri'] : 'https://oauth2.googleapis.com/token';
$now = time();
$header = array( 'alg' => 'RS256', 'typ' => 'JWT' );
if ( ! empty( $key['private_key_id'] ) ) {
$header['kid'] = (string) $key['private_key_id'];
}
$input = self::b64( (string) wp_json_encode( $header ) ) . '.' . self::b64(
(string) wp_json_encode(
array(
'iss' => $key['client_email'],
'scope' => $scope,
'aud' => $aud,
'iat' => $now - 30,
'exp' => $now + 3540,
)
)
);
$sig = '';
$pk = openssl_pkey_get_private( (string) $key['private_key'] );
if ( ! $pk || ! openssl_sign( $input, $sig, $pk, OPENSSL_ALGO_SHA256 ) ) {
return new \WP_Error( 'fwren_gdrive_sign', __( 'Could not sign the token request with the private key.', 'fieldwren' ) );
}
$jwt = $input . '.' . self::b64( $sig );
$this->secrets[] = $jwt;
$b = self::body(
$this->http(
'POST',
$aud,
array(
'form' => true,
'body' => array(
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt,
),
)
)
);
if ( is_wp_error( $b ) ) {
return $b;
}
if ( empty( $b['access_token'] ) ) {
return new \WP_Error( 'fwren_gdrive_token', __( 'Google did not return an access token.', 'fieldwren' ) );
}
set_transient( $tkey, (string) $b['access_token'], max( 300, (int) ( $b['expires_in'] ?? 3600 ) - 300 ) );
$this->secrets[] = (string) $b['access_token'];
return (string) $b['access_token'];
}
protected function error_message( $body, $code ) {
if ( is_array( $body ) && isset( $body['error']['message'] ) ) {
$reason = (string) ( $body['error']['errors'][0]['reason'] ?? '' );
return $body['error']['message'] . ( $reason ? ' [' . $reason . ']' : '' );
}
if ( is_array( $body ) && isset( $body['error_description'] ) ) {
return (string) $body['error_description'];
}
return parent::error_message( $body, $code );
}
/** Drive API call with the bearer token. */
private function api( $method, $url, array $args = array(), array $creds = null ) {
$t = $this->token( $creds );
if ( is_wp_error( $t ) ) {
return $t;
}
$args['headers'] = array_merge( (array) ( $args['headers'] ?? array() ), array( 'Authorization' => 'Bearer ' . $t ) );
$args['timeout'] = $args['timeout'] ?? 60;
return $this->http( $method, $url, $args );
}
public function verify( array $creds ) {
$this->secrets = $this->secret_values( $creds );
$b = self::body( $this->api( 'GET', 'https://www.googleapis.com/drive/v3/about?fields=user(emailAddress)', array(), $creds ) );
if ( is_wp_error( $b ) ) {
return $b;
}
return (string) ( $b['user']['emailAddress'] ?? ( $this->key( $creds )['client_email'] ?? '' ) );
}
public function feed_fields( $form_id ) {
$email = $this->client_email();
return array_merge(
array(
array( 'key' => 'share', 'type' => 'notice', 'label' => __( 'Access', 'fieldwren' ), 'html' => $email ? '' . esc_html__( 'Share the folder (or shared drive) with the service account as editor / Content manager:', 'fieldwren' ) . ' ' . esc_html( $email ) . '
' : '' . esc_html__( 'Save the service account key in Settings → Integrations first; its email is shown here.', 'fieldwren' ) . '
' ),
array( 'key' => 'folder_id', 'type' => 'text', 'label' => __( 'Folder ID', 'fieldwren' ), 'required' => true, 'smartcodes' => false, 'placeholder' => '1AbCdEf…', 'desc' => __( 'The part after /folders/ in the folder\'s URL.', 'fieldwren' ) ),
array( 'key' => 'subfolder', 'type' => 'toggle', 'label' => __( 'Subfolder', 'fieldwren' ), 'text' => __( 'Create a subfolder for each entry', 'fieldwren' ), 'default' => true ),
array( 'key' => 'subfolder_name', 'type' => 'text', 'label' => __( 'Subfolder name', 'fieldwren' ), 'default' => '{form_title} #{entry.id}', 'show_if' => array( 'subfolder' => true ) ),
),
$this->storage_fields()
);
}
/** @return array|\WP_Error Created file / folder. */
private function create( array $meta, $content = null, $mime = '' ) {
$q = '?supportsAllDrives=true&fields=id,name,webViewLink';
if ( null === $content ) {
return self::body( $this->api( 'POST', 'https://www.googleapis.com/drive/v3/files' . $q, array( 'body' => $meta ) ) );
}
if ( strlen( $content ) <= self::MULTIPART_MAX ) {
$boundary = 'fwren' . wp_generate_password( 24, false );
$body = '--' . $boundary . "\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n" . wp_json_encode( $meta ) . "\r\n--" . $boundary . "\r\nContent-Type: " . ( $mime ? $mime : 'application/octet-stream' ) . "\r\n\r\n" . $content . "\r\n--" . $boundary . '--';
return self::body(
$this->api(
'POST',
'https://www.googleapis.com/upload/drive/v3/files' . $q . '&uploadType=multipart',
array(
'headers' => array( 'Content-Type' => 'multipart/related; boundary=' . $boundary ),
'body' => $body,
'binary' => true,
'timeout' => 120,
)
)
);
}
// Larger files: resumable session, then the bytes in one PUT.
$start = $this->api(
'POST',
'https://www.googleapis.com/upload/drive/v3/files' . $q . '&uploadType=resumable',
array(
'headers' => array( 'X-Upload-Content-Type' => $mime ? $mime : 'application/octet-stream', 'X-Upload-Content-Length' => (string) strlen( $content ) ),
'body' => $meta,
)
);
if ( is_wp_error( $start ) ) {
return $start;
}
$loc = $start['headers']['location'] ?? '';
$loc = is_array( $loc ) ? end( $loc ) : (string) $loc;
if ( ! $loc ) {
return new \WP_Error( 'fwren_gdrive', __( 'Drive did not start an upload session.', 'fieldwren' ) );
}
return self::body( $this->api( 'PUT', $loc, array( 'headers' => array( 'Content-Type' => $mime ? $mime : 'application/octet-stream' ), 'body' => $content, 'binary' => true, 'timeout' => 300 ) ) );
}
public function process( array $feed, array $entry, array $values ) {
$s = $feed['settings'];
$parent = preg_replace( '/[^A-Za-z0-9_\-]/', '', (string) ( $s['folder_id'] ?? '' ) );
if ( '' === $parent ) {
return new \WP_Error( 'fwren_gdrive', __( 'No Drive folder ID.', 'fieldwren' ) );
}
$items = $this->storage_items( $s );
if ( ! $items ) {
return __( 'No files in this entry; nothing to upload.', 'fieldwren' );
}
$max = (int) apply_filters( 'fwren/google_drive/max_bytes', 100 * 1024 * 1024 );
if ( ! empty( $s['subfolder'] ) ) {
$name = self::clean_name( $this->val( $s['subfolder_name'] ?? '' ) );
$dir = $this->create( array( 'name' => '' !== $name ? $name : 'Entry ' . (int) ( $entry['id'] ?? 0 ), 'mimeType' => 'application/vnd.google-apps.folder', 'parents' => array( $parent ) ) );
if ( is_wp_error( $dir ) ) {
return $dir;
}
$parent = (string) ( $dir['id'] ?? $parent );
}
$done = 0;
$skipped = array();
foreach ( $items as $item ) {
if ( $item['size'] > $max ) {
$skipped[] = $item['name'];
continue;
}
$content = self::item_content( $item );
if ( is_wp_error( $content ) ) {
return $content;
}
$r = $this->create( array( 'name' => $item['name'], 'parents' => array( $parent ) ), $content, $item['mime'] );
unset( $content );
if ( is_wp_error( $r ) ) {
return $r;
}
$done++;
}
/* translators: %d count */
$msg = sprintf( _n( '%d file uploaded to Google Drive.', '%d files uploaded to Google Drive.', $done, 'fieldwren' ), $done );
if ( $skipped ) {
/* translators: %s file names */
$msg .= ' ' . sprintf( __( 'Skipped (too large): %s', 'fieldwren' ), implode( ', ', $skipped ) );
}
return $msg;
}
}