403Webshell
Server IP : 3.147.158.171  /  Your IP : 216.73.216.229
Web Server : Apache/2.4.67 (Amazon Linux) OpenSSL/3.5.5
System : Linux ip-172-31-2-178.us-east-2.compute.internal 6.1.172-216.329.amzn2023.x86_64 #1 SMP PREEMPT_DYNAMIC Wed May 20 06:31:34 UTC 2026 x86_64
User : ec2-user ( 1000)
PHP Version : 8.4.21
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : OFF
Directory :  /tsai/repo/builder/backend/scripts/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /tsai/repo/builder/backend/scripts/localize_site_configs.py
"""Localize Drupal site_config node host fields for the development environment.

After the Drupal DB is restored from a production backup, the `site_config` nodes
hold production host values (https, .ai/.net domains). This rewrites the two host
fields to their local equivalents, matching the URL rewrites the WordPress
`wp search-replace` steps already perform in deploy-to-local.json:

    field_wp_host:  https:// -> http://,  .ai/.net/.com -> .test
    field_cb_host:  .ai/.net/.com -> .test   (no scheme present)

Both the data table and the revision table are updated so a later UI edit cannot
reintroduce production values. The replacements are plain substring swaps (current
data has no internal .ai/.net/.com substrings) and are idempotent — re-running is a
no-op. Run the next `drush cr` so the API re-fetches the localized values.
"""
import os
import subprocess
import sys
from dotenv import load_dotenv, find_dotenv

if not find_dotenv():
    print("Error: .env file not found.")
    sys.exit(1)
load_dotenv()

MYSQL_HOST = os.getenv('MYSQL_HOST')
MYSQL_USER = os.getenv('MYSQL_USER')
MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD')

missing = [name for name, var in [
    ('MYSQL_HOST', MYSQL_HOST),
    ('MYSQL_USER', MYSQL_USER),
    ('MYSQL_PASSWORD', MYSQL_PASSWORD),
] if var is None]
if missing:
    print(f"Error: Missing environment variables: {', '.join(missing)}")
    sys.exit(1)

assert MYSQL_HOST is not None
assert MYSQL_USER is not None
assert MYSQL_PASSWORD is not None

DB_NAME = 'drupal'

# (table, column) pairs for each host field — data table + revision table.
WP_HOST_TABLES = ['node__field_wp_host', 'node_revision__field_wp_host']
CB_HOST_TABLES = ['node__field_cb_host', 'node_revision__field_cb_host']


def _tld_swap(expr):
    """Wrap a SQL value expression to replace prod TLDs with .test."""
    for tld in ('.ai', '.net', '.com'):
        expr = f"REPLACE({expr}, '{tld}', '.test')"
    return expr


def build_sql():
    statements = []

    for table in WP_HOST_TABLES:
        col = 'field_wp_host_value'
        expr = _tld_swap(f"REPLACE({col}, 'https://', 'http://')")
        statements.append(f"UPDATE {table} SET {col} = {expr};")

    for table in CB_HOST_TABLES:
        col = 'field_cb_host_value'
        expr = _tld_swap(col)
        statements.append(f"UPDATE {table} SET {col} = {expr};")

    return "\n".join(statements)


def run_mysql(sql, capture=False):
    """Run SQL against the drupal DB via the mysql CLI."""
    env = os.environ.copy()
    env['MYSQL_PWD'] = MYSQL_PASSWORD
    command = [
        'mysql',
        f'--host={MYSQL_HOST}',
        f'--user={MYSQL_USER}',
        '-N' if capture else '--batch',
        '-e', sql,
        DB_NAME,
    ]
    try:
        result = subprocess.run(command, check=True, env=env,
                                stderr=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
        return result.stdout
    except subprocess.CalledProcessError as e:
        print(f"Error running mysql: {e}")
        if e.stderr:
            print(f"MySQL error: {e.stderr}")
        sys.exit(1)


def show_hosts(label):
    print(f"\n{label}:")
    rows = run_mysql(
        "SELECT s.field_slug_value, w.field_wp_host_value, c.field_cb_host_value "
        "FROM node__field_slug s "
        "JOIN node__field_wp_host w ON w.entity_id = s.entity_id "
        "JOIN node__field_cb_host c ON c.entity_id = s.entity_id "
        "ORDER BY s.field_slug_value;",
        capture=True,
    )
    for line in rows.strip().splitlines():
        slug, wp_host, cb_host = (line.split('\t') + ['', '', ''])[:3]
        print(f"  {slug:<10} wp_host={wp_host:<40} cb_host={cb_host}")


def main():
    show_hosts("Before localization")
    run_mysql(build_sql())
    show_hosts("After localization")
    print("\nāœ“ site_config hosts localized. Run `drush cr` to refresh caches.")


if __name__ == '__main__':
    main()

Youez - 2016 - github.com/yon3zu
LinuXploit