status || ( $entry->is_bot && ! AARYE_Settings::on( 'sheets_bots' ) ) ) { return; } $queue = (array) get_option( self::QUEUE, array() ); $queue[] = array( 'id' => (int) $id, 'tries' => 0, ); update_option( self::QUEUE, array_slice( $queue, -500 ), false ); AARYE_Async::kick(); } /** * Send queued rows. A failed row is tried again after 5 minutes, then every hour, up to 24 times. */ public static function process() { if ( ! self::enabled() || get_transient( 'aarye_sheets_lock' ) ) { return; } $queue = array_values( (array) get_option( self::QUEUE, array() ) ); if ( ! $queue || ( isset( $queue[0]['next'] ) && $queue[0]['next'] > time() ) ) { return; } set_transient( 'aarye_sheets_lock', 1, 120 ); $done = array(); $failed = array(); foreach ( array_slice( $queue, 0, 50 ) as $item ) { $entry = AARYE_Entries::get( $item['id'] ); if ( ! $entry || true === self::send( $entry ) ) { $done[] = (int) $item['id']; } elseif ( $item['tries'] >= 23 ) { $done[] = (int) $item['id']; // Give up after a day. } else { $failed[ (int) $item['id'] ] = $item['tries'] + 1; break; // Keep rows in order: stop at the first failure and try again later. } } // Re-read: new entries may have been queued meanwhile. $left = array(); foreach ( (array) get_option( self::QUEUE, array() ) as $item ) { if ( in_array( (int) $item['id'], $done, true ) ) { continue; } if ( isset( $failed[ (int) $item['id'] ] ) ) { $item['tries'] = $failed[ (int) $item['id'] ]; $item['next'] = time() + ( 1 === $item['tries'] ? 5 * MINUTE_IN_SECONDS : HOUR_IN_SECONDS ); } $left[] = $item; } update_option( self::QUEUE, $left, false ); delete_transient( 'aarye_sheets_lock' ); } /** * The row for an entry: column title => value. Every form field gets its own column. * * @param object $entry Entry. * @return array */ public static function row( $entry ) { $row = array( 'Entry ID' => (string) $entry->id, 'Date' => get_date_from_gmt( $entry->created_at, 'Y-m-d H:i:s' ), 'Form' => $entry->form_name, 'Name' => $entry->name, 'Email' => $entry->email, 'Phone' => $entry->phone, 'Source' => $entry->source_label, 'Channel' => AARYE_Sources::channel_label( $entry->channel ), 'From an ad' => 'paid' === $entry->channel ? 'Yes' : 'No', 'Campaign' => $entry->campaign, 'Ad set / ad group' => $entry->ad_group, 'Ad' => $entry->ad, 'Keyword' => $entry->keyword, 'Click ID' => '' !== $entry->click_id ? $entry->click_param . '=' . $entry->click_id : '', 'Landing page' => (string) $entry->landing_page, 'Referrer' => (string) $entry->referrer, 'Form page' => (string) $entry->page_url, 'Language' => $entry->language, 'Device' => $entry->device, 'Visits before' => (string) $entry->visits, ); $check = AARYE_Evidence::analyse( $entry ); $row['Source proof'] = $check['proof']['label']; $row['Spam check'] = $check['label']; $row['Spam score'] = (string) $check['score']; $row['Spam check reasons'] = implode( '; ', $check['reasons'] ); foreach ( AARYE_Entries::json( $entry, 'fields' ) as $field ) { $title = '' !== $field['label'] ? $field['label'] : $field['name']; if ( isset( $row[ $title ] ) ) { $title = 'Field: ' . $title; } $row[ $title ] = $field['value']; } $links = array(); foreach ( AARYE_Entries::json( $entry, 'files' ) as $i => $file ) { // Public upload address when the form plugin keeps one, else the entry in WordPress (login needed). $links[] = '' !== $file['url'] ? $file['url'] : admin_url( 'admin.php?page=aarye-leads-entries&entry=' . (int) $entry->id ); } if ( $links ) { $row['Files'] = implode( "\n", $links ); } // Spreadsheets treat text starting with = + - @ as formulas: keep values as plain text. foreach ( $row as $key => $value ) { if ( '' !== $value && in_array( substr( $value, 0, 1 ), array( '=', '+', '-', '@' ), true ) ) { $row[ $key ] = "'" . $value; } } /** * Change the Google Sheets row of an entry. * * @param array $row Column title => value. * @param object $entry Entry. */ return (array) apply_filters( 'aarye_sheets_row', $row, $entry ); } /** * Post to the web app. * * @param object|null $entry Entry, or null for a connection test. * @return bool|string True on success, error message when waiting. */ public static function send( $entry ) { $body = array( 'secret' => (string) AARYE_Settings::get( 'sheets_secret' ) ); if ( null === $entry ) { $body['test'] = true; } else { $row = self::row( $entry ); $body['sheet'] = AARYE_Settings::on( 'sheets_tab_per_form' ) ? mb_substr( preg_replace( '/[\[\]\*\?\/\\\\:]/', ' ', $entry->form_name ? $entry->form_name : 'Leads' ), 0, 90 ) : 'Leads'; $body['headers'] = array_keys( $row ); $body['row'] = $row; } // Google runs the script on this POST, then redirects to the script's reply, which must be read // with GET. Follow that redirect here, so it works whatever HTTP transport the site uses. $response = wp_remote_post( (string) AARYE_Settings::get( 'sheets_url' ), array( 'timeout' => 20, 'redirection' => 0, 'headers' => array( 'Content-Type' => 'application/json' ), 'body' => wp_json_encode( $body ), ) ); $code = (int) wp_remote_retrieve_response_code( $response ); if ( ! is_wp_error( $response ) && in_array( $code, array( 301, 302, 303, 307, 308 ), true ) ) { $location = (string) wp_remote_retrieve_header( $response, 'location' ); if ( false !== strpos( $location, 'accounts.google.com' ) ) { // Google wants a sign-in: the web app is not open to "Anyone". return null === $entry ? self::explain( 401, $location ) : false; } if ( '' !== $location ) { $response = wp_remote_get( $location, array( 'timeout' => 20, 'redirection' => 3, ) ); $code = (int) wp_remote_retrieve_response_code( $response ); } } if ( is_wp_error( $response ) ) { return null === $entry ? $response->get_error_message() : false; } $text = (string) wp_remote_retrieve_body( $response ); $reply = json_decode( $text, true ); if ( is_array( $reply ) && ! empty( $reply['ok'] ) ) { return true; } if ( null === $entry ) { if ( is_array( $reply ) && ! empty( $reply['error'] ) ) { return (string) $reply['error']; } return self::explain( $code, $text ); } return false; } /** * Why Google's answer was not the script's reply, in words. * * @param int $code HTTP status. * @param string $text Body. * @return string */ private static function explain( $code, $text ) { $url = (string) AARYE_Settings::get( 'sheets_url' ); if ( false === strpos( $url, 'script.google.com' ) || '/exec' !== substr( untrailingslashit( (string) wp_parse_url( $url, PHP_URL_PATH ) ), -5 ) ) { return __( 'This is not a web app address. In Apps Script use Deploy → Manage deployments and copy the "Web app URL": it starts with https://script.google.com/ and ends with /exec (not /dev, and not the editor\'s address).', 'aarye-marketing-addon' ); } if ( false !== strpos( $url, '/a/macros/' ) && ( false !== stripos( $text, 'accounts.google.com' ) || false !== stripos( $text, 'ServiceLogin' ) || 401 === $code || 403 === $code ) ) { return __( 'Your web app belongs to a Google Workspace (company) account, where "Anyone" can mean "anyone in your company". In Deploy → Manage deployments → edit, choose "Anyone" (the option without your domain name). If it is missing, your Workspace admin blocks public web apps: create the spreadsheet and script with a personal Gmail account instead.', 'aarye-marketing-addon' ); } if ( false !== stripos( $text, 'Authorization is required' ) || false !== stripos( $text, 'authorization' ) && false !== stripos( $text, 'required' ) ) { return __( 'The script was not authorised yet. In Apps Script, select the doPost function, click Run once and allow access, then Deploy → Manage deployments → edit → New version → Deploy.', 'aarye-marketing-addon' ); } if ( false !== stripos( $text, 'accounts.google.com' ) || false !== stripos( $text, 'ServiceLogin' ) ) { return __( 'Google asked for a sign-in: in Apps Script open Deploy → Manage deployments → edit (pencil), set "Who has access" to "Anyone" (not "Anyone with Google account"), and deploy.', 'aarye-marketing-addon' ); } if ( false !== stripos( $text, 'doPost' ) ) { return __( 'The web app does not have the script yet: paste the script again, click Save, then Deploy → Manage deployments → edit (pencil) → Version: New version → Deploy.', 'aarye-marketing-addon' ); } if ( 404 === $code ) { return __( 'Google says this web app address does not exist. Copy the "Web app URL" (ending in /exec) from Deploy → Manage deployments again.', 'aarye-marketing-addon' ); } if ( false !== stripos( $text, 'TypeError' ) || false !== stripos( $text, 'Exception' ) ) { /* translators: %s: error from Google. */ return sprintf( __( 'The script stopped with an error: %s. Paste the script from this page again, save, and deploy a new version.', 'aarye-marketing-addon' ), mb_substr( wp_strip_all_tags( $text ), 0, 200 ) ); } $title = preg_match( '#]*>(.*?)#is', $text, $m ) ? trim( wp_strip_all_tags( html_entity_decode( $m[1] ) ) ) : trim( mb_substr( wp_strip_all_tags( $text ), 0, 120 ) ); /* translators: 1: HTTP status code, 2: what Google sent back. */ return sprintf( __( 'Google did not answer as expected (HTTP %1$d: "%2$s"). Check that the web app is deployed with access "Anyone", that you pasted the /exec address, and that you deployed a new version after pasting the script.', 'aarye-marketing-addon' ), $code, '' !== $title ? $title : __( 'empty reply', 'aarye-marketing-addon' ) ); } /** * The Apps Script to paste into the spreadsheet. * * @return string */ public static function script() { $secret = (string) AARYE_Settings::get( 'sheets_secret' ); $lines = array( '// Aarye Marketing Addon – adds each new lead as a row in this spreadsheet.', 'const SECRET = ' . wp_json_encode( $secret ) . ';', '', 'function doPost(e) {', ' const data = JSON.parse(e.postData.contents);', ' if (data.secret !== SECRET) return reply({ ok: false, error: \'The secret does not match. Copy the script again from WordPress.\' });', ' if (data.test) return reply({ ok: true });', '', ' const lock = LockService.getScriptLock();', ' lock.waitLock(20000);', ' try {', ' const book = SpreadsheetApp.getActiveSpreadsheet();', ' const sheet = book.getSheetByName(data.sheet) || book.insertSheet(data.sheet);', ' let headers = sheet.getLastColumn() ? sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0] : [];', ' data.headers.forEach(function (h) {', ' if (headers.indexOf(h) === -1) {', ' headers.push(h);', ' sheet.getRange(1, headers.length).setValue(h).setFontWeight(\'bold\');', ' }', ' });', ' if (sheet.getFrozenRows() === 0) sheet.setFrozenRows(1);', ' sheet.appendRow(headers.map(function (h) { return data.row[h] !== undefined ? data.row[h] : \'\'; }));', ' } finally {', ' lock.releaseLock();', ' }', ' return reply({ ok: true });', '}', '', 'function reply(obj) {', ' return ContentService.createTextOutput(JSON.stringify(obj)).setMimeType(ContentService.MimeType.JSON);', '}', ); return implode( "\n", $lines ) . "\n"; } }