@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
// Local QA entry, ordinary login/MFA; never maps to homologation or the active DB.
|
||||
foreach (['APP_ENV' => 'testing', 'APP_URL' => 'http://127.0.0.1:18574', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1',
|
||||
'DB_PORT' => '55441', 'DB_DATABASE' => 'simulator_fiscal_delta_20261021_test', 'DB_USERNAME' => 'postgres', 'DB_PASSWORD' => '', 'DB_URL' => '',
|
||||
'PORTAL_PROFILE_ACCESS_ENABLED' => 'true', 'PORTAL_OPPORTUNITY_SPECIALIZED_DRAFTS_ENABLED' => 'true',
|
||||
'INVESTOR_PATH_ENABLED' => 'true', 'SESSION_DRIVER' => 'file', 'SESSION_COOKIE' => 'agribusiness_opportunities_qa',
|
||||
'CACHE_STORE' => 'array', 'MAIL_MAILER' => 'array', 'QUEUE_CONNECTION' => 'sync'] as $k => $v) {
|
||||
putenv($k.'='.$v); $_ENV[$k] = $_SERVER[$k] = $v;
|
||||
}
|
||||
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
|
||||
$public = realpath(__DIR__.'/../public');
|
||||
$asset = realpath($public.rawurldecode($path));
|
||||
if ($asset && str_starts_with($asset, $public.DIRECTORY_SEPARATOR) && is_file($asset) && pathinfo($asset, PATHINFO_EXTENSION) !== 'php') return false;
|
||||
define('LARAVEL_START', microtime(true));
|
||||
require __DIR__.'/../vendor/autoload.php';
|
||||
$app = require __DIR__.'/../bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Http\Kernel::class)->bootstrap();
|
||||
$target = Illuminate\Support\Facades\DB::selectOne('SELECT current_database() AS name, inet_server_port() AS port');
|
||||
if (! $app->environment('testing') || $target->name !== 'simulator_fiscal_delta_20261021_test' || (int) $target->port !== 55441) {
|
||||
http_response_code(503); exit('QA target rejected');
|
||||
}
|
||||
$app->handleRequest(Illuminate\Http\Request::capture());
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Reconcile the 50 captured identities; public GETs only, no DB/publication writes."""
|
||||
from pathlib import Path
|
||||
from html.parser import HTMLParser
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import collections, csv, datetime, hashlib, json, re, subprocess, sys, urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / 'outputs/legacy-correspondence-20261022'
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
AUDIT = ROOT / 'docs/investmoz/v2/auditoria-portal'
|
||||
reconciliation = json.loads((ROOT / 'outputs/investmoz-legado-inventario-reconciliado-20261015/RECONCILIACAO-LEGADO.json').read_text(encoding='utf-8'))
|
||||
inventory = json.loads((ROOT / 'storage/app/private/investmoz-v2/portal-audit/legacy-discovery/inventory.json').read_text(encoding='utf-8'))
|
||||
config = json.loads(subprocess.check_output(['php', '-r', "$c=require 'config/legacy_content.php';echo json_encode($c);"], cwd=ROOT))
|
||||
mapped = {int(re.search(r'post-(\d+)-', item['external_id'])[1]): (slug, item) for slug, item in config['articles'].items() if item['publishable']}
|
||||
assert len(mapped) == 20 and len(reconciliation['articles']) == 50
|
||||
|
||||
class Page(HTMLParser):
|
||||
data = None
|
||||
reading = False
|
||||
chunks = None
|
||||
def handle_starttag(self, tag, attrs):
|
||||
attrs = dict(attrs)
|
||||
if tag == 'script' and attrs.get('type') == 'application/json' and 'data-page' in attrs:
|
||||
self.reading = True; self.chunks = []
|
||||
elif 'data-page' in attrs and attrs['data-page'].startswith('{'):
|
||||
self.data = json.loads(attrs['data-page'])
|
||||
def handle_data(self, value):
|
||||
if self.reading: self.chunks.append(value)
|
||||
def handle_endtag(self, tag):
|
||||
if tag == 'script' and self.reading:
|
||||
self.data = json.loads(''.join(self.chunks)); self.reading = False
|
||||
|
||||
def fetch(pair):
|
||||
legacy_id, (slug, identity) = pair
|
||||
url = 'https://teste-investidor.tempo.co.mz/' + slug
|
||||
try:
|
||||
request = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 InvesteMoz-Legacy-Correspondence', 'Cache-Control': 'no-cache'})
|
||||
with urllib.request.urlopen(request, timeout=35) as response:
|
||||
raw = response.read(); status = response.status
|
||||
page = Page(); page.feed(raw.decode('utf-8'))
|
||||
article = page.data['props']['article']
|
||||
assert page.data['component'] == 'portal/legacy' and article['legacy_id'] == legacy_id
|
||||
assert article['source_url'] == identity['source_url'] and article['html'].strip()
|
||||
return legacy_id, {'url': url, 'status': status, 'identity_verified': True,
|
||||
'resource_id': article['id'], 'document_sha256': article['sha256'],
|
||||
'current_title': article['title'], 'image_url': article['image']['href'] if article.get('image') else None,
|
||||
'response_sha256': hashlib.sha256(raw).hexdigest()}
|
||||
except Exception as error:
|
||||
return legacy_id, {'url': url, 'identity_verified': False, 'error': type(error).__name__, 'status': getattr(error, 'code', None)}
|
||||
|
||||
if '--reuse-http' in sys.argv:
|
||||
cached = json.loads((OUT / 'public-pages.json').read_text(encoding='utf-8'))
|
||||
checks = {int(k): v for k, v in cached['pages'].items()}; stamp = cached['checked_utc']
|
||||
assert set(checks) == set(mapped)
|
||||
else:
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
checks = dict(pool.map(fetch, mapped.items()))
|
||||
stamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
(OUT / 'public-pages.json').write_text(json.dumps({'checked_utc': stamp, 'method': 'Anonymous HTTP GET; Inertia article identity/source/content checked; no visual acceptance or new publication', 'pages': checks}, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
|
||||
captures = {}
|
||||
for record in inventory['records']:
|
||||
post = record.get('public_props', {}).get('post')
|
||||
if post:
|
||||
captures.setdefault(int(post['id']), []).append(record)
|
||||
staged = collections.defaultdict(list)
|
||||
prepared = {}
|
||||
for article in reconciliation['articles']:
|
||||
legacy_id = article['legacy_id']
|
||||
if legacy_id in mapped or article['group'] in ['mercado_financeiro', 'identidade_incompleta']:
|
||||
continue
|
||||
record = next(r for r in captures[legacy_id] if hashlib.sha256(r['public_props']['post']['content'].encode()).hexdigest() == article['body_sha256'])
|
||||
original = ROOT / record['private_file']
|
||||
assert original.is_file() and hashlib.sha256(original.read_bytes()).hexdigest() == record['sha256']
|
||||
post = record['public_props']['post']; seo = record['public_props']['seo']
|
||||
group = article['group']; directory = OUT / 'private-preparation' / group; directory.mkdir(parents=True, exist_ok=True)
|
||||
payload = {'format': 'investmoz-legacy-article-v1', 'legacy_id': legacy_id, 'title': article['title'],
|
||||
'author': seo.get('author', 'tempo'), 'legacy_category': article['category'],
|
||||
'source_url': record['url'], 'published_at': seo.get('publishedTime', ''),
|
||||
'modified_at': article['modified_at'], 'content_html': post['content'],
|
||||
'image_source_url': post.get('thumbnail'), 'image_sha256': None,
|
||||
'references': article['references']}
|
||||
data = (json.dumps(payload, ensure_ascii=False, indent=2) + '\n').encode()
|
||||
filename = f"post-{legacy_id}-{article['modified_at'][:10].replace('-', '')}.txt"
|
||||
path = directory / filename
|
||||
if path.exists():
|
||||
assert path.read_bytes() == data, 'Prepared version changed; preserve prior bytes'
|
||||
else:
|
||||
path.write_bytes(data)
|
||||
item = {'legacy_id': legacy_id, 'title': article['title'], 'source_url': record['url'],
|
||||
'external_id': f"legacy-tempo-post-{legacy_id}-{article['modified_at'][:10].replace('-', '')}",
|
||||
'file_name': filename, 'relative_path': f'{group}/{filename}',
|
||||
'sha256': hashlib.sha256(data).hexdigest(), 'source_capture_sha256': record['sha256'],
|
||||
'original_body_sha256': article['body_sha256'], 'bytes': len(data), 'published': False,
|
||||
'scan': 'not_run_on_prepared_derivative', 'dependencies': article['dependencies'],
|
||||
'note': 'Private preparation only. Not imported, scanned, published or assigned to a current opportunity. Image unresolved, never substituted by generic image.'}
|
||||
staged[group].append(item); prepared[legacy_id] = item
|
||||
assert len(prepared) == 28
|
||||
qa_receipt_path = OUT / 'qa-import-receipt.json'
|
||||
qa_rows = {}
|
||||
if qa_receipt_path.exists():
|
||||
proof = json.loads(qa_receipt_path.read_text(encoding='utf-8'))
|
||||
assert proof['qa_database'] == 'simulator_fiscal_delta_20261021_test' and proof['port'] == 55441
|
||||
assert proof['imported_private'] == proof['clean_actual_scans'] == proof['idempotent_replay_reused'] == 28
|
||||
qa_rows = {int(re.search(r'post-(\d+)-', r['external_id'])[1]): r for r in proof['resources']}
|
||||
assert set(qa_rows) == set(prepared)
|
||||
assert all(not r['published'] and r['malware_scan_status'] == 'clean' and r['sha256'] == prepared[i]['sha256'] for i, r in qa_rows.items())
|
||||
for group, items in staged.items():
|
||||
(OUT / 'private-preparation' / group / 'preparation.json').write_text(json.dumps({'importable_manifest': False, 'group': group, 'items': items}, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
|
||||
path = AUDIT / 'legado-conteudos-reconciliados.csv'
|
||||
with path.open(encoding='utf-8-sig', newline='') as f:
|
||||
reader = csv.DictReader(f); columns = reader.fieldnames; rows = list(reader)
|
||||
editorial_receipt = AUDIT / 'legado-editorial-qa-20261022.json'
|
||||
editorial_rows = {}
|
||||
if editorial_receipt.exists():
|
||||
editorial = json.loads(editorial_receipt.read_text(encoding='utf-8'))
|
||||
assert editorial['qa_only'] and not editorial['destination_imported'] and not editorial['destination_published']
|
||||
editorial_rows = {int(re.search(r'post-(\d+)-', r['external_id'])[1]): r for r in editorial['rows']}
|
||||
assert len(editorial_rows) == 28 and all(r['private'] for r in editorial_rows.values())
|
||||
extra = ['Endereço no novo portal', 'Estado actual consolidado', 'Pendência actual', 'Conferência HTTP UTC', 'Grupo de preparação QA']
|
||||
destination_receipt = ROOT / 'docs/investmoz/unification/legacy-editorial-installation-receipt-20261022.json'
|
||||
destination_rows = {}
|
||||
if destination_receipt.exists():
|
||||
destination = json.loads(destination_receipt.read_text(encoding='utf-8'))
|
||||
assert destination['new_publications'] == 0
|
||||
destination_rows = {r['legacy_id']: r for r in destination['rows']}
|
||||
assert len(destination_rows) == 28 and all(r['private'] for r in destination_rows.values())
|
||||
for col in extra:
|
||||
if col not in columns: columns.append(col)
|
||||
articles = {a['legacy_id']: a for a in reconciliation['articles']}
|
||||
for row in rows:
|
||||
legacy_id = int(row['ID legado']); article = articles[legacy_id]; check = checks.get(legacy_id)
|
||||
row['Endereço no novo portal'] = check['url'] if check else ''
|
||||
row['Conferência HTTP UTC'] = stamp if check else ''
|
||||
row['Grupo de preparação QA'] = article['group'] if legacy_id in prepared else ''
|
||||
if check:
|
||||
row['Estado actual consolidado'] = 'Publicado; identidade e conteúdo consultáveis na homologação' if check['identity_verified'] else 'Publicação documentada; consulta actual não confirmada'
|
||||
row['Pendência actual'] = 'Não foi feita aceitação visual ou conferência pela Tempo nesta passagem.' if check['identity_verified'] else str(check)
|
||||
if check['identity_verified']:
|
||||
row['Situação'] = 'publicado'; row['Recurso ativo'] = str(check['resource_id'])
|
||||
row['Grupo restante'] = 'publicados'
|
||||
row['Dependência concreta'] = 'Sem pendência de integração desta identidade; mantém-se a revisão editorial corrente.'
|
||||
row['Próxima ação'] = 'Preservar a publicação; gerir edições e versões pela biblioteca existente.'
|
||||
row['Imagem atual'] = json.dumps({'scope': 'homologação', 'href': check['image_url'], 'status': 'referência na ficha; binário não reensaiado'}, ensure_ascii=False)
|
||||
elif legacy_id in prepared:
|
||||
row['Estado actual consolidado'] = 'Importado privado em QA; scan real limpo; por integrar na homologação' if legacy_id in qa_rows else 'Por integrar; exemplar derivado preparado privadamente, sem importação'
|
||||
if legacy_id in qa_rows: row['Recurso QA'] = str(qa_rows[legacy_id]['id'])
|
||||
row['Pendência actual'] = 'Fechar edição/destino de leitura e publicação por lote na homologação. Dependências históricas de 15/10, por confrontar com o estado actual (não são novos bloqueios): ' + ' | '.join(article['dependencies'])
|
||||
if legacy_id in qa_rows:
|
||||
row['Dependência concreta'] = 'Rascunho QA analisado; falta fechar leitor/edição e entrega/publicação na homologação. Referências externas e imagens não recolhidas continuam discriminadas no inventário.'
|
||||
row['Próxima ação'] = 'Continuar por lote, preservando o carácter histórico/editorial; não converter em oportunidade vigente nem em regra fiscal.'
|
||||
elif article['group'] == 'mercado_financeiro':
|
||||
row['Estado actual consolidado'] = 'Original vazio'; row['Pendência actual'] = 'Fornecer corpo editorial pela Tempo; imagem e Fintech não substituem o original. Sem novo endereço público.'
|
||||
else:
|
||||
row['Estado actual consolidado'] = 'Original sem título'; row['Pendência actual'] = 'Identificação editorial pela Tempo para o post 74364; corpo com 21 caracteres úteis preservado. Sem título ou endereço novo inventado.'
|
||||
row['Evidência atual'] = 'outputs/legacy-correspondence-20261022/public-pages.json; qa-import-receipt.json; editorial-gaps-current.json; inventário histórico de 15/10 preservado'
|
||||
if legacy_id in editorial_rows:
|
||||
assert editorial_rows[legacy_id]['original_sha256'] == prepared[legacy_id]['sha256']
|
||||
row['Estado actual consolidado'] = 'Privado em QA; edição, leitura e prévia disponíveis; entrega privada preparada'
|
||||
row['Pendência actual'] = 'Revisão editorial pela equipa; integração Git e transporte privado autenticado para homologação; publicação separada pelo portal. Imagens não verificadas mantêm referência/aviso.'
|
||||
if legacy_id == 62413:
|
||||
row['Pendência actual'] += ' Rever/corrigir a nota de demonstração QA antes de publicar.'
|
||||
row['Dependência concreta'] = row['Pendência actual']
|
||||
row['Próxima ação'] = 'Seguir o guia e a sequência de entrega privada do manual; não repetir importação QA ou provas dos 20 aceites.'
|
||||
row['Evidência atual'] = 'legado-editorial-qa-20261022.json; manual: Legado — edição e leitura dos 28 rascunhos em QA; inventário e referências históricas preservados'
|
||||
if legacy_id in destination_rows:
|
||||
item = destination_rows[legacy_id]
|
||||
assert item['sha256'] == prepared[legacy_id]['sha256']
|
||||
row['Endereço no novo portal'] = f"https://teste-investidor.tempo.co.mz/management/portal-services/resources/{item['resource_id']}/article/preview"
|
||||
row['Recurso ativo'] = str(item['resource_id'])
|
||||
row['Estado actual consolidado'] = 'Rascunho privado na homologação; pesquisa, editor, prévia e recuperação conferidos'
|
||||
row['Pendência actual'] = 'Revisão editorial e publicação separada pela equipa no portal. As referências sem exemplar de imagem verificado permanecem explícitas.'
|
||||
if legacy_id == 62413:
|
||||
row['Pendência actual'] += ' Rever/corrigir a nota de demonstração QA antes de publicar.'
|
||||
row['Dependência concreta'] = row['Pendência actual']
|
||||
row['Próxima ação'] = 'Rever pela gestão; corrigir e pré-visualizar; publicar expressamente quando autorizado, sem comandos.'
|
||||
row['Evidência atual'] = 'docs/investmoz/unification/legacy-editorial-installation-receipt-20261022.json; preservação dos registos anteriores conferida; provas QA reutilizadas'
|
||||
assert len(rows) == 50 and len({row['ID legado'] for row in rows}) == 50
|
||||
with path.open('w', encoding='utf-8-sig', newline='') as f:
|
||||
writer = csv.DictWriter(f, columns); writer.writeheader(); writer.writerows(rows)
|
||||
|
||||
def esc(value): return str(value).replace('|', '\\|').replace('\n', ' ')
|
||||
table = ['# Correspondência integral dos 50 artigos do legado', '',
|
||||
'Conferência HTTP individual em ' + stamp + '. Lista por identidade editorial; imagens, recursos da biblioteca e variantes de URL não são artigos adicionais. Não altera publicações. Endereço em branco significa que não foi demonstrada uma página nova, não uma ligação a criar por suposição.', '',
|
||||
'| ID | Título original | Endereço original | Endereço no novo portal | Estado | Pendência |', '| --- | --- | --- | --- | --- | --- |']
|
||||
for row in rows:
|
||||
table.append('| ' + ' | '.join(esc(row[k]) for k in ['ID legado', 'Título', 'URLs observadas', 'Endereço no novo portal', 'Estado actual consolidado', 'Pendência actual']) + ' |')
|
||||
(AUDIT / 'legado-correspondencia-integral.md').write_text('\n'.join(table) + '\n', encoding='utf-8')
|
||||
summary = {'checked_utc': stamp, 'distinct_articles': 50, 'publications_documented': 20,
|
||||
'public_pages_identity_verified': sum(p['identity_verified'] for p in checks.values()),
|
||||
'pending_content': 28, 'private_preparation': {k: len(v) for k, v in staged.items()},
|
||||
'empty': 1, 'untitled': 1, 'database_writes_by_correspondence_script': 0, 'active_database_writes': 0, 'new_publications': 0,
|
||||
'qa_imports': len(qa_rows), 'qa_clean_scans': len(qa_rows), 'remaining_integration_complete': False}
|
||||
(OUT / 'receipt.json').write_text(json.dumps(summary, indent=2), encoding='utf-8')
|
||||
print(json.dumps(summary))
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
// Read-only export from the named QA; this does not import or publish in a destination.
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
use App\Services\EditorialReading;
|
||||
use App\Services\VerifiedDocumentBinary;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
$target = DB::selectOne('select current_database() as name,inet_server_port() as port');
|
||||
if (! app()->environment('testing') || $target->name !== 'simulator_fiscal_delta_20261021_test' || (int) $target->port !== 55441) {
|
||||
throw new RuntimeException('Named isolated QA only');
|
||||
}
|
||||
$directory = base_path('outputs/legacy-editorial-20261022');
|
||||
if (! is_dir($directory)) {
|
||||
mkdir($directory, 0700, true);
|
||||
}
|
||||
$identities = json_decode(file_get_contents(config_path('legacy_editorial_resources.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
if (count($identities) !== 28) {
|
||||
throw new RuntimeException('Exact 28-original scope required');
|
||||
}
|
||||
$label = $argv[1] ?? 'v1';
|
||||
if (! preg_match('/^[a-z0-9-]{1,32}$/D', $label)) {
|
||||
throw new RuntimeException('Invalid package label');
|
||||
}
|
||||
$zip = new ZipArchive;
|
||||
$archive = $directory.'/legacy-editorial-private-'.$label.'.zip';
|
||||
if (is_file($archive)) {
|
||||
throw new RuntimeException('Preserve existing package; choose a reviewed subsequent version rather than overwrite');
|
||||
}
|
||||
if ($zip->open($archive, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
|
||||
throw new RuntimeException('Cannot create private package');
|
||||
}
|
||||
$manifest = ['format' => 'investmoz-legacy-editorial-private-delivery-v1', 'prepared_at' => gmdate(DATE_ATOM), 'destination' => 'teste-investidor.tempo.co.mz', 'publish' => false, 'documents' => [], 'images' => [],
|
||||
'rules' => ['Transport/import is private and distinct from publication.', 'Resolve target IDs by original SHA256/external identity; no QA user/document/resource IDs are authoritative in the destination.', 'Keep source QA revisions as provenance, never impersonate their actors as destination audit authors.', 'Recheck target scan and existing identity/version; reuse matching originals, never overwrite conflicts.', 'Apply current metadata/edition through authenticated management, creating destination history. No automatic publication.']];
|
||||
$reading = app(EditorialReading::class);
|
||||
$rows = [];
|
||||
$imageHashes = [];
|
||||
DB::beginTransaction();
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
try {
|
||||
foreach ($identities as $identity) {
|
||||
$doc = DB::table('documents')->where('external_id', $identity['external_id'])->where('sha256', $identity['sha256'])->whereNull('deleted_at')->first();
|
||||
if (! $doc) {
|
||||
throw new RuntimeException('Missing original identity');
|
||||
}
|
||||
$resource = DB::table('portal_resources')->where('document_id', $doc->id)->first();
|
||||
if (! $resource || $resource->published || $doc->data_classification !== 'internal') {
|
||||
throw new RuntimeException('Expected private QA draft');
|
||||
}
|
||||
$binary = app(VerifiedDocumentBinary::class)->respond($doc);
|
||||
$bytes = $binary instanceof BinaryFileResponse ? file_get_contents($binary->getFile()->getPathname()) : $binary->getContent();
|
||||
if (hash('sha256', $bytes) !== $identity['sha256']) {
|
||||
throw new RuntimeException('Original changed');
|
||||
}
|
||||
$file = 'originals/'.$identity['external_id'].'.txt';
|
||||
$zip->addFromString($file, $bytes);
|
||||
$display = $reading->reading($resource, null, true);
|
||||
$edition = $resource->editorial_content ? json_decode($resource->editorial_content, true, 512, JSON_THROW_ON_ERROR) : null;
|
||||
$imageBinding = null;
|
||||
if ($edition && ! empty($edition['image_resource_id'])) {
|
||||
$imageDoc = DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')->where('r.id', $edition['image_resource_id'])->first(['d.*']);
|
||||
if (! $imageDoc) {
|
||||
throw new RuntimeException('Selected image missing');
|
||||
}
|
||||
$imageBinding = ['sha256' => $imageDoc->sha256, 'source_url' => $imageDoc->original_source];
|
||||
unset($edition['image_resource_id']);
|
||||
}
|
||||
if ($display['image_url']) {
|
||||
preg_match('~/documentos/(\d+)/view~', $display['image_url'], $match);
|
||||
$imageDoc = $reading->publicResources()->where('r.id', (int) $match[1])->first(['d.*']);
|
||||
$imageBinary = app(VerifiedDocumentBinary::class)->respond($imageDoc);
|
||||
$imageBytes = $imageBinary instanceof BinaryFileResponse ? file_get_contents($imageBinary->getFile()->getPathname()) : $imageBinary->getContent();
|
||||
if (! isset($imageHashes[$imageDoc->sha256])) {
|
||||
$imageFile = 'images/'.$imageDoc->sha256;
|
||||
$zip->addFromString($imageFile, $imageBytes);
|
||||
$imageHashes[$imageDoc->sha256] = true;
|
||||
$manifest['images'][] = ['file' => $imageFile, 'sha256' => $imageDoc->sha256, 'source_url' => $imageDoc->original_source, 'mode' => 'reuse target matching hash first; import only if absent and authorized'];
|
||||
}
|
||||
}
|
||||
$revisions = DB::table('portal_resource_revisions')->where('resource_id', $resource->id)->orderBy('revision_no')->get();
|
||||
$historyFile = 'provenance/'.$identity['external_id'].'.json';
|
||||
$zip->addFromString($historyFile, json_encode(['scope' => 'QA provenance only; IDs and actors are not destination identities', 'resource_snapshot' => $resource, 'revisions' => $revisions], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
$metadata = (array) $resource;
|
||||
foreach (['id', 'document_id', 'created_by', 'approved_by', 'last_reviewed_by', 'last_reviewed_at', 'metadata_version', 'document_group_id', 'duplicate_of_resource_id', 'document_identity_key', 'editorial_content', 'created_at', 'updated_at'] as $key) {
|
||||
unset($metadata[$key]);
|
||||
}
|
||||
$manifest['documents'][] = ['external_id' => $identity['external_id'], 'file' => $file, 'sha256' => $identity['sha256'], 'kind' => $identity['kind'], 'metadata' => $metadata, 'qa_metadata_version' => $resource->metadata_version, 'edition' => $edition, 'selected_image' => $imageBinding, 'original_image_reference' => $display['image_source_url'], 'original_image_sha256' => $display['image_expected_sha256'], 'body_image_references' => $display['image_references'], 'history_file' => $historyFile, 'publish' => false, 'version_identity' => 'Legado '.$identity['external_id']];
|
||||
$rows[] = ['external_id' => $identity['external_id'], 'qa_resource_id' => $resource->id, 'version' => $resource->metadata_version, 'original_sha256' => $doc->sha256, 'private' => ! $resource->published, 'image_available' => (bool) $display['image_url'], 'image_reference' => $display['image_source_url'], 'body_image_references' => count($display['image_references']), 'history_revisions' => $revisions->count()];
|
||||
}
|
||||
} finally {
|
||||
DB::rollBack();
|
||||
}
|
||||
$manifest['notice'] = 'The QA proof edition of original post 62413 contains an explicitly marked QA note. Review/correct it in the portal before any publication; no editorial text is silently removed from this package.';
|
||||
$zip->addFromString('manifest.json', json_encode($manifest, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
$zip->close();
|
||||
$verify = new ZipArchive;
|
||||
if ($verify->open($archive, ZipArchive::CHECKCONS) !== true) {
|
||||
throw new RuntimeException('Archive invalid');
|
||||
}
|
||||
foreach ($manifest['documents'] as $item) {
|
||||
if (hash('sha256', $verify->getFromName($item['file'])) !== $item['sha256']) {
|
||||
throw new RuntimeException('Archive original mismatch');
|
||||
}
|
||||
}
|
||||
foreach ($manifest['images'] as $item) {
|
||||
if (hash('sha256', $verify->getFromName($item['file'])) !== $item['sha256']) {
|
||||
throw new RuntimeException('Archive image mismatch');
|
||||
}
|
||||
}
|
||||
$entries = $verify->numFiles;
|
||||
$verify->close();
|
||||
$receipt = ['qa_only' => true, 'originals' => count($rows), 'rows' => $rows, 'archive_entries' => $entries, 'archive_sha256' => hash_file('sha256', $archive), 'archive_bytes' => filesize($archive), 'verified_original_hashes' => 28, 'included_image_originals' => count($manifest['images']), 'destination_imported' => false, 'destination_published' => false, 'database_writes' => 0];
|
||||
file_put_contents($directory.'/private-delivery-'.$label.'-receipt.json', json_encode($receipt, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['originals' => count($rows), 'archive_entries' => $entries, 'sha256' => $receipt['archive_sha256'], 'included_images' => count($manifest['images']), 'destination_imported' => false, 'destination_published' => false]);
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
foreach (['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441',
|
||||
'DB_DATABASE' => 'simulator_fiscal_delta_20261021_test', 'DB_USERNAME' => 'postgres', 'DB_PASSWORD' => '', 'DB_URL' => '', 'SESSION_DRIVER' => 'array'] as $k => $v) {
|
||||
putenv($k.'='.$v); $_ENV[$k] = $_SERVER[$k] = $v;
|
||||
}
|
||||
require __DIR__.'/../vendor/autoload.php';
|
||||
$app = require __DIR__.'/../bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\CorridorAgribusinessOpportunities;
|
||||
use App\Services\OpportunityPromotion;
|
||||
$target = DB::selectOne('SELECT current_database() AS name, inet_server_port() AS port');
|
||||
if (! app()->environment('testing') || $target->name !== 'simulator_fiscal_delta_20261021_test' || (int) $target->port !== 55441) throw new RuntimeException('QA only');
|
||||
config(['portal.profile_access_enabled' => true]);
|
||||
$actor = App\Models\User::findOrFail(295);
|
||||
// QA-role simulation, like the bounded tests; this is not evidence of a real production MFA login.
|
||||
session(['portal.mfa_actor' => $actor->id, 'portal.mfa_at' => time(), 'login.id' => null]);
|
||||
$request = Illuminate\Http\Request::create('/minhas-oportunidades', 'GET');
|
||||
$request->setUserResolver(fn () => $actor); $app->instance('request', $request);
|
||||
$entries = app(CorridorAgribusinessOpportunities::class)->entries();
|
||||
$dir = storage_path('app/private/agribusiness-opportunities-20261023');
|
||||
$records = Opportunity::whereIn('management_creation_key', array_column($entries, 'key'))->get();
|
||||
if (! file_exists($dir.'/before-disclosure.json')) file_put_contents($dir.'/before-disclosure.json', json_encode($records->map(fn ($r) => $r->getRawOriginal())->all(), JSON_THROW_ON_ERROR));
|
||||
$result = DB::transaction(function () use ($actor, $entries) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(231026, 34)');
|
||||
$result = [];
|
||||
foreach ($entries as $entry) {
|
||||
$record = Opportunity::where('management_creation_key', $entry['key'])->lockForUpdate()->firstOrFail();
|
||||
if ($record->status !== 'published') {
|
||||
$values = app(App\Services\OpportunityManagement::class)->values($record);
|
||||
if ($record->status !== 'draft' || ($values['canonical']['official_title'] ?? null) !== $entry['title'] || ($values['canonical']['executive_summary'] ?? null) !== $entry['summary']) throw new RuntimeException('Edited or withdrawn record requires individual review: '.$record->id);
|
||||
$input = $record->workflow_context['promotional_summary']['input'];
|
||||
$preview = app(OpportunityPromotion::class)->preview($actor, $record, [...$input, 'source_date' => null, 'action' => 'disclose', 'etag' => app(App\Services\OpportunityManagement::class)->etag($record)]);
|
||||
app(OpportunityPromotion::class)->confirm($actor, $record->id, ['token' => $preview['token'], 'operation_key' => (string) Illuminate\Support\Str::uuid(), 'confirm' => true,
|
||||
'reason' => 'QA automatizada: divulgação das 34 fichas de Agronegócio expressamente instruída pela Tempo; em preparação, sem autorização de execução.']);
|
||||
} elseif (data_get($record->workflow_context, 'publication.purpose') !== OpportunityPromotion::PURPOSE) throw new RuntimeException('Different publication preserved');
|
||||
$result[] = ['id' => $record->id, 'title' => $entry['title'], 'corridor' => $entry['corridor'], 'url' => '/oportunidades/'.$record->slug];
|
||||
}
|
||||
return $result;
|
||||
});
|
||||
$receipt = ['target' => $target, 'published' => count($result), 'authentication' => 'QA role simulation only; no production authentication claimed', 'source_sha256' => CorridorAgribusinessOpportunities::SOURCE_HASH, 'records' => $result, 'active_writes' => 0];
|
||||
file_put_contents($dir.'/disclosure-receipt.json', json_encode($receipt, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
echo json_encode(['published' => count($result), 'target' => $target, 'active_writes' => 0]).PHP_EOL;
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
// Initial source loading only. Everyday editing and disclosure use the portal.
|
||||
$options = getopt('', ['apply', 'actor:', 'organization:']);
|
||||
foreach (['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441',
|
||||
'DB_DATABASE' => 'simulator_fiscal_delta_20261021_test', 'DB_USERNAME' => 'postgres', 'DB_PASSWORD' => '', 'DB_URL' => ''] as $k => $v) {
|
||||
putenv($k.'='.$v); $_ENV[$k] = $_SERVER[$k] = $v;
|
||||
}
|
||||
require __DIR__.'/../vendor/autoload.php';
|
||||
$app = require __DIR__.'/../bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Services\CorridorAgribusinessOpportunities;
|
||||
$target = DB::selectOne('SELECT current_database() AS name, inet_server_port() AS port');
|
||||
if (! app()->environment('testing') || $target->name !== 'simulator_fiscal_delta_20261021_test' || (int) $target->port !== 55441) throw new RuntimeException('Refusing non-QA target.');
|
||||
config(['portal.profile_access_enabled' => true, 'portal.opportunity_specialized_drafts_enabled' => true]);
|
||||
$service = app(CorridorAgribusinessOpportunities::class);
|
||||
if (! isset($options['apply'])) {echo json_encode(['target' => $target, 'entries' => $service->entries(), 'writes' => 0], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); exit;}
|
||||
$actor = App\Models\User::findOrFail($options['actor'] ?? 0);
|
||||
$organization = $options['organization'] ?? '';
|
||||
$request = Illuminate\Http\Request::create('/minhas-oportunidades/drafts', 'POST');
|
||||
$request->setUserResolver(fn () => $actor); $app->instance('request', $request);
|
||||
$dir = storage_path('app/private/agribusiness-opportunities-20261023');
|
||||
if (! is_dir($dir)) mkdir($dir, 0700, true);
|
||||
if (! file_exists($dir.'/before.json')) {
|
||||
$before = [];
|
||||
foreach (['opportunities', 'audit_events', 'development_corridors', 'portal_role_assignments', 'portal_resources', 'documents'] as $table) $before[$table] = DB::table($table)->orderBy('id')->get()->all();
|
||||
file_put_contents($dir.'/before.json', json_encode($before, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
$records = $service->register($actor, $organization);
|
||||
$receipt = ['target' => $target, 'source_sha256' => $service::SOURCE_HASH, 'records' => $records, 'total' => count($records),
|
||||
'new' => count(array_filter($records, fn ($r) => $r['created'])), 'published' => App\Models\Opportunity::whereIn('id', array_column($records, 'id'))->published()->count(), 'active_writes' => 0];
|
||||
file_put_contents($dir.'/receipt.json', json_encode($receipt, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($receipt, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE).PHP_EOL;
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
// Delimited recovery requested by Tempo, 23/10/2026. Never import or approve new/edited dossiers.
|
||||
declare(strict_types=1);
|
||||
|
||||
ini_set('zend.exception_ignore_args', '1');
|
||||
require getcwd().'/vendor/autoload.php';
|
||||
$app = require getcwd().'/bootstrap/app.php';
|
||||
(new Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables)->bootstrap($app);
|
||||
(new Illuminate\Foundation\Bootstrap\LoadConfiguration)->bootstrap($app);
|
||||
$args = getopt('', ['manifest:', 'output:', 'apply', 'preview-sha256:', 'backup:', 'qa']);
|
||||
$manifestPath = $args['manifest'] ?? '';
|
||||
$manifestHash = '8d07007a2e1e8758d4741b4ac594f78d5943f71ad78b2daae7f85aefa9d2de4a';
|
||||
if (!is_file($manifestPath) || !hash_equals($manifestHash, hash_file('sha256', $manifestPath))) {
|
||||
throw new RuntimeException('Exact reviewed 29-original recovery manifest required.');
|
||||
}
|
||||
$manifest = json_decode(file_get_contents($manifestPath), true, 512, JSON_THROW_ON_ERROR);
|
||||
if (count($manifest['items']) !== 29 || count(array_unique(array_column($manifest['items'], 'target_record_id'))) !== 29) {
|
||||
throw new RuntimeException('Exact original scope required.');
|
||||
}
|
||||
$qa = isset($args['qa']);
|
||||
$c = config('database.connections.'.config('database.default'));
|
||||
$expected = $qa ? 'simulator_fiscal_delta_20261021_test' : 'teste_investidor';
|
||||
$port = $qa ? 55441 : 5432;
|
||||
if ($c['driver'] !== 'pgsql' || !empty($c['url']) || !in_array($c['host'], ['127.0.0.1', 'localhost'], true) || $c['database'] !== $expected || (int)$c['port'] !== $port) {
|
||||
throw new RuntimeException('Named target mismatch.');
|
||||
}
|
||||
if (!$qa && (!getenv('SSH_CONNECTION') || !function_exists('posix_geteuid') || posix_geteuid() !== 0 || rtrim(config('app.url'), '/') !== 'https://teste-investidor.tempo.co.mz')) {
|
||||
throw new RuntimeException('Authenticated destination operator required.');
|
||||
}
|
||||
$output = $args['output'] ?? '';
|
||||
if (!$output || str_contains(str_replace('\\', '/', $output), '/public/')) {
|
||||
throw new RuntimeException('Private receipt path required.');
|
||||
}
|
||||
$pdo = new PDO('pgsql:host='.$c['host'].';port='.$c['port'].';dbname='.$expected, $c['username'], $c['password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
|
||||
$apply = isset($args['apply']);
|
||||
$pdo->exec($apply ? 'BEGIN ISOLATION LEVEL SERIALIZABLE' : 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
try {
|
||||
$actual = $pdo->query('select current_database() as name,inet_server_port() as port')->fetch(PDO::FETCH_ASSOC);
|
||||
if ($actual['name'] !== $expected || (int)$actual['port'] !== $port) throw new RuntimeException('Actual target mismatch.');
|
||||
if ($apply) $pdo->query('select pg_advisory_xact_lock(231026,29)');
|
||||
$plan = [];
|
||||
$before = [];
|
||||
foreach ($manifest['items'] as $item) {
|
||||
$query = $pdo->prepare('select * from investment_dossiers where id = ?'.($apply ? ' for update' : ''));
|
||||
$query->execute([$item['target_record_id']]);
|
||||
$row = $query->fetch(PDO::FETCH_ASSOC);
|
||||
if (!$row || $row['deleted_at'] !== null || $row['title'] !== $item['title'] || !hash_equals($item['content_sha256'], hash('sha256', $row['content'])) || !hash_equals($item['source_sha256'], hash('sha256', $row['source']))) {
|
||||
throw new RuntimeException('Missing, archived or changed original: '.$item['code']);
|
||||
}
|
||||
if (!hash_equals($item['approval_sha256'], hash('sha256', $item['approval_evidence']))) throw new RuntimeException('Approval provenance changed.');
|
||||
$replayed = $pdo->prepare("select count(*) from audit_events where source_system='portfolio-visibility-recovery-v1' and external_id=? and entity_id=? and action='approved_visibility_restored'");
|
||||
$replayed->execute([$manifestHash.':'.$row['id'], $row['id']]);
|
||||
$already = (int)$replayed->fetchColumn() === 1;
|
||||
if ($already) {
|
||||
if ($row['publication_status'] !== 'published' || $row['approval_basis'] !== 'document_owner' || $row['approval_evidence'] !== $item['approval_evidence']) throw new RuntimeException('Recovery subsequently changed: '.$item['code']);
|
||||
} elseif ($row['publication_status'] !== 'draft' || $row['editor_id'] !== null || $row['reviewer_id'] !== null || (int)$row['version_no'] !== (int)$item['expected_target_version']) {
|
||||
throw new RuntimeException('Preserve subsequent editorial decisions: '.$item['code']);
|
||||
}
|
||||
$before[] = $row;
|
||||
$plan[] = ['id' => $row['id'], 'code' => $item['code'], 'version' => (int)$row['version_no'], 'status' => $row['publication_status'], 'content_sha256' => $item['content_sha256'], 'source_sha256' => $item['source_sha256'], 'already_restored' => $already];
|
||||
}
|
||||
$previewHash = hash('sha256', json_encode([$expected, $manifestHash, $plan], JSON_THROW_ON_ERROR));
|
||||
if ($apply) {
|
||||
if (!hash_equals($previewHash, $args['preview-sha256'] ?? '')) throw new RuntimeException('Preview changed; recover current state before writing.');
|
||||
if (!$qa) {
|
||||
$directory = $args['backup'] ?? '';
|
||||
$backup = json_decode(file_get_contents($directory.'/backup-receipt.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$restore = json_decode(file_get_contents($directory.'/restore-receipt.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
if (!$restore['restore_verified'] || $backup['target']['database'] !== $expected || (int)$backup['target']['port'] !== $port || !hash_equals($backup['sha256'], $restore['source_dump_sha256'])) throw new RuntimeException('Verified matching backup/restore required.');
|
||||
}
|
||||
$snapshot = $output.'.before.json';
|
||||
if (is_file($snapshot)) throw new RuntimeException('Preserve earlier recovery snapshot; use a new receipt path.');
|
||||
file_put_contents($snapshot, json_encode(['database' => $expected, 'rows' => $before], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
if (!$qa) chmod($snapshot, 0600);
|
||||
foreach ($plan as $index => $entry) {
|
||||
if ($entry['already_restored']) continue;
|
||||
$item = $manifest['items'][$index];
|
||||
$update = $pdo->prepare("update investment_dossiers set publication_status='published',approval_basis='document_owner',approval_evidence=?,published_at=now(),version_no=version_no+1,updated_at=now() where id=? and version_no=?");
|
||||
$update->execute([$item['approval_evidence'], $entry['id'], $entry['version']]);
|
||||
if ($update->rowCount() !== 1) throw new RuntimeException('Concurrent change.');
|
||||
$event = $pdo->prepare("insert into audit_events(source_system,external_id,entity_type,entity_id,actor_user_id,action,before_data,after_data) values('portfolio-visibility-recovery-v1',?,'investment_dossiers',?,NULL,'approved_visibility_restored',?,?)");
|
||||
$event->execute([$manifestHash.':'.$entry['id'], $entry['id'], json_encode(['version_no' => $entry['version'], 'publication_status' => 'draft', 'approval_basis' => $before[$index]['approval_basis']], JSON_THROW_ON_ERROR), json_encode(['code' => $item['code'], 'version_no' => $entry['version']+1, 'publication_status' => 'published', 'approval_basis' => 'document_owner', 'approval_sha256' => $item['approval_sha256'], 'content_sha256' => $item['content_sha256'], 'source_record_id' => $item['source_record_id'], 'source_published_at' => $item['original_published_at'], 'instruction' => 'Tempo 23/10/2026: preserve and restore completed approved functionality', 'authenticated_transport' => $qa ? 'isolated-QA' : 'SSH', 'not_a_new_editorial_approval' => true], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
}
|
||||
$visible = (int)$pdo->query("select count(*) from investment_dossiers d where publication_status='published' and (exists(select 1 from projects p where p.id=d.project_id and p.deleted_at is null) or exists(select 1 from economic_clusters c where c.id=d.cluster_id and c.deleted_at is null) or exists(select 1 from development_corridors r where r.id=d.corridor_id and r.deleted_at is null))")->fetchColumn();
|
||||
$result = ['database' => $actual, 'qa' => $qa, 'mode' => $apply ? 'applied' : 'preview', 'manifest_sha256' => $manifestHash, 'preview_sha256' => $previewHash, 'scope' => count($plan), 'restored' => $apply ? count(array_filter($plan, fn($r) => !$r['already_restored'])) : 0, 'visible' => $visible, 'data_content_changed' => false, 'new_dossiers_imported' => 0, 'fake_editor_or_reviewer_assigned' => false, 'plan' => $plan];
|
||||
if ($apply) $pdo->commit(); else $pdo->rollBack();
|
||||
file_put_contents($output, json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
if (!$qa) chmod($output, 0600);
|
||||
unset($result['plan']);
|
||||
echo json_encode($result, JSON_THROW_ON_ERROR);
|
||||
} catch (Throwable $error) {
|
||||
if ($pdo->inTransaction()) $pdo->rollBack();
|
||||
throw $error;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
// Rehearse recovery with the existing importer. Never accepts an active database.
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$target = Illuminate\Support\Facades\DB::selectOne('select current_database() as database,inet_server_port() as port');
|
||||
throw_unless($target->database === 'simulator_fiscal_delta_20261021_test' && (int) $target->port === 55441
|
||||
&& config('database.connections.pgsql.host') === '127.0.0.1', RuntimeException::class, 'Isolated QA only.');
|
||||
$app->detectEnvironment(fn () => 'testing');
|
||||
config(['geometry-import.enabled' => true, 'portal.managers' => ['qa-content-promoter@example.test'],
|
||||
'services.malware.scanner' => 'clamd', 'services.malware.socket' => null,
|
||||
'services.malware.host' => '127.0.0.1', 'services.malware.port' => 3310]);
|
||||
$actor = App\Models\User::where('email', 'qa-content-promoter@example.test')->firstOrFail();
|
||||
$directory = config('geometry-import.directory');
|
||||
$out = storage_path('app/private/territory-demarcation-recovery');
|
||||
Illuminate\Support\Facades\File::ensureDirectoryExists($out, 0700);
|
||||
$manifest = [];
|
||||
foreach (glob($directory.'/moz-adm*-ine-*') as $file) {
|
||||
$manifest[] = ['file' => basename($file), 'bytes' => filesize($file), 'sha256' => hash_file('sha256', $file)];
|
||||
}
|
||||
file_put_contents($out.'/source-inventory.json', json_encode($manifest, JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
$scanner = app(App\Services\Malware\MalwareScanner::class);
|
||||
$health = $scanner->health();
|
||||
throw_unless($health['available'], RuntimeException::class, 'Current scanner unavailable.');
|
||||
$scans = [];
|
||||
foreach ([1, 2, 3] as $level) {
|
||||
$file = $directory.'/moz-adm'.$level.'-ine-20190607.geojson';
|
||||
// Scope the stream budget to this retained GIS original in this process only.
|
||||
config(['services.malware.max_file_bytes' => filesize($file), 'services.malware.max_stream_bytes' => filesize($file)]);
|
||||
$scan = $scanner->scan($file, filesize($file), storage_path('app/private'));
|
||||
$scan['signatures_at'] = $scan['signatures_at']?->format(DATE_ATOM);
|
||||
if ($level === 3 && $scan['reason_code'] === 'scanner_decompression_limit') {
|
||||
$binary = getenv('GIS_CLAMSCAN_BINARY');
|
||||
$database = getenv('GIS_CLAMSCAN_DATABASE');
|
||||
throw_unless(is_file($binary ?: '') && is_dir($database ?: ''), RuntimeException::class, 'GIS scanner paths required.');
|
||||
$process = new Symfony\Component\Process\Process([$binary, '--database='.$database, '--max-filesize=40M', '--max-scansize=100M', '--no-summary', $file]);
|
||||
$process->setTimeout(120)->mustRun();
|
||||
throw_unless(str_ends_with(trim($process->getOutput()), ': OK'), RuntimeException::class, 'GIS original scan incomplete.');
|
||||
$version = new Symfony\Component\Process\Process([$binary, '--database='.$database, '--version']);
|
||||
$version->mustRun();
|
||||
$parts = explode('/', trim($version->getOutput()));
|
||||
$signatureTime = strtotime(end($parts));
|
||||
throw_unless($signatureTime && time() - $signatureTime < 48 * 3600, RuntimeException::class, 'Current GIS signatures required.');
|
||||
$scan = ['result' => 'clean', 'engine' => 'ClamAV', 'engine_version' => trim($version->getOutput()),
|
||||
'signatures_at' => gmdate(DATE_ATOM, $signatureTime), 'scope' => 'retained GIS original only',
|
||||
'original_sha256' => hash_file('sha256', $file), 'stream_attempt' => $scan, 'exit_code' => $process->getExitCode()];
|
||||
}
|
||||
$scans[] = ['file' => basename($file), 'sha256' => hash_file('sha256', $file), 'scan' => $scan];
|
||||
echo json_encode(['level' => $level, 'scan' => $scan]).PHP_EOL;
|
||||
throw_unless($scan['result'] === 'clean', RuntimeException::class, 'Original scan incomplete.');
|
||||
}
|
||||
file_put_contents($directory.'/geometry-source-scans.json', json_encode(['captured_at' => gmdate('c'), 'files' => $scans], JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
$service = app(App\Services\TerritoryGeometryImport::class);
|
||||
foreach ([1, 2, 3] as $level) {
|
||||
$plan = $service->preview($actor, $level);
|
||||
file_put_contents($out.'/preview-'.$level.'.json', json_encode($plan, JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['level' => $level, 'resolved' => $plan['resolved'], 'pending' => $plan['pending']]).PHP_EOL;
|
||||
if (! in_array('--apply', $argv, true)) break; // Lower levels require imported parent correspondences.
|
||||
$result = $service->apply($actor, ['level' => $level, 'hash' => $plan['hash'], 'idempotency_key' => (string) Illuminate\Support\Str::uuid(),
|
||||
'reason' => 'Recuperação QA da demarcação anteriormente demonstrada, com originais e correspondências aceites.', 'confirm' => true]);
|
||||
file_put_contents($out.'/result-'.$level.'.json', json_encode($result, JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['level' => $level, 'inserted' => $result['inserted'], 'reused' => $result['reused']]).PHP_EOL;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
require __DIR__.'/../vendor/autoload.php';
|
||||
// Offline verification against the preserved article exemplar; no database or source writes.
|
||||
$path = $argv[1] ?? throw new RuntimeException('Pass the preserved agronegocio article JSON path.');
|
||||
$sourceHash = hash_file('sha256', $path);
|
||||
$source = json_decode(file_get_contents($path), true, 512, JSON_THROW_ON_ERROR);
|
||||
if (($source['format'] ?? '') !== 'investmoz-legacy-article-v1' || ($source['slug'] ?? '') !== 'agronegocio') {
|
||||
throw new RuntimeException('Unexpected source article.');
|
||||
}
|
||||
$original = (new App\Services\LegacyContent)->sanitize($source['content_html']);
|
||||
$html = (new App\Services\CorridorAgribusiness)->enrich($original);
|
||||
$doc = new DOMDocument;
|
||||
$doc->loadHTML('<?xml encoding="UTF-8">'.$html);
|
||||
$xpath = new DOMXPath($doc);
|
||||
$groups = $xpath->query('//ul[starts-with(@id,"agronegocio-oportunidades-")]');
|
||||
$entries = $xpath->query('//ul[starts-with(@id,"agronegocio-oportunidades-")]/li');
|
||||
if ($groups->length !== 6 || $entries->length !== 34 || $sourceHash !== hash_file('sha256', $path)) {
|
||||
throw new RuntimeException('Incomplete integration or source changed.');
|
||||
}
|
||||
// Removing only the additions must recover the exact sanitized original.
|
||||
foreach (iterator_to_array($groups) as $group) {
|
||||
$group->parentNode->removeChild($group->previousSibling);
|
||||
$group->parentNode->removeChild($group->nextSibling);
|
||||
$group->parentNode->removeChild($group);
|
||||
}
|
||||
$body = $doc->getElementsByTagName('body')->item(0);
|
||||
$recovered = implode('', array_map(fn ($node) => $doc->saveHTML($node), iterator_to_array($body->childNodes)));
|
||||
if ($recovered !== $original) {
|
||||
throw new RuntimeException('Original displayed content was changed.');
|
||||
}
|
||||
echo json_encode(['source_sha256' => $sourceHash, 'source_unchanged' => true, 'original_display_preserved' => true,
|
||||
'corridors' => 6, 'agribusiness_entries' => 34, 'database_writes' => 0], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE).PHP_EOL;
|
||||
Reference in New Issue
Block a user