[ hash, name, created, seen ]. const RULES = 'nodebook_app_rules'; const CODE_TTL = 600; public static function init() { add_action( 'init', array( __CLASS__, 'rules' ) ); add_filter( 'query_vars', array( __CLASS__, 'query_vars' ) ); add_action( 'template_redirect', array( __CLASS__, 'route' ), 0 ); } /* ------------------------------------------------------------------ * * Address * ------------------------------------------------------------------ */ /** * A private address per site, like "node-k7p2xq": never linked or announced. Phones get there through the * QR code in Settings; anyone else gets "page not found". */ public static function path() { static $path = null; if ( null === $path ) { $slug = (string) get_option( 'nodebook_app_slug' ); if ( ! preg_match( '/^node-[a-z0-9]{6,12}$/', $slug ) ) { $chars = 'abcdefghjkmnpqrstuvwxyz23456789'; $slug = 'node-'; for ( $i = 0; $i < 8; $i++ ) { $slug .= $chars[ random_int( 0, strlen( $chars ) - 1 ) ]; } // add_option() only writes when nobody else did first, so two requests can never end up with two addresses. add_option( 'nodebook_app_slug', $slug, '', true ); wp_cache_delete( 'nodebook_app_slug', 'options' ); wp_cache_delete( 'alloptions', 'options' ); $saved = (string) get_option( 'nodebook_app_slug' ); $slug = preg_match( '/^node-[a-z0-9]{6,12}$/', $saved ) ? $saved : $slug; } $path = trim( sanitize_title( (string) apply_filters( 'nodebook_app_path', $slug ) ), '/' ); $path = '' === $path ? $slug : $path; } return $path; } public static function pretty() { return '' !== (string) get_option( 'permalink_structure' ); } /** The app's address, or one of its files (manifest.json, sw.js). */ public static function url( $what = '', array $args = array() ) { if ( self::pretty() ) { $url = home_url( '/' . self::path() . '/' . $what ); } else { $url = add_query_arg( self::VAR, '' === $what ? 'home' : str_replace( array( '.json', '.js' ), '', $what ), home_url( '/' ) ); } return $args ? add_query_arg( $args, $url ) : $url; } public static function query_vars( $vars ) { $vars[] = self::VAR; return $vars; } public static function rules() { $p = preg_quote( self::path(), '#' ); add_rewrite_rule( '^' . $p . '/?$', 'index.php?' . self::VAR . '=home', 'top' ); add_rewrite_rule( '^' . $p . '/manifest\.json$', 'index.php?' . self::VAR . '=manifest', 'top' ); add_rewrite_rule( '^' . $p . '/sw\.js$', 'index.php?' . self::VAR . '=sw', 'top' ); if ( 'node' !== self::path() ) { // Phones connected before 1.23 still open /node/: they are moved to the private address (strangers get a 404). add_rewrite_rule( '^node/?$', 'index.php?' . self::VAR . '=legacy', 'top' ); } $sig = self::path() . '|' . NODEBOOK_VERSION . '|2'; if ( get_option( self::RULES ) !== $sig ) { update_option( self::RULES, $sig, true ); flush_rewrite_rules( false ); } } /* ------------------------------------------------------------------ * * Phones * ------------------------------------------------------------------ */ public static function devices( $user_id = 0 ) { $user_id = $user_id ? (int) $user_id : Nodebook_Node::owner(); $d = get_user_meta( $user_id, self::DEVICES, true ); return is_array( $d ) ? $d : array(); } private static function hash( $secret ) { return hash_hmac( 'sha256', (string) $secret, wp_salt( 'auth' ) ); } /** * A 6-digit code to connect a phone, valid 10 minutes. Owner only. * * @return array|WP_Error code, expires (unix), url */ public static function create_code( $user_id ) { $user_id = (int) $user_id; if ( ! $user_id || Nodebook_Node::owner() !== $user_id ) { return new WP_Error( 'nodebook_not_owner', __( 'Only the person Node works for can connect a phone.', 'nodebook' ) ); } $old = get_user_meta( $user_id, 'nodebook_app_code', true ); if ( is_array( $old ) && ! empty( $old['h'] ) ) { delete_transient( 'nodebook_app_pair_' . $old['h'] ); } $code = (string) wp_rand( 100000, 999999 ); $h = substr( self::hash( 'pair' . $code ), 0, 40 ); set_transient( 'nodebook_app_pair_' . $h, $user_id, self::CODE_TTL ); update_user_meta( $user_id, 'nodebook_app_code', array( 'h' => $h, 'e' => time() + self::CODE_TTL, ) ); return array( 'code' => $code, 'expires' => time() + self::CODE_TTL, 'url' => self::url( '', array( 'pair' => $code ) ), ); } /** Too many wrong codes from this address in 15 minutes? */ private static function throttled( $count = false ) { $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; $key = 'nodebook_app_try_' . md5( $ip ); $n = (int) get_transient( $key ); if ( $count ) { set_transient( $key, $n + 1, 15 * MINUTE_IN_SECONDS ); } return $n >= 8; } /** "iPhone", "Android", … from the browser's user agent. */ public static function device_name( $ua ) { foreach ( array( 'iPhone' => 'iPhone', 'iPad' => 'iPad', 'Android' => 'Android', 'Mac OS' => 'Mac', 'Windows' => 'Windows', ) as $needle => $name ) { if ( false !== stripos( (string) $ua, $needle ) ) { return $name; } } return __( 'Phone', 'nodebook' ); } /** * Swap a code for a phone key. * * @return string|WP_Error "selector.secret" to keep in the cookie */ public static function pair( $code, $ua = '' ) { if ( self::throttled() ) { return new WP_Error( 'nodebook_slow_down', __( 'Too many tries. Wait a few minutes and get a new code.', 'nodebook' ) ); } $code = preg_replace( '/\D/', '', (string) $code ); $h = substr( self::hash( 'pair' . $code ), 0, 40 ); $uid = 6 === strlen( $code ) ? (int) get_transient( 'nodebook_app_pair_' . $h ) : 0; if ( ! $uid || Nodebook_Node::owner() !== $uid ) { self::throttled( true ); return new WP_Error( 'nodebook_bad_code', __( 'That code did not work. Codes last 10 minutes: get a new one under Settings → Node.', 'nodebook' ) ); } delete_transient( 'nodebook_app_pair_' . $h ); delete_user_meta( $uid, 'nodebook_app_code' ); $selector = bin2hex( random_bytes( 6 ) ); $secret = bin2hex( random_bytes( 20 ) ); $devices = self::devices( $uid ); $devices[ $selector ] = array( 'hash' => self::hash( $secret ), 'name' => self::device_name( $ua ), 'created' => time(), 'seen' => time(), ); update_user_meta( $uid, self::DEVICES, array_slice( $devices, -10, null, true ) ); return $selector . '.' . $secret; } /** The owner's user ID if this key is valid, else 0. */ public static function check( $key ) { $parts = explode( '.', (string) $key ); if ( 2 !== count( $parts ) || ! ctype_xdigit( $parts[0] ) || ! ctype_xdigit( $parts[1] ) ) { return 0; } $owner = Nodebook_Node::owner(); $devices = self::devices( $owner ); if ( ! $owner || empty( $devices[ $parts[0] ] ) || ! hash_equals( $devices[ $parts[0] ]['hash'], self::hash( $parts[1] ) ) || ! user_can( $owner, 'manage_options' ) ) { return 0; } if ( $devices[ $parts[0] ]['seen'] < time() - HOUR_IN_SECONDS ) { $devices[ $parts[0] ]['seen'] = time(); update_user_meta( $owner, self::DEVICES, $devices ); } return $owner; } public static function forget( $selector, $user_id = 0 ) { $user_id = $user_id ? (int) $user_id : Nodebook_Node::owner(); $devices = self::devices( $user_id ); unset( $devices[ (string) $selector ] ); update_user_meta( $user_id, self::DEVICES, $devices ); } private static function cookie_key() { return isset( $_COOKIE[ self::COOKIE ] ) ? sanitize_text_field( wp_unslash( $_COOKIE[ self::COOKIE ] ) ) : ''; } private static function set_cookie( $value, $expires ) { if ( headers_sent() ) { return; } setcookie( self::COOKIE, $value, array( 'expires' => $expires, 'path' => self::pretty() ? wp_parse_url( self::url(), PHP_URL_PATH ) : COOKIEPATH, 'secure' => is_ssl(), 'httponly' => true, 'samesite' => 'Lax', ) ); } /** A form token bound to this phone and action. */ private static function token( $action ) { $sel = explode( '.', self::cookie_key() )[0]; return substr( hash_hmac( 'sha256', $action . '|' . $sel, wp_salt( 'nonce' ) ), 0, 20 ); } /** * The hidden fields an app form needs (action, this phone's token, where to go back to), for add-ons * that build their own forms. Post them to Nodebook_App::url(). */ public static function form_fields( $do, $back = '' ) { return ''; } /* ------------------------------------------------------------------ * * Requests * ------------------------------------------------------------------ */ public static function route() { $what = (string) get_query_var( self::VAR ); if ( '' === $what ) { return; } if ( ! defined( 'DONOTCACHEPAGE' ) ) { define( 'DONOTCACHEPAGE', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- shared constant cache plugins read. } nocache_headers(); header( 'X-Robots-Tag: noindex, nofollow' ); header( 'Referrer-Policy: same-origin' ); self::no_cache(); if ( 'legacy' === $what ) { $key = self::cookie_key(); if ( '' !== $key && self::check( $key ) ) { self::set_cookie( $key, time() + YEAR_IN_SECONDS ); wp_safe_redirect( self::url() ); exit; } self::not_found(); return; } if ( 'manifest' === $what ) { self::manifest(); } elseif ( 'sw' === $what ) { self::service_worker(); } elseif ( ! Nodebook_Node::on() && 'off' === Nodebook_Node::personality() ) { self::page( __( 'Node is off', 'nodebook' ), '

' . esc_html__( 'Node is switched off in Settings → Node.', 'nodebook' ) . '

', '', false ); } else { self::app(); if ( self::$hidden ) { return; // WordPress goes on and shows the theme's 404 page. } } exit; } /** Tell page caches (LiteSpeed, WP Rocket, Cloudflare and others) to keep their hands off the app. */ private static function no_cache() { header( 'Cache-Control: no-store, no-cache, must-revalidate, max-age=0, private' ); header( 'X-LiteSpeed-Cache-Control: no-cache' ); header( 'CDN-Cache-Control: no-store' ); do_action( 'litespeed_control_set_nocache', 'nodebook app' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- LiteSpeed Cache's own hook. } private static function manifest() { header( 'Content-Type: application/manifest+json; charset=utf-8' ); $scope = self::pretty() ? wp_parse_url( self::url(), PHP_URL_PATH ) : (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH ); $data = array( 'name' => self::name() . ' · ' . wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), 'short_name' => self::name(), 'description' => __( 'Your little assistant for this site: who to call, what to do, and what is coming in.', 'nodebook' ), 'id' => self::url(), 'start_url' => self::url( '', array( 'app' => 1 ) ), 'scope' => '' !== $scope ? $scope : '/', 'display' => 'standalone', 'orientation' => 'portrait', 'background_color' => '#f7f7f8', 'theme_color' => '#f7f7f8', 'icons' => array( array( 'src' => NODEBOOK_URL . 'assets/img/app-192.png', 'sizes' => '192x192', 'type' => 'image/png', ), array( 'src' => NODEBOOK_URL . 'assets/img/app-512.png', 'sizes' => '512x512', 'type' => 'image/png', ), array( 'src' => NODEBOOK_URL . 'assets/img/app-maskable.png', 'sizes' => '512x512', 'type' => 'image/png', 'purpose' => 'maskable', ), ), ); /** * The phone app's manifest (name, colours, icons). * * @param array $data Manifest. */ $data = (array) apply_filters( 'nodebook_app_manifest', $data ); echo wp_json_encode( $data ); } /** The phone app's name ("Node", or a white-label name). */ public static function name() { $n = trim( wp_strip_all_tags( (string) apply_filters( 'nodebook_app_name', 'Node' ) ) ); return '' !== $n ? mb_substr( $n, 0, 30 ) : 'Node'; } /** Offline: the last screens you opened stay readable; everything else goes to the network first. */ private static function service_worker() { header( 'Content-Type: application/javascript; charset=utf-8' ); $cache = 'nodebook-app-' . NODEBOOK_VERSION; $shell = array( self::url(), nodebook_asset( 'css/app.css' ) . '?ver=' . NODEBOOK_VERSION, nodebook_asset( 'js/app.js' ) . '?ver=' . NODEBOOK_VERSION, NODEBOOK_URL . 'assets/img/app-192.png' ); echo 'const CACHE = ' . wp_json_encode( $cache ) . ";\nconst SHELL = " . wp_json_encode( $shell ) . ";\n"; echo <<<'JS' self.addEventListener('install', function (e) { e.waitUntil(caches.open(CACHE).then(function (c) { return c.addAll(SHELL); }).catch(function () {}).then(function () { return self.skipWaiting(); })); }); self.addEventListener('activate', function (e) { e.waitUntil(caches.keys().then(function (keys) { return Promise.all(keys.filter(function (k) { return k.indexOf('nodebook-app-') === 0 && k !== CACHE; }).map(function (k) { return caches.delete(k); })); }).then(function () { return self.clients.claim(); })); }); self.addEventListener('fetch', function (e) { var req = e.request; if (req.method !== 'GET') { return; } var url = new URL(req.url); if (url.origin !== self.location.origin) { return; } if (req.mode === 'navigate') { e.respondWith(fetch(req).then(function (res) { if (res.ok) { var copy = res.clone(); caches.open(CACHE).then(function (c) { c.put(req, copy); }); } return res; }).catch(function () { return caches.match(req).then(function (hit) { return hit || caches.match(SHELL[0]); }); })); return; } if (SHELL.indexOf(req.url) !== -1) { e.respondWith(caches.match(req).then(function (hit) { return hit || fetch(req); })); } }); self.addEventListener('message', function (e) { if (e.data === 'forget') { caches.keys().then(function (keys) { keys.forEach(function (k) { if (k.indexOf('nodebook-app-') === 0) { caches.delete(k); } }); }); } }); JS; } /** Pair, act, or show a screen. */ private static function app() { // phpcs:disable WordPress.Security.NonceVerification -- the phone's own form token (token()) is checked for every action; pairing is protected by a one-time code and throttling. $method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_key( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : 'GET'; if ( 'POST' === $method && isset( $_POST['pair'] ) ) { $ua = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : ''; $key = self::pair( sanitize_text_field( wp_unslash( $_POST['pair'] ) ), $ua ); if ( is_wp_error( $key ) ) { self::pair_screen( $key->get_error_message() ); return; } self::set_cookie( $key, time() + YEAR_IN_SECONDS ); wp_safe_redirect( self::url( '', array( 'hello' => 1 ) ) ); return; } $owner = self::check( self::cookie_key() ); if ( ! $owner ) { // Only phones that arrive with a code (the QR link), a phone that was connected before, or the // installed app itself see the code screen. Everyone else: page not found. $invited = isset( $_GET['pair'] ) || isset( $_GET['app'] ) || isset( $_GET['bye'] ) || '' !== self::cookie_key(); if ( ! $invited ) { self::not_found(); return; } self::pair_screen(); return; } wp_set_current_user( $owner ); if ( 'POST' === $method ) { $do = isset( $_POST['do'] ) ? sanitize_key( wp_unslash( $_POST['do'] ) ) : ''; $t = isset( $_POST['t'] ) ? sanitize_text_field( wp_unslash( $_POST['t'] ) ) : ''; if ( '' === $do || ! hash_equals( self::token( $do ), $t ) ) { wp_safe_redirect( self::url( '', array( 'msg' => 'expired' ) ) ); return; } self::act( $do, $owner ); return; } $view = isset( $_GET['view'] ) ? sanitize_key( wp_unslash( $_GET['view'] ) ) : 'today'; if ( 'contact' === $view ) { self::contact_screen( isset( $_GET['id'] ) ? absint( $_GET['id'] ) : 0 ); } elseif ( 'search' === $view ) { self::search_screen( isset( $_GET['q'] ) ? sanitize_text_field( wp_unslash( $_GET['q'] ) ) : '' ); } elseif ( 'more' === $view ) { self::more_screen(); } elseif ( 'email' === $view ) { self::email_screen( isset( $_GET['id'] ) ? absint( $_GET['id'] ) : 0, isset( $_GET['kind'] ) ? sanitize_key( wp_unslash( $_GET['kind'] ) ) : '' ); } elseif ( has_action( 'nodebook_app_view_' . $view ) ) { /** A screen from an add-on (it prints a page with Nodebook_App::page()). */ do_action( 'nodebook_app_view_' . $view ); } else { self::today_screen(); } // phpcs:enable } /** Set when this request should look like any missing page. */ private static $hidden = false; /** The site's own 404 (classic or block theme), as if nothing lived here. */ private static function not_found() { global $wp_query; $wp_query->set_404(); status_header( 404 ); self::$hidden = true; } /** Handle a button from the app, then go back (post/redirect/get). */ private static function act( $do, $owner ) { // phpcs:disable WordPress.Security.NonceVerification.Missing -- checked by the caller (token()). $id = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0; $back = isset( $_POST['back'] ) ? esc_url_raw( wp_unslash( $_POST['back'] ) ) : self::url(); $back = wp_validate_redirect( $back, self::url() ); $msg = 'saved'; switch ( $do ) { case 'later': Nodebook_Node::dismiss( isset( $_POST['key'] ) ? sanitize_text_field( wp_unslash( $_POST['key'] ) ) : '', $owner ); $msg = 'later'; break; case 'task': $task = Nodebook_Tasks::get( $id ); if ( $task && ( ! $task['contact_id'] || Nodebook_Team::can_see( (int) $task['contact_id'] ) ) ) { Nodebook_Tasks::complete( $id, '', $owner ); } $msg = 'task'; break; case 'followed': if ( Nodebook_Team::can_see( $id ) ) { Nodebook_Followup::mark_done( $id, $owner ); } $msg = 'followed'; break; case 'note': $text = isset( $_POST['note'] ) ? sanitize_textarea_field( wp_unslash( $_POST['note'] ) ) : ''; $channel = isset( $_POST['channel'] ) ? sanitize_key( wp_unslash( $_POST['channel'] ) ) : 'note'; if ( $id && Nodebook_Team::can_see( $id ) && Nodebook_Contacts::get( $id ) ) { if ( isset( Nodebook_Followup::channels()[ $channel ] ) ) { Nodebook_Followup::log_touch( $id, $channel, $text, $owner ); } elseif ( '' !== trim( $text ) ) { Nodebook_Activities::add( $id, 'note', wp_trim_words( $text, 12, '…' ), array( 'user_id' => $owner, 'data' => array( 'text' => $text ), ) ); } // The next step becomes a task, like on the computer. $title = isset( $_POST['task_title'] ) ? sanitize_text_field( wp_unslash( $_POST['task_title'] ) ) : ''; $when = isset( $_POST['remind'] ) ? sanitize_key( wp_unslash( $_POST['remind'] ) ) : ''; $date = isset( $_POST['remind_date'] ) ? sanitize_text_field( wp_unslash( $_POST['remind_date'] ) ) : ''; $due = '' !== $when ? Nodebook_Tasks::due_from( $when, $date ) : null; if ( '' !== trim( $title ) || $due ) { $team = Nodebook_Team::users(); $who = isset( $_POST['assignee'] ) ? absint( $_POST['assignee'] ) : $owner; Nodebook_Tasks::add( $id, '' !== trim( $title ) ? $title : __( 'Follow up', 'nodebook' ), array( 'due_at' => $due, 'assignee_id' => isset( $team[ $who ] ) ? $who : $owner, 'created_by' => $owner, ) ); } } $msg = 'note'; break; case 'email': $subject = isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : ''; $body = isset( $_POST['body'] ) ? sanitize_textarea_field( wp_unslash( $_POST['body'] ) ) : ''; $kind = isset( $_POST['kind'] ) ? sanitize_key( wp_unslash( $_POST['kind'] ) ) : ''; if ( ! $id || ! Nodebook_Team::can_see( $id ) ) { break; } $sent = Nodebook_Email::send( $id, $subject, $body, $owner ); if ( is_wp_error( $sent ) ) { set_transient( 'nodebook_app_mailerr_' . $owner, $sent->get_error_message(), 120 ); $back = self::url( '', array( 'view' => 'email', 'id' => $id, 'kind' => $kind, ) ); $msg = 'emailfail'; break; } if ( 'review' === $kind ) { Nodebook_Reviews::mark( $id, 'email', $owner ); } $back = self::contact_url( $id ); $msg = 'emailsent'; break; case 'review_wa': $c = $id && Nodebook_Team::can_see( $id ) ? Nodebook_Contacts::get( $id ) : null; $n = $c ? Nodebook_Phone::international( (string) $c['phone'], (string) ( $c['country'] ?? '' ) ) : ''; if ( $c && $n && '' !== Nodebook_Reviews::url() ) { Nodebook_Reviews::mark( $id, 'whatsapp', $owner ); Nodebook_Node::flush( $owner ); list( , $text ) = Nodebook_Reviews::message( $c ); // Straight on to WhatsApp with the message ready. wp_redirect( 'https://wa.me/' . $n . '?text=' . rawurlencode( $text ) ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- WhatsApp's own address, built here. exit; } break; case 'inbox_read': update_user_meta( $owner, Nodebook_Mentions::READ, time() ); $msg = ''; break; case 'forget': self::forget( explode( '.', self::cookie_key() )[0], $owner ); self::set_cookie( '', time() - DAY_IN_SECONDS ); $back = self::url( '', array( 'bye' => 1 ) ); $msg = ''; break; default: /** * A button from an add-on in the phone app. Return the message key to show, or '' for none. * * @param string $msg Default "saved". * @param string $do The action. * @param int $id The id field. * @param int $owner The person using the app. */ $msg = (string) apply_filters( 'nodebook_app_act', $msg, $do, $id, $owner ); break; } Nodebook_Node::flush( $owner ); wp_safe_redirect( $msg ? add_query_arg( 'msg', $msg, remove_query_arg( 'msg', $back ) ) : $back ); exit; // phpcs:enable } /* ------------------------------------------------------------------ * * Screens * ------------------------------------------------------------------ */ /** A one-button form with the phone's own token (add-ons use it too). */ public static function form( $do, $fields, $button, $class = 'na-btn' ) { $h = '
'; foreach ( $fields as $k => $v ) { $h .= ''; } return $h . '
'; } private static function here() { $uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_url( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; return home_url( (string) $uri ); } public static function contact_url( $id ) { return self::url( '', array( 'view' => 'contact', 'id' => (int) $id, ) ); } /** Where a focus item leads inside the app (people, tasks, deals), or its admin screen. */ private static function item_link( array $item ) { if ( ! empty( $item['who'] ) && false === strpos( (string) $item['action'][1], 'page=nodebook-today' ) ) { return self::contact_url( $item['who'] ); } $map = array( 'asked' => '#na-waiting', 'late' => '#na-tasks', 'tasks' => '#na-tasks', 'ordered' => '#na-deals', 'deals' => '#na-deals', 'reorder' => '#na-reorder', ); if ( isset( $map[ $item['kind'] ] ) ) { return $map[ $item['kind'] ]; } return $item['action'][1]; } /** A round avatar with the same colour as on the computer. */ private static function avatar( $name, $seed, $big = false ) { $words = preg_split( '/[\s@._-]+/u', trim( (string) $name ), -1, PREG_SPLIT_NO_EMPTY ); $init = $words ? mb_substr( $words[0], 0, 1 ) . ( count( $words ) > 1 && false === strpos( (string) $name, '@' ) ? mb_substr( end( $words ), 0, 1 ) : '' ) : '?'; $tone = absint( crc32( strtolower( (string) $seed ) ) ) % 8; return ''; } private static function icon( $name, $size = 20 ) { return wp_kses( Nodebook_Icons::svg( $name, $size ), Nodebook_Icons::kses() ); } /** The "likely to buy" number next to a name. */ private static function score_chip( array $c ) { if ( ! isset( $c['score'] ) || null === $c['score'] ) { return ''; } $s = (int) $c['score']; $tone = $s >= 75 ? 'hot' : ( $s >= 60 ? 'warm' : ( $s >= 40 ? 'mild' : 'cold' ) ); /* translators: %s: score */ return ' ' . esc_html( (string) $s ) . ''; } /** "Best: weekday evenings" under a name, when there is a clear pattern. */ private static function best_line( $id ) { $best = Nodebook_Insights::best_time( (int) $id ); if ( ! $best ) { return ''; } return '' . esc_html( $best['now'] ? __( 'Good moment to reach them now', 'nodebook' ) : $best['text'] ) . ''; } /** On a contact: likely to buy (with why), best time, buying rhythm. */ private static function insights_html( array $c ) { $h = ''; $x = Nodebook_Insights::explain( $c ); if ( null !== $x['score'] ) { $h .= '
' . esc_html__( 'Likely to buy', 'nodebook' ) . '' . self::score_chip( $c ) . ' ' . esc_html( $x['label'] ) . ''; if ( $x['reasons'] ) { $h .= ''; } $h .= '

' . esc_html( $x['learned'] ? __( 'Compared with the people who bought from you before.', 'nodebook' ) : __( 'Based on how small businesses usually sell. It learns from your own customers as sales come in.', 'nodebook' ) ) . '

'; } $best = Nodebook_Insights::best_time( (int) $c['id'] ); if ( $best ) { $h .= '
' . esc_html__( 'Best time to reach', 'nodebook' ) . '' . esc_html( $best['text'] ) . ( $best['now'] ? ' · ' . esc_html__( 'now', 'nodebook' ) : '' ) . '
'; } $rhythm = Nodebook_Insights::reorder_of( (int) $c['id'] ); if ( $rhythm ) { $h .= '
' . esc_html__( 'Due to reorder', 'nodebook' ) . '' . esc_html( sprintf( /* translators: 1: "every 6 weeks", 2: "9 weeks" */ __( 'Buys %1$s · last %2$s ago', 'nodebook' ), Nodebook_Insights::every( $rhythm['every'] ), Nodebook_Insights::span( (int) floor( ( time() - strtotime( $rhythm['last'] . ' UTC' ) ) / DAY_IN_SECONDS ) ) ) ) . '
'; } return '' !== $h ? '
' . $h . '
' : ''; } /** Address of the compose screen for a contact. */ private static function email_url( $id, $kind = '' ) { return self::url( '', array_filter( array( 'view' => 'email', 'id' => (int) $id, 'kind' => $kind ) ) ); } /** * Call, WhatsApp, Email (in the app) and, with a review link, Review. * * @param array $c Contact. * @param bool $tiles Big tiles with icons (contact card) or small buttons (lists). * @param bool $review Show the Review button. */ private static function actions_html( array $c, $tiles = false, $review = false ) { $h = ''; $icons = array( 'call' => 'phone', 'whatsapp' => 'message', 'email' => 'mail', ); foreach ( Nodebook_Followup::actions( $c ) as $a ) { $url = 'email' === $a['kind'] ? self::email_url( (int) $c['id'] ) : $a['url']; $h .= '' . ( $tiles ? self::icon( $icons[ $a['kind'] ] ?? 'external', 22 ) : '' ) . '' . esc_html( $a['label'] ) . ''; } if ( $review ) { $h .= self::review_button( $c, $tiles ); } return $h; } /** Ask for a review: by email in the app, or straight to WhatsApp (logged first). */ private static function review_button( array $c, $tiles ) { if ( '' === Nodebook_Reviews::url() || ! Nodebook_Reviews::can_ask( $c ) ) { return ''; } $label = __( 'Review', 'nodebook' ); $inner = ( $tiles ? self::icon( 'star', 22 ) : '' ) . '' . esc_html( $label ) . ''; $cls = 'na-act na-act--review' . ( $tiles ? ' na-tile' : '' ); if ( is_email( (string) $c['email'] ) && 'complained' !== (string) ( $c['email_status'] ?? '' ) ) { return '' . $inner . ''; } return '
'; } private static function flash() { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- message display only. $msg = isset( $_GET['msg'] ) ? sanitize_key( wp_unslash( $_GET['msg'] ) ) : ''; $map = array( 'saved' => __( 'Saved.', 'nodebook' ), 'later' => __( 'Okay, later.', 'nodebook' ), 'task' => __( 'Task done. Nice!', 'nodebook' ), 'followed' => __( 'Marked as followed up.', 'nodebook' ), 'note' => __( 'Logged.', 'nodebook' ), 'expired' => __( 'That took a while: please try again.', 'nodebook' ), 'emailsent' => __( 'Email sent. It is on their timeline.', 'nodebook' ), ); $map = (array) apply_filters( 'nodebook_app_messages', $map ); if ( isset( $_GET['hello'] ) ) { return '

' . esc_html__( 'Connected! Now add me to your home screen: Share → Add to Home Screen (iPhone) or ⋮ → Add to Home screen (Android).', 'nodebook' ) . '

'; } // phpcs:enable return isset( $map[ $msg ] ) ? '

' . esc_html( $map[ $msg ] ) . '

' : ''; } /** One full HTML page in the app's frame. */ public static function page( $title, $body, $tab = '', $nav = true ) { $ver = NODEBOOK_VERSION; echo ''; echo '' . esc_html( $title . ' · ' . self::name() ) . ''; echo ''; echo ''; // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- standalone app page without the theme. /** Add-ons can add their styles to the phone app. */ do_action( 'nodebook_app_head' ); $strip = $nav && class_exists( 'Nodebook_Sample' ) && Nodebook_Sample::present() ? '

' . esc_html__( 'You are looking at sample data. Remove it on your computer under Import & Export.', 'nodebook' ) . '

' : ''; echo '
' . $strip . self::flash() . $body . '
'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- screens are built from escaped parts. if ( $nav ) { echo ''; } echo ''; // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- standalone app page without the theme. } private static function pair_screen( $error = '' ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- prefill only. $code = isset( $_GET['pair'] ) ? preg_replace( '/\D/', '', sanitize_text_field( wp_unslash( $_GET['pair'] ) ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- message only. $bye = isset( $_GET['bye'] ); $body = '
' . Nodebook_Node::blob( $bye ? 'calm' : 'hello', 88 ) . '

' . esc_html( $bye ? __( 'See you!', 'nodebook' ) : __( 'Hi, I’m Node', 'nodebook' ) ) . '

'; $body .= '

' . esc_html( sprintf( /* translators: %s: site name */ __( 'Connect this phone to %s. On your computer, open Nodebook → Settings → Node and press “Connect a phone”. Then type the code here.', 'nodebook' ), wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) ) ) . '

'; if ( '' !== $error ) { $body .= ''; } $body .= '
'; self::page( __( 'Connect', 'nodebook' ), $body, '', false ); } private static function today_screen() { $owner = get_current_user_id(); $team = Nodebook_Team::is_team(); $who = $team ? $owner : 0; $items = Nodebook_Node::focus( $owner ); $name = Nodebook_Node::user_first( $owner ); $b = '
' . Nodebook_Node::blob( Nodebook_Node::mood( $items ), 64 ) . '

' . esc_html( Nodebook_Node::headline( $items, $name ) ) . '

'; $inbox = Nodebook_Mentions::unread( $owner ); if ( $inbox ) { $b .= '

' . esc_html__( 'For you', 'nodebook' ) . ' ' . esc_html( number_format_i18n( count( $inbox ) ) ) . '' . self::form( 'inbox_read', array(), __( 'Mark as read', 'nodebook' ), 'na-link na-link--right' ) . '

'; } if ( $items ) { $b .= '
    '; foreach ( $items as $i => $item ) { $link = self::item_link( $item ); $ext = 0 === strpos( $link, admin_url() ); $b .= '
  1. ' . esc_html( $item['text'] ) . '

    ' . esc_html( $item['action'][0] ) . '' . self::form( 'later', array( 'key' => $item['key'] ), __( 'Not now', 'nodebook' ), 'na-link' ) . '
  2. '; } $b .= '
'; } $waiting = array_values( array_filter( Nodebook_Followup::due( 30, $who ), array( 'Nodebook_Followup', 'is_due' ) ) ); if ( $waiting ) { $b .= '

' . esc_html__( 'Follow up', 'nodebook' ) . ' ' . esc_html( number_format_i18n( count( $waiting ) ) ) . '

'; } $tasks = Nodebook_Tasks::due( $who, '', Nodebook_Tasks::end_of_today(), 20 ); if ( $tasks ) { $b .= '

' . esc_html__( 'Tasks', 'nodebook' ) . ' ' . esc_html( number_format_i18n( count( $tasks ) ) ) . '

'; } $reorder = Nodebook_Insights::reorder_due( $who, 10 ); if ( $reorder ) { $b .= '

' . esc_html__( 'Due to reorder', 'nodebook' ) . ' ' . esc_html( number_format_i18n( count( $reorder ) ) ) . '

'; } $deals = ! Nodebook_Deals::on() ? array() : Nodebook_Deals::query( array( 'owner' => $who, 'closing_before' => wp_date( 'Y-m-d', time() + 7 * DAY_IN_SECONDS ), 'order' => 'close', 'limit' => 10, ) ); $have = array_map( 'intval', wp_list_pluck( $deals, 'id' ) ); foreach ( Nodebook_Deals::on() ? Nodebook_Deals::ordered( $who ) : array() as $od ) { if ( ! in_array( (int) $od['id'], $have, true ) ) { array_unshift( $deals, $od ); } } if ( $deals ) { $b .= '

' . esc_html__( 'Deals to close', 'nodebook' ) . ' ' . esc_html( number_format_i18n( count( $deals ) ) ) . '

'; } if ( ! $items && ! $waiting && ! $tasks && ! $deals && ! $inbox && ! $reorder ) { $b .= '

' . esc_html__( 'Nothing waiting. New inquiries, tasks and people showing interest show up here.', 'nodebook' ) . '

'; } self::page( __( 'Today', 'nodebook' ), $b, 'today' ); } private static function search_screen( $q ) { $b = ''; $r = Nodebook_Contacts::query( array( 'search' => $q, 'per_page' => 30, 'orderby' => '' === $q ? 'last_seen' : 'created_at', ) ); if ( $r['rows'] ) { $b .= ''; } elseif ( '' !== $q ) { $b .= '

' . esc_html__( 'Nobody found.', 'nodebook' ) . '

'; } self::page( __( 'Search', 'nodebook' ), $b, 'search' ); } private static function contact_screen( $id ) { $c = $id && Nodebook_Team::can_see( $id ) ? Nodebook_Contacts::get( $id ) : null; if ( ! $c ) { self::page( __( 'Not found', 'nodebook' ), '

' . esc_html__( 'This contact does not exist (anymore).', 'nodebook' ) . '

', 'search' ); return; } $name = Nodebook_Contacts::display_name( $c ); $company = $c['company_id'] ? Nodebook_Companies::get( (int) $c['company_id'] ) : null; $status = Nodebook_Fields::statuses()[ $c['status'] ] ?? $c['status']; $b = '
' . self::avatar( $name, 'c' . (int) $c['id'], true ) . '

' . esc_html( $name ) . '

' . esc_html( trim( $status . ( $company ? ' · ' . $company['name'] : '' ) ) ) . '

'; $tip = Nodebook_Node::on() ? Nodebook_Node::contact_tip( $c ) : null; if ( $tip ) { $b .= '
' . Nodebook_Node::blob( $tip['mood'], 28 ) . '

' . esc_html( $tip['text'] ) . '

'; } if ( ! empty( $c['pinned'] ) ) { $b .= '

📌 ' . esc_html( (string) $c['pinned'] ) . '

'; } $acts = self::actions_html( $c, true, true ); if ( '' !== $acts ) { $b .= '
' . $acts . '
'; } if ( Nodebook_Followup::is_due( $c ) ) { $b .= self::form( 'followed', array( 'id' => (int) $c['id'] ), __( 'Mark as followed up', 'nodebook' ), 'na-btn na-btn--wide' ); } $b .= '
'; foreach ( array( __( 'Email', 'nodebook' ) => $c['email'], __( 'Phone', 'nodebook' ) => $c['phone'], __( 'City', 'nodebook' ) => trim( (string) $c['city'] . ( $c['country'] ? ', ' . Nodebook_Admin::country_name( (string) $c['country'] ) : '' ), ', ' ), ) as $k => $v ) { if ( '' !== (string) $v ) { $b .= '
' . esc_html( $k ) . '
' . esc_html( (string) $v ) . '
'; } } $b .= '
'; $b .= self::insights_html( $c ); // Log a call, message or note. $b .= '
'; foreach ( array_merge( array( 'note' => __( 'Note', 'nodebook' ) ), Nodebook_Followup::channels() ) as $k => $label ) { $b .= ''; } $team = Nodebook_Team::is_team(); $people = $team ? wp_json_encode( array_values( Nodebook_Mentions::people() ) ) : ''; $b .= '
'; $b .= '
' . esc_html__( 'Add a next step', 'nodebook' ) . '
'; if ( $team ) { $b .= ''; } $b .= '
'; $tasks = Nodebook_Tasks::for_contact( (int) $c['id'], 0 ); if ( $tasks['open'] ) { $b .= '

' . esc_html__( 'Tasks', 'nodebook' ) . '

'; } /** * Extra sections on a contact in the phone app (before "Lately"). * * @param string $html Escaped HTML. * @param array $c Contact. */ $b .= (string) apply_filters( 'nodebook_app_contact_sections', '', $c ); $rows = Nodebook_Activities::for_contact( (int) $c['id'], 12 ); if ( $rows ) { $b .= '

' . esc_html__( 'Lately', 'nodebook' ) . '

'; } $b .= '

' . esc_html__( 'Open in WordPress', 'nodebook' ) . ' ↗

'; self::page( $name, $b, '' ); } /** Write an email (or a review request) and send it from the site. */ private static function email_screen( $id, $kind ) { $c = $id && Nodebook_Team::can_see( $id ) ? Nodebook_Contacts::get( $id ) : null; if ( ! $c || ! is_email( (string) $c['email'] ) ) { self::page( __( 'Not found', 'nodebook' ), '

' . esc_html__( 'This contact has no email address.', 'nodebook' ) . '

', '' ); return; } $review = 'review' === $kind && '' !== Nodebook_Reviews::url(); if ( $review ) { list( $subject, $body ) = Nodebook_Reviews::message( $c ); } else { $topic = Nodebook_Followup::topic( (int) $c['id'] ); $subject = $topic ? $topic['title'] : wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); $body = Nodebook_Followup::message( $c ); } $name = Nodebook_Contacts::display_name( $c ); $err = get_transient( 'nodebook_app_mailerr_' . get_current_user_id() ); if ( $err ) { delete_transient( 'nodebook_app_mailerr_' . get_current_user_id() ); } $warn = Nodebook_Email::warning( $c ); $b = '
' . esc_html__( 'Cancel', 'nodebook' ) . '

' . esc_html( $review ? __( 'Ask for a review', 'nodebook' ) : __( 'New email', 'nodebook' ) ) . '

'; $b .= '
'; $b .= '

' . esc_html__( 'To', 'nodebook' ) . '' . esc_html( $name . ' <' . $c['email'] . '>' ) . '

'; if ( $err ) { $b .= ''; } if ( '' !== $warn ) { $b .= '

' . esc_html( $warn ) . '

'; } $templates = $review ? array() : Nodebook_Followup::templates(); if ( $templates ) { $user = wp_get_current_user(); $tags = array( '{first_name}' => trim( (string) $c['first_name'] ), '{item}' => $subject, '{site}' => wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), '{my_name}' => $user->first_name ? $user->first_name : $user->display_name, ); $b .= ''; } $b .= ''; $b .= '
'; $b .= '

' . esc_html__( 'Sent from your site. Replies come to your own inbox, and it goes on their timeline.', 'nodebook' ) . '

'; $b .= ''; $b .= '

' . esc_html__( 'Open in my mail app instead', 'nodebook' ) . '

'; self::page( $review ? __( 'Ask for a review', 'nodebook' ) : __( 'New email', 'nodebook' ), $b, '' ); } private static function more_screen() { $owner = get_current_user_id(); $b = '
' . Nodebook_Node::blob( 'calm', 56 ) . '

' . esc_html( wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) ) . '

'; /** * Extra sections on the More screen of the phone app. * * @param string $html Escaped HTML. */ $b .= (string) apply_filters( 'nodebook_app_more_sections', '' ); $b .= '

' . esc_html( sprintf( /* translators: %s: user name */ __( 'Connected as %s. This phone stays connected until you disconnect it here or in Settings → Node.', 'nodebook' ), Nodebook_Node::user_first( $owner ) ) ) . '

' . self::form( 'forget', array(), __( 'Disconnect this phone', 'nodebook' ), 'na-btn na-btn--danger' ); self::page( __( 'More', 'nodebook' ), $b, 'more' ); } }