isset( $saved['country'] ) ? (string) $saved['country'] : 'ke', 'accent' => isset( $saved['accent'] ) && preg_match( '/^#[0-9a-f]{6}$/i', $saved['accent'] ) ? $saved['accent'] : '#11794a', 'theme' => isset( $saved['theme'] ) && in_array( $saved['theme'], array( 'light', 'dark', 'auto' ), true ) ? $saved['theme'] : 'light', 'credit' => ! empty( $saved['credit'] ), 'highlight' => ! isset( $saved['highlight'] ) || ! empty( $saved['highlight'] ), ); } /** * Whether an administrator has turned on downloads from Mulabase. * * @return bool */ function mulabase_connected() { return (bool) get_option( 'mulabase_connected', false ); } /** * Schedules the twice-daily sync if it isn't scheduled yet. */ function mulabase_schedule() { if ( ! wp_next_scheduled( 'mulabase_sync_event' ) ) { wp_schedule_event( time() + 12 * HOUR_IN_SECONDS, 'twicedaily', 'mulabase_sync_event' ); } } /** * Fetches one JSON endpoint from the Open Data API. * * @param string $path Path under the API base, e.g. "/countries/". * @return array|WP_Error Decoded "data" member. */ function mulabase_fetch( $path ) { $res = wp_remote_get( MULABASE_API . $path, array( 'timeout' => 20, 'headers' => array( 'Accept' => 'application/json' ), ) ); if ( is_wp_error( $res ) ) { return $res; } $code = wp_remote_retrieve_response_code( $res ); if ( 200 !== $code ) { /* translators: %d: HTTP status code. */ return new WP_Error( 'mulabase_http', sprintf( __( 'Mulabase answered with HTTP %d.', 'mulabase' ), $code ) ); } $json = json_decode( wp_remote_retrieve_body( $res ), true ); if ( ! is_array( $json ) || ! isset( $json['data'] ) || ! is_array( $json['data'] ) ) { return new WP_Error( 'mulabase_json', __( 'Mulabase sent data this plugin could not read.', 'mulabase' ) ); } return $json['data']; } /** * Downloads calculators, countries and indicators and stores a compact copy. * Keeps the previous copy if anything fails. * * @return true|WP_Error */ function mulabase_sync() { if ( ! mulabase_connected() ) { return new WP_Error( 'mulabase_off', __( 'Downloads from Mulabase are turned off.', 'mulabase' ) ); } $calcs = mulabase_fetch( '/export/calculators.json' ); if ( is_wp_error( $calcs ) ) { update_option( 'mulabase_sync_error', $calcs->get_error_message(), false ); return $calcs; } $countries = mulabase_fetch( '/countries/' ); $indicators = mulabase_fetch( '/indicators/?history=1' ); $names = array(); if ( ! is_wp_error( $countries ) ) { foreach ( $countries as $c ) { if ( isset( $c['code'], $c['name'] ) ) { $names[ $c['code'] ] = (string) $c['name']; } } } $out = array(); foreach ( $calcs as $c ) { if ( empty( $c['slug'] ) || empty( $c['type'] ) || empty( $c['rules'] ) ) { continue; } $country = (string) $c['country']; $out[ $c['slug'] ] = array( 'slug' => (string) $c['slug'], 'type' => (string) $c['type'], 'country' => $country, 'countryName' => isset( $names[ $country ] ) ? $names[ $country ] : strtoupper( $country ), 'name' => (string) $c['name'], 'currency' => (string) $c['currency'], 'period' => isset( $c['period'] ) ? $c['period'] : null, 'verifiedAt' => isset( $c['verifiedAt'] ) ? $c['verifiedAt'] : null, 'url' => esc_url_raw( (string) $c['url'] ), 'sources' => isset( $c['sources'] ) && is_array( $c['sources'] ) ? array_slice( $c['sources'], 0, 8 ) : array(), 'caveat' => isset( $c['caveat'] ) ? (string) $c['caveat'] : '', 'rules' => $c['rules'], ); } if ( ! $out ) { update_option( 'mulabase_sync_error', __( 'Mulabase sent no calculators.', 'mulabase' ), false ); return new WP_Error( 'mulabase_empty', __( 'Mulabase sent no calculators.', 'mulabase' ) ); } $old = mulabase_data(); update_option( 'mulabase_data', array( 'calculators' => $out, 'countries' => $names ? $names : ( isset( $old['countries'] ) ? $old['countries'] : array() ), 'indicators' => is_wp_error( $indicators ) ? ( isset( $old['indicators'] ) ? $old['indicators'] : array() ) : $indicators, 'synced' => time(), ), false ); delete_option( 'mulabase_sync_error' ); return true; } /** * The stored data. Never contacts Mulabase: downloads happen only through * mulabase_sync(), after an administrator has turned them on. * * @return array{calculators:array,countries:array,indicators:array,synced:int} */ function mulabase_data() { $data = get_option( 'mulabase_data', array() ); return wp_parse_args( is_array( $data ) ? $data : array(), array( 'calculators' => array(), 'countries' => array(), 'indicators' => array(), 'synced' => 0, ) ); } /** * Normalizes a country given as a code or a name ("ke", "Kenya", "south-africa"). * * @param string $value Country. * @return string Lower-case code, or '' if unknown. */ function mulabase_country_code( $value ) { $value = strtolower( trim( (string) $value ) ); if ( '' === $value ) { return ''; } $names = mulabase_data()['countries']; if ( isset( $names[ $value ] ) || 'africa' === $value ) { return $value; } foreach ( $names as $code => $name ) { if ( sanitize_title( $name ) === sanitize_title( $value ) ) { return $code; } } return ''; } /** * The main calculator of a type for a country ("income-tax" or "tariff"). * * @param string $type Calculator type. * @param string $country Country code. * @return array|null */ function mulabase_main_calculator( $type, $country ) { foreach ( mulabase_data()['calculators'] as $c ) { if ( $c['type'] !== $type || $c['country'] !== $country ) { continue; } // Kenya also has an NSSF-only calculator; Uganda an agent-commission table. if ( false !== strpos( $c['slug'], 'nssf' ) || false !== strpos( $c['slug'], 'agent-commission' ) ) { continue; } return $c; } return null; } /** * Every main calculator of a type, one per country, sorted by country name. * * @param string $type Calculator type. * @return array */ function mulabase_main_calculators( $type ) { $out = array(); foreach ( array_keys( mulabase_data()['countries'] ) as $code ) { $c = mulabase_main_calculator( $type, $code ); if ( $c ) { $out[] = $c; } } usort( $out, function ( $a, $b ) { return strcmp( $a['countryName'], $b['countryName'] ); } ); return $out; } /** * Parses "150000", "150,000", "150k" or "1.2m". * * @param mixed $value Amount. * @return float|null */ function mulabase_amount( $value ) { $s = strtolower( preg_replace( '/[\s,_]/', '', (string) $value ) ); if ( ! preg_match( '/^(\d+(?:\.\d+)?)([km])?$/', $s, $m ) ) { return null; } $mult = array( '' => 1, 'k' => 1000, 'm' => 1000000, ); return (float) $m[1] * $mult[ isset( $m[2] ) ? $m[2] : '' ]; } /** * Marginal brackets: [{upTo, rate}, …]. * * @param float $amount Amount. * @param array $brackets Brackets. * @return float */ function mulabase_brackets( $amount, $brackets ) { $remaining = $amount; $lower = 0; $total = 0; foreach ( $brackets as $b ) { if ( $remaining <= 0 ) { break; } $width = null === $b['upTo'] ? $remaining : max( 0, $b['upTo'] - $lower ); $chunk = min( $remaining, $width ); $total += $chunk * $b['rate']; $remaining -= $chunk; if ( null !== $b['upTo'] ) { $lower = $b['upTo']; } } return $total; } /** * PAYE for a gross amount in the calculator's own period. Extra inputs left * out keep their share of the calculator's example salary. * * @param array $cfg Income-tax rules. * @param float $gross Gross pay. * @return array{gross:float,tax:float,deductions:float,net:float} */ function mulabase_income_tax( $cfg, $gross ) { $scale = ! empty( $cfg['defaultGross'] ) ? $gross / $cfg['defaultGross'] : 1; $extra = array(); foreach ( isset( $cfg['inputs'] ) ? $cfg['inputs'] : array() as $i ) { $extra[ $i['key'] ] = ( isset( $i['default'] ) ? $i['default'] : 0 ) * $scale; } $pre_tax = 0; $all = 0; $deduction = array(); foreach ( isset( $cfg['deductions'] ) ? $cfg['deductions'] : array() as $d ) { $base = ( isset( $d['base'] ) && 0 === strpos( $d['base'], 'input:' ) ) ? ( isset( $extra[ substr( $d['base'], 6 ) ] ) ? $extra[ substr( $d['base'], 6 ) ] : 0 ) : $gross; $amount = isset( $d['fixed'] ) ? $d['fixed'] : 0; if ( isset( $d['brackets'] ) ) { $amount += mulabase_brackets( $base, $d['brackets'] ); } if ( isset( $d['rate'] ) ) { $amount += $base * $d['rate']; } if ( isset( $d['min'] ) ) { $amount = max( $d['min'], $amount ); } if ( isset( $d['max'] ) ) { $amount = min( $d['max'], $amount ); } if ( $base <= 0 && ! isset( $d['fixed'] ) ) { $amount = 0; } $deduction[ isset( $d['key'] ) ? $d['key'] : count( $deduction ) ] = $amount; $all += $amount; if ( ! empty( $d['reducesTaxable'] ) ) { $pre_tax += $amount; } } $allow = 0; foreach ( isset( $cfg['allowances'] ) ? $cfg['allowances'] : array() as $a ) { $amount = isset( $a['fixed'] ) ? $a['fixed'] : 0; if ( isset( $a['rateOfInput'] ) ) { $amount += ( isset( $extra[ $a['rateOfInput']['input'] ] ) ? $extra[ $a['rateOfInput']['input'] ] : 0 ) * $a['rateOfInput']['rate']; } if ( isset( $a['rateOfGross'] ) ) { $amount += $gross * $a['rateOfGross']; } $allow += isset( $a['cap'] ) ? min( $amount, $a['cap'] ) : $amount; } $taxable = max( 0, $gross - $pre_tax - $allow ); $tax = mulabase_brackets( $taxable, $cfg['bands'] ); $relief = 0; foreach ( isset( $cfg['reliefs'] ) ? $cfg['reliefs'] : array() as $r ) { $amount = isset( $r['amount'] ) ? $r['amount'] : 0; if ( isset( $r['rateOfDeduction'] ) ) { $d = isset( $deduction[ $r['rateOfDeduction']['key'] ] ) ? $deduction[ $r['rateOfDeduction']['key'] ] : 0; $amount += isset( $r['rateOfDeduction']['cap'] ) ? min( $d * $r['rateOfDeduction']['rate'], $r['rateOfDeduction']['cap'] ) : $d * $r['rateOfDeduction']['rate']; } $relief += $amount; } $exempt = isset( $cfg['exemptUpTo'] ) && $gross <= $cfg['exemptUpTo']; $tax = $exempt ? 0 : max( 0, $tax - $relief ); return array( 'gross' => $gross, 'tax' => $tax, 'deductions' => $all, 'net' => $gross - $all - $tax, ); } /** * A tariff fee for an amount: flat, or a capped percentage. Null = not allowed. * * @param array $cfg Tariff rules. * @param float $amount Amount. * @param string $column Transaction key; '' for the first column. * @return array{fee:float|null,label:string}|null Null when out of range or unknown column. */ function mulabase_tariff_fee( $cfg, $amount, $column = '' ) { $col = null; foreach ( $cfg['columns'] as $c ) { if ( '' === $column || $c['key'] === $column ) { $col = $c; break; } } if ( ! $col ) { return null; } $rows = $cfg['rows']; $n = count( $rows ); for ( $i = 0; $i < $n; $i++ ) { $r = $rows[ $i ]; $next = isset( $rows[ $i + 1 ] ) ? $rows[ $i + 1 ]['min'] : -INF; if ( $amount >= $r['min'] && ( null === $r['max'] || $amount <= $r['max'] || $amount < $next ) ) { $v = isset( $r['values'][ $col['key'] ] ) ? $r['values'][ $col['key'] ] : null; if ( is_array( $v ) ) { $f = round( $amount * $v['pct'] ) / 100; $v = isset( $v['cap'] ) ? min( $f, $v['cap'] ) : $f; } return array( 'fee' => null === $v ? null : (float) $v, 'label' => (string) $col['label'], ); } } return null; } /** * Formats money the way the widgets do: "KES 1,250" or "KES 12.50". * * @param string $currency Currency code. * @param float $n Amount. * @return string */ function mulabase_money( $currency, $n ) { $r = round( $n, 2 ); return $currency . "\u{00a0}" . number_format_i18n( $r, floor( $r ) == $r ? 0 : 2 ); // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual }