The kit: respira_app_* functions

Every function the add-on gives an app, with its real signature.

The kit is the whole API an app has: 22 functions, 20 of them starting with respira_app_ and two, respira_secret() and respira_secret_previous(), that do not. This page lists every one with its signature as the add-on declares it. The list is generated from the add-on's source (respira-code-core-functions.php, respira-code-kit-functions.php and the three functions the loader declares), so it cannot drift from the code.

Three rules hold for all of them.

  • No function takes a slug. The add-on finds your app from the file that made the call, so one app cannot act as another.
  • An app calls these and nothing else of Respira's. The lint refuses Respira_Code_* classes, respira_code_* functions and hooks, and refuses an app that declares a name starting with respira_app_ or respira_code_.
  • Inside a namespace, write the leading backslash, as in \respira_app_log(), or import the name with use function. The lint requires it for \respira_app_rate_limit() and \respira_app_owner_request(). Every kit call on this page is written that way.

If the add-on is switched off on a site, the loader carries stand-ins so the app does not fatal: respira_secret() answers null, the mail functions answer a WP_Error respira_code_addon_inactive, and respira_app_log() does nothing.

Secrets

respira_secret( $name )

Reads a secret the site owner set for this app on the Respira Code Secrets screen.

  • Returns: The value as a string, or null.
  • Refuses: Returns null when the secret is unset, unreadable, not declared under secrets in app.json, or when the caller is not an app. It never throws, and the value is replaced with [secret:NAME] in every response, log and audit row.
function mail_key() {
	$key = \respira_secret( 'RESEND_KEY' );
	if ( null === $key ) {
		\respira_app_log( 'warning', 'no_key', 'The mail key is not set yet.' );
		return '';
	}
	return $key;
}

function previous_key() {
	// For 7 days after the owner rotates the key, the old value still answers here.
	return \respira_secret_previous( 'RESEND_KEY' );
}

respira_secret_previous( $name )

Reads the value a secret had before its last rotation, so a webhook signed with the old one still checks out.

  • Returns: The previous value for 7 days after a rotation, otherwise null.
  • Refuses: The same as respira_secret(): null for anything unset, undeclared or outside an app.

Mail

respira_app_batch_status( $batch_id )

Says where a batch of this app stands.

  • Returns: The same shape as a batch answer: status, batch_id, plan_sha256, total, counts, pause_reason.
  • Refuses: A WP_Error with 404 when this app has no batch with that id. One app never sees another app's batch.
function batch_left( $batch_id ) {
	$status = \respira_app_batch_status( $batch_id );
	return \is_wp_error( $status ) ? null : $status['counts']['queued'];
}

respira_app_on_mail_event( $cb )

Registers a callback for delivery events of this app's own letters: delivered, opened, clicked, bounced, complained and failed.

  • Returns: true when registered.
  • Refuses: false when not called from an app or when the callback is not callable. The callback gets ( $type, $message_id, $kind, $recipient_hash, $at ). The address is never passed, only its hash.
\respira_app_on_mail_event(
	static function ( $type, $message_id, $kind, $recipient_hash, $at ) {
		if ( 'bounced' === $type ) {
			\respira_app_log( 'notice', 'bounce', 'A letter bounced.', array( 'kind' => $kind ) );
		}
	}
);

respira_app_send( $kind, $to, $o = array() )

Sends one email of a kind declared in app.json to one person. A ledger claims the send before the provider is called, so the same letter cannot go out twice.

  • Returns: An array with status (sent, queued, held, skipped, failed, unknown or dry_run), counts, total, and as it applies mail_id, reason and plan_sha256. A test send returns a receipt.
  • Refuses: A WP_Error, and nothing is sent, for an unknown option, an unknown kind or one declared for many people, a missing template value, a link that is not https on this site, a test address that is not an administrator, and any call made inside a deploy canary (409). A person who already got the letter is skipped with the reason already_sent, a suppressed address with suppressed, and a person past 5 an hour or 20 a day, or a kind past 200 an hour, with the limit named.
function send_welcome( $email, $name ) {
	$result = \respira_app_send(
		'welcome',
		array(
			'email' => $email,
			'name'  => $name,
			'vars'  => array( 'first_name' => $name ),
		)
	);
	if ( \is_wp_error( $result ) ) {
		\respira_app_log( 'error', 'welcome_failed', $result->get_error_message() );
		return false;
	}
	return 'sent' === $result['status'];
}

respira_app_send_batch( $kind, $recipients, $o = array() )

Sends one email of a kind declared for many people to a list. Options are dry_run, receipt and expect_plan only.

  • Returns: The batch: status, batch_id, plan_sha256, total, counts and pause_reason. A dry run returns would_send, would_skip and needs_receipt.
  • Refuses: A WP_Error for a kind declared for one person, a bad recipient, a list that is not the one the dry run showed (expect_plan), and any call inside a canary. A batch larger than the 10 people an hour an app may mail without one needs a test receipt from respira_app_send() with test_to, or the owner's standing approval. Without it the whole batch is refused with respira_code_mail_receipt_required and nothing is sent.
function send_invites( array $recipients ) {
	$plan = \respira_app_send_batch( 'invite', $recipients, array( 'dry_run' => true ) );
	if ( \is_wp_error( $plan ) ) {
		return $plan;
	}
	// A test letter to an administrator gives the receipt a batch above 10 people needs.
	$test = \respira_app_send( 'invite', array( 'vars' => array( 'first_name' => 'Test' ) ), array( 'test_to' => \get_option( 'admin_email' ) ) );
	if ( \is_wp_error( $test ) || empty( $test['receipt'] ) ) {
		return $test;
	}
	return \respira_app_send_batch(
		'invite',
		$recipients,
		array(
			'receipt'     => $test['receipt'],
			'expect_plan' => $plan['plan_sha256'],
		)
	);
}

Jobs

respira_app_job_alive()

A long job says it is still working, so no other runner takes its lock. Call it every few minutes.

  • Returns: true while the job runs.
  • Refuses: false outside a run of one of this app's jobs.
\respira_app_on_job(
	'demo_hourly',
	static function () {
		foreach ( array( 1, 2, 3 ) as $batch ) {
			// ... a slow step ...
			\respira_app_job_alive();
		}
	}
);

respira_app_on_job( $hook, $handler )

Gives the handler for a job declared under cron in app.json. Respira keeps WP-Cron equal to the manifest and runs the handler under a lock, one instance at a time.

  • Returns: true when registered.
  • Refuses: false when not called from an app. A thrown error fails that run only, and three fatals quarantine the job until the owner releases it.
\respira_app_on_job(
	'demo_hourly',
	static function () {
		\respira_app_log( 'info', 'tick', 'The hourly job ran.' );
	}
);

respira_app_run_job( ...$args )

Runs one job of the calling app with fatal attribution. A fatal or thrown error inside it fails the release only if the job never finished on that release. After that it quarantines the job alone. The app is the one whose file called it, never an argument.

  • Returns: The callback's result, or a WP_Error, or null.
  • Refuses: respira_code_job_refused when it is not called from an app, the callback is not callable or the job belongs to another app, and respira_code_job_failed when the callback throws.
function run_clean_up() {
	return \respira_app_run_job(
		'demo_hourly',
		static function () {
			// ... the job's work ...
			return 'done';
		}
	);
}

Erasure and links

respira_app_delete_link( $email, $lang = null )

Makes the link that lets one person delete what this app holds about them. A GET shows a confirmation page, and only a POST erases.

  • Returns: The link as a string.
  • Refuses: An empty string when the app declares no personal data, or outside an app.
function footer_links( $email ) {
	$delete = \respira_app_delete_link( $email, 'en' );
	$unsub  = \respira_app_unsubscribe_link( $email );
	return array(
		'delete'      => $delete,
		'unsubscribe' => $unsub,
	);
}

respira_app_erase( $email )

Deletes everything this app declared as personal data for an address, child tables first, and suppresses the address hash. No copy is kept.

  • Returns: An array of the rows deleted per table.
  • Refuses: A WP_Error for something that is not an email address (400) or for an app with no live release (404). It deletes only the declared tables.
function forget_person( $email ) {
	$export = \respira_app_export( $email );
	if ( \is_wp_error( $export ) ) {
		return $export;
	}
	return \respira_app_erase( $email );
}

respira_app_export( $email )

Reads everything this app declared as personal data for an address, for a person who asks for their copy.

  • Returns: An array of the declared rows.
  • Refuses: A WP_Error for something that is not an email address.

respira_app_unsubscribe_link( $email )

Makes the one-click unsubscribe link of this app for an address.

  • Returns: The link as a string.
  • Refuses: An empty string outside an app, or when the mail part is not loaded.

Who may call

respira_app_owner_request()

Says whether this request is the site owner's own: a user with manage_options and respira_manage and no API credential on the request.

  • Returns: true or false.
  • Refuses: false for a request with a Respira key or token, an application password or an Authorization header, for an ability, and for background work such as WP-Cron or a queued job. Use it as the permission callback of an owner-only route and add a nonce to forms.
function save_settings() {
	if ( ! \respira_app_owner_request() ) {
		\wp_die( \esc_html__( 'Only the site owner can do this.', 'demo' ), '', array( 'response' => 403 ) );
	}
	\check_admin_referer( 'demo_save' );
	if ( ! \current_user_can( 'manage_options' ) ) {
		\wp_die( \esc_html__( 'Not allowed.', 'demo' ), '', array( 'response' => 403 ) );
	}
	// ... save ...
}

\add_action( 'admin_post_demo_save', __NAMESPACE__ . '\\save_settings' );

respira_app_rate_limit( $key, $limit, $window_seconds )

Counts a caller against a limit, for this app only, and atomically. Call it before the first write in any public route.

  • Returns: true while the call is allowed, false when it is over the limit.
  • Refuses: false outside an app too. The window is at most 7 days. Inside a namespace write \respira_app_rate_limit(), or import it with use function, or the lint does not count it.
function signup( \WP_REST_Request $request ) {
	$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? \sanitize_text_field( \wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
	if ( ! \respira_app_rate_limit( 'signup:' . $ip, 5, 3600 ) ) {
		return new \WP_REST_Response( array( 'error' => 'slow_down' ), 429 );
	}
	// The first write comes after the check.
	return new \WP_REST_Response( array( 'ok' => true ), 201 );
}

Files

respira_app_state_dir()

Gives the one directory the app may write files to, the same for every release: wp-content/respira-apps/<slug>/state/data. It is never web-readable.

  • Returns: An absolute path without a trailing slash.
  • Refuses: An empty string when called outside an app, with a warning in the log. The lint refuses a file write anywhere else.
function remember( array $data ) {
	$dir = \respira_app_state_dir();
	if ( '' === $dir ) {
		return false;
	}
	return false !== \file_put_contents( $dir . '/last-run.json', \wp_json_encode( $data ) );
}

Logs

respira_app_log( $level, $code, $message, $context = array() )

Writes a row to the app's log, channel app.

  • Returns: Nothing.
  • Refuses: A message is cut at 1,024 bytes and context at 4,096. Secret-looking keys in context are blanked. Rows are kept 30 days. On a site where the add-on is off, the call does nothing.
\respira_app_log( 'info', 'signup_confirmed', 'A person confirmed their address.', array( 'lang' => 'en' ) );

Language

respira_app_lang()

Says which language this request speaks, one the app declares. Polylang decides first, then WPML, then the locale.

  • Returns: A language code.
  • Refuses: Nothing; it falls back to the default language.
function thanks_line() {
	$lang = \respira_app_lang();
	return \respira_app_t( 'form.thanks', array( 'name' => 'Ana' ), $lang );
}

function script_strings() {
	return \respira_app_t_for_js( array( 'form.thanks', 'form.error' ) );
}

respira_app_t( $key, $vars = array(), $lang = null )

Gives a string in the visitor's language from the app's i18n tables, with {name} placeholders filled from vars.

  • Returns: Plain text. Escape it where you print it.
  • Refuses: A key missing in a language falls back to the default language, then to [[key]], so put [[ in each contract's must_not.

respira_app_t_for_js( $keys, $lang = null )

Gives a set of strings for a script, key to text.

  • Returns: An array. Print it with wp_json_encode().
  • Refuses: Nothing; a missing key is handled as in respira_app_t().

Hooks

respira_app_add_action( $hook_name, $callback, $priority = 10, $accepted_args = 1 )

add_action() for app code. The app stays in flight while the callback runs, so a fatal it causes inside WordPress core is still the app's and the crash guard acts on the right release.

  • Returns: true.
  • Refuses: Nothing. A plain add_action() works too; you lose the attribution.
\respira_app_add_action(
	'init',
	static function () {
		\register_post_type( 'demo_note', array( 'public' => false ) );
	}
);

respira_app_add_filter( $hook_name, $callback, $priority = 10, $accepted_args = 1 )

add_filter() for app code, with the same attribution. It is also how an app answers the health check: add a callback on respira_app_health, shown below.

  • Returns: true.
  • Refuses: Nothing.
\respira_app_add_filter(
	'respira_app_health',
	static function ( $answer, $slug ) {
		if ( 'demo' !== $slug ) {
			return $answer;
		}
		global $wpdb;
		$count = $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $wpdb->prefix . 'demo_people' ) );
		if ( null === $count ) {
			return array( 'ok' => false, 'detail' => 'The people table is not readable.' );
		}
		return array( 'ok' => true );
	},
	10,
	2
);

The health filter

This is a filter, not a function, and an app that sets "health": true in app.json must answer it. The canary and verify call apply_filters( 'respira_app_health', null, $slug ) through a route of the add-on and read the answer.

  • Arguments: $answer (null), $slug. Answer only for your own slug and return $answer untouched for any other, because every app shares the one hook.
  • Answer: true, or an array with ok set to true or false and an optional detail.
  • Anything else, including no answer, fails the check with "the app did not answer respira_app_health".
\respira_app_add_filter(
	'respira_app_health',
	static function ( $answer, $slug ) {
		if ( 'demo' !== $slug ) {
			return $answer;
		}
		global $wpdb;
		$count = $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $wpdb->prefix . 'demo_people' ) );
		if ( null === $count ) {
			return array( 'ok' => false, 'detail' => 'The people table is not readable.' );
		}
		return array( 'ok' => true );
	},
	10,
	2
);

How the examples were checked

Every example on this page was run through the add-on's own upload lint, the real Respira_Code_Lint, wrapped in the namespace and guard a release needs. Each passed with no error and no warning. The same check ran on the manifests in the manifest page.