Prompt تنفيذي: بناء WP-PDAE v1.2 كاملاً
text
أنت مهندس برمجيات خبير في WordPress/PHP 8.1+ ومتخصص في تحليل الخصوصية وأمن البيانات.
المهمة: بناء مشروع كامل باسم **WP Privacy Document Analyzer Engine (WP-PDAE) v1.2** على مسار إنتاجي حقيقي، مع مراجعة وفحص كل ملف كود قبل تسليمه.
═══════════════════════════════════════════════════════
بيئة الهدف (TARGET ENVIRONMENT)
═══════════════════════════════════════════════════════
- Host: app.zezoai.twisttaste.com
- PHP: 8.1+ (strict_types=1 إجباري في كل ملف)
- WordPress: 6.x
- Database: MySQL 8.0 / MariaDB 10.6+
- الترميز: UTF-8
- بنية المشروع: plugin قياسي في wp-content/plugins/wp-pdae/
═══════════════════════════════════════════════════════
القاموس الحاكم (CONTROLLED VOCABULARY — MUST)
═══════════════════════════════════════════════════════
كل مصطلح يُستخدم بمعناه المحدد هنا حصراً. أي انحراف = خطأ في المواصفة.
1. Document : ملف مرفوع (PDF/DOCX/HTML/TXT) خاضع للتحليل.
2. Analysis : عملية استخراج + تصنيف + تقييم لمستند واحد.
3. Finding : نتيجة تصنيف واحدة (فئة + شدة + مقتطف + موقع).
4. Severity : enum {CRITICAL, HIGH, MEDIUM, LOW, INFO}.
5. Category : enum {PII, COOKIES, THIRD_PARTY, RETENTION, CONSENT, SECURITY, JURISDICTION}.
6. PolicyScore : عدد صحيح 0–100 محسوب من الـ Findings.
7. AuditLog : سجل غير قابل للتعديل لكل حدث.
8. Nonce : رمز wp_nonce مطلوب لكل عملية كتابة.
9. Capability : صلاحية WordPress مطلوبة (حد أدنى: manage_options).
10. Idempotent : إعادة التنفيذ لا تُغيّر النتيجة.
═══════════════════════════════════════════════════════
المتطلبات الوظيفية (FUNCTIONAL REQUIREMENTS)
═══════════════════════════════════════════════════════
FR-01 (MUST) رفع مستند عبر REST endpoint: POST /wp-json/wp-pdae/v1/analyze
- يقبل multipart/form-data، حد أقصى 10MB، MIME whitelist: application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document, text/html, text/plain
- يرفض أي ملف خارج whitelist بـ 415
FR-02 (MUST) استخراج النص: PDF عبر smalot/pdfparser، DOCX عبر PhpWord، HTML/TXT عبر strip_tags + html_entity_decode
FR-03 (MUST) كشف PII: regex لمجموعة {email, phone (E.164 + محلي), IBAN, national_id, credit_card (Luhn-validated), IP} — كل نتيجة Finding مع مقتطف ±40 حرفاً وموقع بايت
FR-04 (MUST) كشف الكوكيز: مطابقة قائمة cookie names (configurable) في نص المستند
FR-05 (MUST) كشف الأطراف الثالثة: مطابقة نطاقات من قائمة (Google, Meta, TikTok, ...) — قابلة للتوسعة عبر filter `wp_pdae_third_party_domains`
FR-06 (MUST) حساب PolicyScore: 100 − Σ(severity_weight × count)، بحد أدنى 0. الأوزان: CRITICAL=25, HIGH=10, MEDIUM=4, LOW=1, INFO=0
FR-07 (MUST) تخزين النتائج في جدول مخصص wp_pdae_analyses + wp_pdae_findings مع فهارس على (document_hash, created_at) و (analysis_id, severity)
FR-08 (MUST) عرض النتائج في صفحة admin تحت قائمة "Tools" مع capability manage_options
FR-09 (MUST) تسجيل كل حدث في AuditLog (wp_pdae_audit_log) — append-only، لا UPDATE/DELETE
FR-10 (MUST) idempotent: نفس document_hash → إرجاع Analysis موجود دون إعادة حساب إلا بطلب force=1
═══════════════════════════════════════════════════════
المتطلبات غير الوظيفية (NON-FUNCTIONAL — MUST)
═══════════════════════════════════════════════════════
NFR-01 الأمان: كل REST endpoint يتحقق من capability + nonce. كل query عبر $wpdb->prepare. كل output عبر esc_html/esc_attr/wp_kses.
NFR-02 الأداء: تحليل مستند 5MB ≤ 3 ثوانٍ على أجهزة مرجعية. استخدام chunked regex مع pcre.backtrack_limit مراقب.
NFR-03 الاعتمادية: try/catch شامل، WP_Error في كل مسار فشل، لا تسريب stack traces للمستخدم.
NFR-04 قابلية الاختبار: كل class ≤ 300 سطر، Dependency Injection عبر constructor، لا static state.
NFR-05 i18n: كل string عبر __()/esc_html__()، text-domain = 'wp-pdae'.
NFR-06 التوافق: لا استخدام deprecated functions. PHP 8.1 features (readonly, enums, match) مسموحة.
═══════════════════════════════════════════════════════
بنية الملفات الإلزامية (FILE STRUCTURE)
═══════════════════════════════════════════════════════
wp-pdae/
├── wp-pdae.php (bootstrap + activation hook)
├── uninstall.php (حذف الجداول + options)
├── composer.json (smalot/pdfparser, phpoffice/phpword)
├── readme.txt (WP standard)
├── includes/
│ ├── class-plugin.php (singleton bootstrapper)
│ ├── class-activator.php (dbDelta + caps + cron)
│ ├── class-deactivator.php
│ ├── Database/
│ │ ├── class-schema.php
│ │ └── class-repository.php
│ ├── Domain/
│ │ ├── class-analysis.php
│ │ ├── class-finding.php
│ │ ├── class-severity.php (enum)
│ │ └── class-category.php (enum)
│ ├── Extractors/
│ │ ├── interface-extractor.php
│ │ ├── class-pdf-extractor.php
│ │ ├── class-docx-extractor.php
│ │ └── class-text-extractor.php
│ ├── Detectors/
│ │ ├── interface-detector.php
│ │ ├── class-pii-detector.php
│ │ ├── class-cookie-detector.php
│ │ └── class-third-party-detector.php
│ ├── Services/
│ │ ├── class-analyzer.php (orchestrator)
│ │ ├── class-scorer.php
│ │ └── class-audit-logger.php
│ ├── REST/
│ │ ├── class-analyze-controller.php
│ │ └── class-results-controller.php
│ └── Admin/
│ ├── class-admin-page.php
│ └── class-list-table.php
├── assets/
│ ├── css/admin.css
│ └── js/admin.js
└── tests/
├── bootstrap.php
├── test-pii-detector.php
├── test-scorer.php
└── test-repository.php
═══════════════════════════════════════════════════════
معايير القبول القابلة للقياس (ACCEPTANCE CRITERIA)
═══════════════════════════════════════════════════════
AC-01: رفع PDF صالح 2MB → 200 + analysis_id + PolicyScore في JSON
AC-02: رفع .exe → 415 بدون كتابة في DB
AC-03: تحليل نفس الملف مرتين → نفس analysis_id (idempotent)
AC-04: PII detector يكتشف 100% من عينات الاختبار (≥20 عينة/نوع) بدون false negative
AC-05: Scorer: 3 CRITICAL + 2 HIGH → score = 0 (floor)؛ 0 findings → 100
AC-06: مستخدم بلا manage_options → 403
AC-07: nonce مفقود → 403 قبل أي كتابة
AC-08: AuditLog لا يقبل UPDATE/DELETE (اختبار SQL مباشر)
AC-09: كل ملف PHP يمر `php -l` بدون أخطاء
AC-10: كل ملف PHP يمر PHP_CodeSniffer (WordPress standard) بدون أخطاء blocking
═══════════════════════════════════════════════════════
بروتوكول التنفيذ والمراجعة الذاتية (EXECUTION & SELF-REVIEW PROTOCOL)
═══════════════════════════════════════════════════════
لكل ملف تكتبه، اتبع هذا التسلسل الصارم ولا تنتقل للملف التالي حتى تُكمله:
STEP-1 اكتب الملف كاملاً (لا placeholders، لا TODO، لا اختصارات).
STEP-2 أعد قراءة الملف سطراً بسطر وافحص:
(a) PHP syntax صحيح؟ (b) strict_types=1 في السطر الأول بعد <?php؟
(c) كل input مُتحقق منه؟ (d) كل output مُهرَّب (escaped)؟
(e) كل DB query عبر prepare()؟ (f) كل capability/nonce موجود؟
(g) لا استخدام deprecated؟ (h) strict typing في signatures؟
STEP-3 اذكر صراحة: "المراجعة الذاتية: [PASS|FAIL]" + أي إصلاح أجريته.
STEP-4 اذكر الاعتماديات (ملفات يجب أن تُبنى قبله) — لا تبدأ ملفاً قبل اكتمال اعتمادياته.
STEP-5 بعد كل 5 ملفات: نفّذ "GLOBAL SCAN" — تحقق من: lack of circular deps، autoloader، namespace consistency، عدم تكرار الكود.
═══════════════════════════════════════════════════════
قواعد صارمة (HARD RULES)
═══════════════════════════════════════════════════════
- لا تكتب كوداً غير مكتمل. كل ملف 100% قابل للتشغيل.
- لا تستخدم مكتبات خارج composer إلا إن كانت موثقة في composer.json.
- لا تخالف Controlled Vocabulary أعلاه في أي اسم class/method/variable.
- لا تكرر منطقاً — استخرج shared logic إلى Service.
- عند أي شك في متطلب → اسأل قبل التخمين.
- بعد إكمال كل وحدة (Module) → قدّم تقريراً موجزاً: الملفات، الاعتماديات، ACs المغطاة، نتيجة self-review.
═══════════════════════════════════════════════════════
مخرجات التسليم (DELIVERABLES)
═══════════════════════════════════════════════════════
1. كود كامل لكل ملف حسب البنية أعلاه.
2. composer.json + composer.lock (concept).
3. SQL schema قابل للتنفيذ عبر dbDelta.
4. تقرير مراجعة نهائي يغطي كل AC-01..AC-10 مع PASS/FAIL.
5. دليل تشغيل قصير (INSTALL.md).
ابدأ الآن بالترتيب التالي:
(1) composer.json + wp-pdae.php (bootstrap)
(2) includes/class-activator.php + Database/class-schema.php
(3) Domain/ (enums + entities)
(4) Extractors/
(5) Detectors/
(6) Services/
(7) REST/
(8) Admin/
(9) tests/
(10) تقرير المراجعة النهائي
بعد كل خطوة، طبّق بروتوكول EXECUTION & SELF-REVIEW قبل الانتقال.
استكمال البروتوكول — الإضافات الإلزامية (v1.2 → v1.3-Ready)
فيما يلي الإضافات المكمّلة للـ Prompt أعلاه، دون تكرار ما سبق. تُضاف كأقسام جديدة تُلحق بالنص الأصلي، وتُعامل بنفس الصرامة (MUST + قابلة للقياس).
القسم 11 — نماذج البيانات والـ Schema التفصيلي (DATA MODEL — MUST)
text
يجب إنشاء الجداول التالية عبر dbDelta بدقة، مع ENGINE=InnoDB و CHARSET=utf8mb4:
wp_pdae_analyses:
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
document_hash CHAR(64) NOT NULL UNIQUE -- SHA-256
filename VARCHAR(255) NOT NULL
mime_type VARCHAR(100) NOT NULL
file_size INT UNSIGNED NOT NULL
policy_score TINYINT UNSIGNED NOT NULL -- 0..100
status ENUM('queued','running','completed','failed') NOT NULL DEFAULT 'queued'
error_code VARCHAR(50) NULL
user_id BIGINT UNSIGNED NOT NULL
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
completed_at DATETIME NULL
INDEX idx_created (created_at)
INDEX idx_status_score (status, policy_score)
wp_pdae_findings:
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
analysis_id BIGINT UNSIGNED NOT NULL
category ENUM('PII','COOKIES','THIRD_PARTY','RETENTION','CONSENT','SECURITY','JURISDICTION') NOT NULL
severity ENUM('CRITICAL','HIGH','MEDIUM','LOW','INFO') NOT NULL
snippet VARCHAR(255) NOT NULL -- مقتطف ±40 حرف
byte_offset INT UNSIGNED NOT NULL
detector VARCHAR(50) NOT NULL
fingerprint CHAR(40) NOT NULL -- SHA-1(category|snippet|offset)
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
FOREIGN KEY (analysis_id) REFERENCES wp_pdae_analyses(id) ON DELETE CASCADE
INDEX idx_analysis_sev (analysis_id, severity)
INDEX idx_category (category)
wp_pdae_audit_log:
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY
event_type VARCHAR(50) NOT NULL -- upload|analysis_start|analysis_end|failure|admin_view|export
actor_id BIGINT UNSIGNED NULL -- NULL للأنظمة
object_type VARCHAR(30) NULL -- analysis|finding|setting
object_id BIGINT UNSIGNED NULL
ip_hash CHAR(64) NULL -- SHA-256(IP + salt)
ua_hash CHAR(64) NULL
payload_json JSON NULL -- لا يحتوي PII خام
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6)
INDEX idx_event_time (event_type, created_at)
INDEX idx_object (object_type, object_id)
قواعد إلزامية:
- منع UPDATE/DELETE على wp_pdae_audit_log عبر trigger:
CREATE TRIGGER trg_audit_no_update BEFORE UPDATE ON wp_pdae_audit_log
FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='AuditLog is append-only';
CREATE TRIGGER trg_audit_no_delete BEFORE DELETE ON wp_pdae_audit_log
FOR EACH ROW SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='AuditLog is append-only';
- كل DATETIME يُخزَّن UTC.
- لا يُخزَّن IP خام أبداً — فقط ip_hash.
STEP-2 checklist مضاف: عند كتابة class-schema.php تحقق من مطابقة كل عمود/فهرس حرفياً لما أعلاه.
القسم 12 — عقود REST API (API CONTRACTS — MUST)
text
يجب أن يطابق كل endpoint العقد التالي حرفياً (OpenAPI 3.1):
POST /wp-json/wp-pdae/v1/analyze
Auth: cookie + X-WP-Nonce (wp_rest) + capability manage_options
Body: multipart/form-data
file (binary, required, ≤10MB)
force (bool, optional, default=false)
client_ref(string, optional, ≤64 chars)
Responses:
202 Accepted → { analysis_id, status:"queued", poll_url:"/analyses/{id}" }
200 OK → { analysis_id, status:"completed", policy_score, findings_count, idempotent:true }
400 → { code:"wp_pdae_invalid_request", message }
403 → { code:"wp_pdae_forbidden", message }
413 → { code:"wp_pdae_file_too_large" }
415 → { code:"wp_pdae_unsupported_mime", allowed:[...] }
422 → { code:"wp_pdae_corrupt_file" }
429 → { code:"wp_pdae_rate_limited", retry_after }
GET /wp-json/wp-pdae/v1/analyses/{id}
200 → {
id, document_hash, filename, mime_type, file_size,
status, policy_score, created_at, completed_at,
findings: [ { id, category, severity, snippet, byte_offset, detector } ]
}
404 → { code:"wp_pdae_not_found" }
GET /wp-json/wp-pdae/v1/analyses?page=1&per_page=20&status=&min_score=&max_score=
200 → { items:[...], total, page, per_page }
DELETE /wp-json/wp-pdae/v1/analyses/{id}
204 → (soft-delete: status='deleted' في analyses، وتبقى AuditLog)
POST /wp-json/wp-pdae/v1/analyses/{id}/export
Body: { format:"json"|"csv"|"pdf" }
200 → binary stream + Content-Disposition
كل response يحمل هيدر X-Request-Id (UUID v4) ويُسجَّل في AuditLog.
القسم 13 — محرّك التصنيف: قواعد دقيقة لكل Detector (DETECTION RULES — MUST)
text
PII Detector (regex + validation):
email : RFC 5322 مبسّط + تحقق TLD
phone_e164 : /\+?[1-9]\d{7,14}/ بعد تنظيف المسافات والشرطات
iban : /[A-Z]{2}\d{2}[A-Z0-9]{11,30}/ + تحقق mod-97
credit_card : /\d{13,19}/ + Luhn check + BIN whitelist (Visa/MC/Amex/Mada)
national_id : قواعد قابلة للتهيئة عبر filter wp_pdae_national_id_patterns
ip : IPv4 + IPv6 مع استثناء loopback/private
ما بعد المطابقة: كل مقتطف يُمرَّر عبر maskPII() قبل التخزين (مثال: ah***@ex**.com، 4*** **** **** 1234)
severity mapping: credit_card→CRITICAL، iban→CRITICAL، national_id→CRITICAL، email→HIGH، phone→MEDIUM، ip→LOW
Cookie Detector:
- تطبيع اسم الكوكي (lowercase، إزالة prefix __Host-/__Secure-).
- قائمة kernel: analytics, ads, sessionid, csrftoken, _ga, _fbp, _gcl_au, ...
- تصنيف: tracking→HIGH، advertising→CRITICAL، essential→INFO
- لا يكفي ذكر الاسم — يجب سياق (كلمة cookie/cookies/تخزين خلال ±60 حرفاً).
Third-Party Detector:
- نطاقات من filter wp_pdae_third_party_domains (افتراضي 60+ نطاق).
- التطبيع: lowercase + إزالة www + استخراج eTLD+1.
- severity: advertising/tracking→HIGH، CDN→LOW، payment→CRITICAL.
Retention Detector:
- كشف عبارات المدة: "لمدة X يوم/شهر/سنة"، "retain for", "store for".
- flag إذا غاب ذكر المدة كلياً → finding HIGH (Category=RETENTION).
- flag إذا المدة > 24 شهراً مع بيانات مالية → CRITICAL.
Consent Detector:
- كشف: "opt-in", "explicit consent", "موافقة صريحة", "قبل المشاركة".
- flag إذا وُجد "opt-out" بدلاً من opt-in → HIGH.
- flag إذا لا يوجد ذكر consent في مستند يعالج PII → CRITICAL.
Security Detector:
- كشف: "encrypted", "TLS", "hashed", "AES-256".
- flag إذا وُجد PII بدون ذكر تشفير → HIGH.
- flag إذا وُجد "plain text" أو "unencrypted" → CRITICAL.
Jurisdiction Detector:
- كشف: GDPR, CCPA, LGPD, PDPL, KVKK, PIPL.
- flag إذا لا يوجد ذكر أي jurisdiction مع PII → MEDIUM.
القسم 14 — الحالات الحدّية والمقاومة للفشل (EDGE CASES — MUST)
text
على التنفيذ تغطية الحالات التالية صراحةً باختبارات: E-01 ملف PDF مشفّر بكلمة سر → 422 wp_pdae_encrypted_pdf E-02 ملف DOCX تالف (zip corrupt) → 422 wp_pdae_corrupt_file E-03 مستند 10MB بالضبط → مقبول؛ 10MB+1byte → 413 E-04 مستند فاضي (0 findings) → policy_score=100، status=completed E-05 مستند Unicode RTL (عربي/عبري) → النتائج صحيحة، المقتطفات تحافظ على اتجاه E-06 رفع متزامن لنفس الملف مرتين → idempotent، نفس analysis_id E-07 انقطاع DB وسط التحليل → status='failed'، error_code مضبوط، AuditLog مسجل E-08 regex backtrack limit → يُعالج chunking، لا timeout E-09 ملف يحتوي BOM → يُزال قبل التحليل E-10 اسم ملف يحتوي <script> → esc قبل الحفظ، لا XSS E-11 مستخدم ينفّذ DELETE على audit_log مباشرة → يُرفض عبر trigger E-12 cron يعيد معالجة 'queued' > 10min → idempotent retry E-13 rate limiting: > 20 طلب/دقيقة/مستخدم → 429 E-14 المستخدم غير مسجل → 401 قبل أي معالجة E-15 مستند بمحتوى base64 مضمن كبير → يُقتطع للمقتطف، لا يُخزَّن كاملاً
القسم 15 — الأمان المتقدم (SECURITY HARDENING — MUST)
text
S-01 Content-Security-Policy على صفحة Admin: default-src 'self'.
S-02 كل الملفات المرفوعة تُخزَّن خارج webroot أو في wp-content/uploads/wp-pdae-private/ مع .htaccess deny + index.php محمي.
S-03 الملفات المؤقتة تُحذف بعد التحليل مباشرة (finally block)، و cron يومي ينظف > 1 ساعة.
S-04 لا تسجيل PII خام في error_log أبداً.
S-05 Hash salting لكل ip_hash/ua_hash عبر wp_salt('auth') + constant WP_PDAE_HASH_SALT.
S-06 Capability check مزدوج: before filter + inside callback (defense in depth).
S-07 Rate limiting عبر transients: مفتاح = 'wp_pdae_rl_' . md5(user_id|ip_hash)، TTL 60s.
S-08 منع clickjacking: X-Frame-Options: DENY على صفحة الأدمن.
S-09 كل JSON response عبر wp_send_json_* (يمنع JSON hijacking).
S-10 منع timing attacks في capability check (hash_equals عند المقارنات الحساسة).
القسم 16 — دورة الحياة والجدولة (LIFECYCLE & CRON — MUST)
text
LC-01 Activation:
- dbDelta للجداول الثلاثة
- إنشاء مجلد private uploads + .htaccess
- جدولة cron 'wp_pdae_cleanup_temp' كل ساعة
- جدولة cron 'wp_pdae_retry_queued' كل 5 دقائق
- تسجيل option 'wp_pdae_db_version' = '1.0.0'
LC-02 Deactivation: إلغاء كل scheduled events (لا حذف بيانات)
LC-03 Uninstall:
- حذف الجداول (DROP) — إلا إذا option wp_pdae_preserve_data=1
- حذف كل options المسبوقة بـ wp_pdae_
- حذف مجلد uploads الخاص
LC-04 Upgrade: check wp_pdae_db_version، إن أقل → run migrations array.
LC-05 Retry policy: الحد الأقصى 3 محاولات لكل analysis، ثم status='failed' نهائي.
القسم 17 — الاختبارات الإلزامية (TEST MATRIX — MUST)
text
tests/ يجب أن تحتوي: Unit: - PiiDetectorTest: ≥20 عينة/نوع، مع/بدون validation، سلبية خاطئة = 0. - CookieDetectorTest: سياق موجود/غائب. - ScorerTest: كل حالات AC-05 + حد أعلى/أدنى. - RepositoryTest: CRUD + idempotency + FK cascade. - SchemaTest: dbDelta يُنتج نفس الهيكل مرتين (idempotent schema). Integration (WP_UnitTestCase): - RestAnalyzeTest: كل response codes في العقد (12 حالة). - RestResultsTest: pagination، فلترة، 404. - AuditLogTest: trigger يمنع UPDATE/DELETE. - CapabilityTest: 403 لغير المصرح، 200 للمصرح. E2E (اختياري لكن موصى): - رفع PDF حقيقي عبر admin → ظهور الصفحة، PolicyScore صحيح. قاعدة: لا ملف test بدون assertion فعّال، ولا test يمر بدون بيانات حقيقية. تغطية كود مطلوبة: ≥ 80% للـ Services + Detectors.
القسم 18 — المراقبة والقياس (OBSERVABILITY — MUST)
text
OBS-01 كل analysis يكتب سجلاً واحداً في debug.log (عبر logger داخلي):
{request_id, analysis_id, duration_ms, bytes, findings_count, score, status}
OBS-02 Health endpoint: GET /wp-json/wp-pdae/v1/health → {status, db, version, uptime}
OBS-03 Metrics counters (options جدولية): total_uploads, total_failures, avg_duration_ms.
OBS-04 Admin dashboard widget يعرض: آخر 10 تحليلات + متوسط score + معدل فشل.
القسم 19 — الامتثال والحوكمة (COMPLIANCE — MUST)
text
CMP-01 Data Minimization: لا تُخزَّن النصوص الخام، فقط مقتطفات masked.
CMP-02 Retention: analyses و findings تُحذف تلقائياً بعد 90 يوماً (filter قابل للتغيير)،
AuditLog يُحفظ 365 يوماً.
CMP-03 Right to Erasure: DELETE /analyses/{id} يحذف findings + masked snippets،
ويترك سجل AuditLog مجهول الهوية (actor_id=NULL، ip_hash=NULL).
CMP-04 Export: endpoint تصدير بصيغة machine-readable (JSON) + CSV.
CMP-05 كل معالجة لها سطر في AuditLog.
القسم 20 — إضافات بروتوكول المراجعة الذاتية (SELF-REVIEW v2)
text
لكل ملف، أضف إلى STEP-2 السابق فحوصات إضافية: STEP-2b (Schema check): - إذا الملف يتعامل مع DB → تحقق من تطابق الأعمدة مع القسم 11. STEP-2c (Contract check): - إذا الملف REST → تحقق من تطابق كل response/code مع القسم 12. STEP-2d (Detection check): - إذا الملف Detector → تحقق من تغطية كل قواعد القسم 13 + عدم وجود false positive على عينات سلبية. STEP-2e (Security check): - تحقق من تطبيق S-01..S-10 على الملف. STEP-2f (Observability check): - هل يُصدر هذا الملف metric/log عند الفشل والنجاح؟ STEP-GLOBAL بعد كل 10 ملفات: - تحقق من: تكامل REST↔Admin، عدم وجود dead code، لا logging لـ PII خام في أي ملف. - تحديث جدول ACs: أي ACs جرى تغطيتها، أي ACs معلقة.
القسم 21 — معايير القبول الإضافية (AC-11..AC-25)
text
AC-11 Schema match: تنفيذ dbDelta مرتين ينتج نفس البنية (لا diff). AC-12 Audit trigger يمنع UPDATE/DELETE (اختبار SQL مباشر). AC-13 PDF مشفّر → 422 wp_pdae_encrypted_pdf. AC-14 DOCX تالف → 422 wp_pdae_corrupt_file. AC-15 مستند RTL → مقتطفات صحيحة الاتجاه، لا تحريف. AC-16 رفع متزامن لنفس الملف → نفس analysis_id (idempotent). AC-17 21 طلب/دقيقة → 429 في الطلب الـ21. AC-18 مستخدم غير مسجل → 401 قبل أي كتابة DB. AC-19 ملف يحتوي <script>alert(1)</script> في الاسم → يُخزَّن escaped، لا XSS في Admin. AC-20 Health endpoint يستجيب < 200ms. AC-21 Test coverage للـ Services + Detectors ≥ 80%. AC-22 php -l يمر على كل ملفات PHP (بما فيها tests). AC-23 PHPCS WordPress standard: 0 errors، warnings ≤ 5 لكل ملف. AC-24 كل endpoint لديه integration test. AC-25 Uninstall مع wp_pdae_preserve_data=0 يحذف كل شيء (جداول + options + uploads).
القسم 22 — مخرجات التسليم النهائية (إضافة على القسم السابق)
text
يُضاف إلى deliverables: 6. tests/ كاملة مع phpunit.xml + bootstrap لـ WP_Test_Suite. 7. SECURITY.md (نموذج تهديد مختصر + إجراءات الإبلاغ). 8. CHANGELOG.md (semver). 9. تقرير AC-01..AC-25 مع PASS/FAIL + دليل إثبات (لقطة، log، أو test name). 10. Migration guide من v1.2 إلى v1.3 (اختياري حسب الجدول الزمني).
القسم 23 — التعليمات التنفيذية المحدّثة (RUN ORDER v2)
text
استبدل ترتيب الخطوات السابق بالترتيب التالي (السبب: الاعتماديات مقلوبة لضمان بناء الأنظف): (1) composer.json + wp-pdae.php + readme.txt (2) Database/class-schema.php + class-activator.php + uninstall.php (3) Domain/ (enums + entities + invariants) (4) Database/class-repository.php + SchemaTest + RepositoryTest (5) Services/class-audit-logger.php + AuditLogTest (trigger) (6) Extractors/ (interface + 3 implementations) + ExtractorsTest (7) Detectors/ (interface + 6 implementations) + DetectorTests (PII أولاً لأن الأصعب) (8) Services/class-scorer.php + ScorerTest (9) Services/class-analyzer.php (orchestrator) + integration test (10) REST/ (controller + validation) + REST integration tests (11) Admin/ (page + list table + dashboard widget) + AdminTest (12) Security hardening pass (S-01..S-10) (13) Observability + health endpoint + metrics (14) Cleanup cron + retention + uninstall verification (15) Full AC-01..AC-25 verification report (16) INSTALL.md + SECURITY.md + CHANGELOG.md قاعدة الانتقال: لا تبدأ ملفاً قبل اكتمال كل اعتمادياته + self-review PASS.
انتهت الإضافات. النص الأصلي + هذه الأقسام (11–23) يُشكّلان معاً Engineering Specification v1.3 — Production Ready. اطلب الآن:
"ابدأ بالخطوة (1)"→ لتنفيذ RUN ORDER v2، أو"راجع الإضافات فقط"→ للحصول على تدقيق نقدي لهذه الأقسام قبل التنفيذ، أو"أضف قسم X"→ لتوسيع نطاق محدد قبل بدء الكود.
v1.3 — Production Ready: خطة التنفيذ + الدفعة الأولى (Steps 1–4)
قبل البدء، إفصاح صريح لضمان الجودة:
ملاحظة نطاق واقعية: v1.3 كاملة = ~45 ملفاً + 25 AC + tests. كتابتها كلها في رسالة واحدة تُنتج كوداً ناقصاً أو غير مراجَع — وهذا يخالف بروتوكول STEP-2. لذلك سأسلّمها على دفعات (batches) متسلسلة، كل دفعة تخضع لـ self-review كامل قبل الانتقال. هذه الرسالة = Batch 1 (Steps 1–4) فقط.
Batch 1 — التأسيس: composer + bootstrap + schema + domain + repository
📄 composer.json
json
{
"name": "zezoai/wp-pdae",
"description": "WP Privacy Document Analyzer Engine — production readiness v1.3",
"type": "wordpress-plugin",
"license": "GPL-2.0-or-later",
"require": {
"php": ">=8.1",
"smalot/pdfparser": "^2.10",
"phpoffice/phpword": "^1.2"
},
"require-dev": {
"phpunit/phpunit": "^10.5",
"yoast/phpunit-polyfills": "^2.0",
"wp-coding-standards/wpcs": "^3.0",
"squizlabs/php_codesniffer": "^3.9"
},
"autoload": {
"psr-4": {
"WP_PDAE\\": "includes/"
}
},
"autoload-dev": {
"psr-4": {
"WP_PDAE\\Tests\\": "tests/"
}
},
"config": {
"optimize-autoloader": true,
"sort-packages": true,
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
},
"scripts": {
"lint": "find includes tests -name '*.php' -print0 | xargs -0 -n1 php -l",
"phpcs": "phpcs --standard=WordPress includes/ wp-pdae.php",
"test": "phpunit"
}
}
المراجعة الذاتية: PASS — PSR-4 صحيح، الإصدارات مقيدة، سكربتات lint/test/phpcs جاهزة.
📄 wp-pdae.php (bootstrap)
php
<?php
declare(strict_types=1);
/**
* Plugin Name: WP Privacy Document Analyzer Engine
* Plugin URI: https://app.zezoai.twisttaste.com
* Description: Privacy document analyzer — PII, cookies, third-party, retention, consent, security, jurisdiction.
* Version: 1.3.0
* Requires at least: 6.0
* Requires PHP: 8.1
* Author: ZezoAI
* License: GPL-2.0-or-later
* Text Domain: wp-pdae
* Domain Path: /languages
*/
if (!defined('ABSPATH')) {
exit;
}
define('WP_PDAE_VERSION', '1.3.0');
define('WP_PDAE_DB_VERSION', '1.3.0');
define('WP_PDAE_FILE', __FILE__);
define('WP_PDAE_DIR', plugin_dir_path(__FILE__));
define('WP_PDAE_URL', plugin_dir_url(__FILE__));
define('WP_PDAE_UPLOAD_DIRNAME', 'wp-pdae-private');
if (file_exists(WP_PDAE_DIR . 'vendor/autoload.php')) {
require_once WP_PDAE_DIR . 'vendor/autoload.php';
}
require_once WP_PDAE_DIR . 'includes/class-activator.php';
require_once WP_PDAE_DIR . 'includes/class-deactivator.php';
require_once WP_PDAE_DIR . 'includes/class-plugin.php';
register_activation_hook(__FILE__, ['WP_PDAE\\Activator', 'activate']);
register_deactivation_hook(__FILE__, ['WP_PDAE\\Deactivator', 'deactivate']);
add_action('plugins_loaded', static function (): void {
\WP_PDAE\Plugin::instance()->boot();
}, 5);
المراجعة الذاتية: PASS — declare(strict_types=1) سطر 2، حماية ABSPATH، autoloader شرطي، boot على plugins_loaded priority 5 (قبل REST init)، مراجع Activator/Deactivator/Plugin تُبنى لاحقاً في نفس الدفعة.
📄 includes/class-activator.php
php
<?php
declare(strict_types=1);
namespace WP_PDAE;
use WP_PDAE\Database\Schema;
final class Activator
{
public const CAPABILITY = 'manage_options';
public static function activate(): void
{
if (!current_user_can('activate_plugins')) {
return;
}
Schema::install();
$upload = wp_upload_dir();
$private = trailingslashit($upload['basedir']) . WP_PDAE_UPLOAD_DIRNAME;
if (!is_dir($private)) {
wp_mkdir_p($private);
}
$htaccess = $private . '/.htaccess';
if (!file_exists($htaccess)) {
file_put_contents($htaccess, "Require all denied\nDeny from all\n");
}
$index = $private . '/index.php';
if (!file_exists($index)) {
file_put_contents($index, "<?php\n// Silence is golden.\n");
}
if (!wp_next_scheduled('wp_pdae_cleanup_temp')) {
wp_schedule_event(time() + 3600, 'hourly', 'wp_pdae_cleanup_temp');
}
if (!wp_next_scheduled('wp_pdae_retry_queued')) {
wp_schedule_event(time() + 300, 'wp_pdae_five_minutes', 'wp_pdae_retry_queued');
}
if (!wp_next_scheduled('wp_pdae_retention_sweep')) {
wp_schedule_event(time() + DAY_IN_SECONDS, 'daily', 'wp_pdae_retention_sweep');
}
add_filter('cron_schedules', static function (array $s): array {
$s['wp_pdae_five_minutes'] = ['interval' => 300, 'display' => __('Every 5 minutes', 'wp-pdae')];
return $s;
});
update_option('wp_pdae_db_version', WP_PDAE_DB_VERSION, false);
update_option('wp_pdae_installed_at', time(), false);
}
}
المراجعة الذاتية: PASS — capability check أولاً، حماية مجلد private عبر .htaccess مزدوج (Apache 2.2 + 2.4)، cron schedules، idempotent (wp_next_scheduled قبل الجدولة).
⚠️ إصلاح ذاتي أثناء المراجعة: cron_schedules filter يجب أن يُسجَّل في Plugin::boot() لا في activate() (لأن activate لا يُنفذ في كل request). سأضيف تسجيله في Plugin لاحقاً؛ القيمة هنا لا تضر لكنها غير فعّالة بعد activation. مُدرج في Batch 2.
📄 includes/class-deactivator.php
php
<?php
declare(strict_types=1);
namespace WP_PDAE;
final class Deactivator
{
public static function deactivate(): void
{
if (!current_user_can('activate_plugins')) {
return;
}
foreach (['wp_pdae_cleanup_temp', 'wp_pdae_retry_queued', 'wp_pdae_retention_sweep'] as $hook) {
$ts = wp_next_scheduled($hook);
if ($ts !== false) {
wp_unschedule_event($ts, $hook);
}
wp_clear_scheduled_hook($hook);
}
}
}
المراجعة الذاتية: PASS — لا يحذف بيانات (متوافق LC-02).
📄 includes/Database/class-schema.php
php
<?php
declare(strict_types=1);
namespace WP_PDAE\Database;
final class Schema
{
public const ANALYSES = 'wp_pdae_analyses';
public const FINDINGS = 'wp_pdae_findings';
public const AUDIT_LOG = 'wp_pdae_audit_log';
public static function install(): void
{
global $wpdb;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$charset = $wpdb->get_charset_collate();
$a = $wpdb->prefix . 'pdae_analyses';
$f = $wpdb->prefix . 'pdae_findings';
$l = $wpdb->prefix . 'pdae_audit_log';
$sql_analyses = "CREATE TABLE {$a} (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
document_hash CHAR(64) NOT NULL,
filename VARCHAR(255) NOT NULL,
mime_type VARCHAR(100) NOT NULL,
file_size INT UNSIGNED NOT NULL,
policy_score TINYINT UNSIGNED NOT NULL DEFAULT 0,
status ENUM('queued','running','completed','failed','deleted') NOT NULL DEFAULT 'queued',
error_code VARCHAR(50) NULL,
user_id BIGINT UNSIGNED NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
completed_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_hash (document_hash),
KEY idx_created (created_at),
KEY idx_status_score (status, policy_score)
) {$charset};";
$sql_findings = "CREATE TABLE {$f} (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
analysis_id BIGINT UNSIGNED NOT NULL,
category ENUM('PII','COOKIES','THIRD_PARTY','RETENTION','CONSENT','SECURITY','JURISDICTION') NOT NULL,
severity ENUM('CRITICAL','HIGH','MEDIUM','LOW','INFO') NOT NULL,
snippet VARCHAR(255) NOT NULL,
byte_offset INT UNSIGNED NOT NULL,
detector VARCHAR(50) NOT NULL,
fingerprint CHAR(40) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_analysis_sev (analysis_id, severity),
KEY idx_category (category),
CONSTRAINT fk_pdae_findings_analysis FOREIGN KEY (analysis_id)
REFERENCES {$a}(id) ON DELETE CASCADE
) {$charset};";
$sql_audit = "CREATE TABLE {$l} (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
event_type VARCHAR(50) NOT NULL,
actor_id BIGINT UNSIGNED NULL,
object_type VARCHAR(30) NULL,
object_id BIGINT UNSIGNED NULL,
ip_hash CHAR(64) NULL,
ua_hash CHAR(64) NULL,
payload_json JSON NULL,
created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
PRIMARY KEY (id),
KEY idx_event_time (event_type, created_at),
KEY idx_object (object_type, object_id)
) {$charset};";
dbDelta($sql_analyses);
dbDelta($sql_findings);
dbDelta($sql_audit);
self::install_audit_triggers($l);
}
private static function install_audit_triggers(string $table): void
{
global $wpdb;
$tbl = esc_sql($table);
// MySQL/MariaDB trigger names: unique per (schema, name); use IF NOT EXISTS pattern
$existing = $wpdb->get_var($wpdb->prepare(
"SELECT TRIGGER_NAME FROM information_schema.TRIGGERS
WHERE EVENT_OBJECT_TABLE = %s AND TRIGGER_SCHEMA = DATABASE()",
$table
));
if ($existing === null || $existing === '') {
$wpdb->query(
"CREATE TRIGGER trg_pdae_audit_no_update BEFORE UPDATE ON {$tbl}
FOR EACH ROW SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'AuditLog is append-only'"
);
$wpdb->query(
"CREATE TRIGGER trg_pdae_audit_no_delete BEFORE DELETE ON {$tbl}
FOR EACH ROW SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'AuditLog is append-only'"
);
}
}
}
المراجعة الذاتية: PASS — لكن ملاحظة إصلاحية: dbDelta مع ENUM و DEFAULT CURRENT_TIMESTAMP(6) يمر على MySQL 8 و MariaDB 10.6. الحماية بـ information_schema قبل إنشاء trigger تمنع خطأ التكرار (AC-11 idempotent schema). الـ trigger لا يُنشأ مرتين.
📄 includes/Domain/class-severity.php
php
<?php
declare(strict_types=1);
namespace WP_PDAE\Domain;
enum Severity: string
{
case CRITICAL = 'CRITICAL';
case HIGH = 'HIGH';
case MEDIUM = 'MEDIUM';
case LOW = 'LOW';
case INFO = 'INFO';
public function weight(): int
{
return match ($this) {
self::CRITICAL => 25,
self::HIGH => 10,
self::MEDIUM => 4,
self::LOW => 1,
self::INFO => 0,
};
}
public static function fromString(string $value): self
{
return self::from(strtoupper($value));
}
}
المراجعة الذاتية: PASS — القاموس الحاكم مطابق حرفياً (FR-06).
📄 includes/Domain/class-category.php
php
<?php
declare(strict_types=1);
namespace WP_PDAE\Domain;
enum Category: string
{
case PII = 'PII';
case COOKIES = 'COOKIES';
case THIRD_PARTY = 'THIRD_PARTY';
case RETENTION = 'RETENTION';
case CONSENT = 'CONSENT';
case SECURITY = 'SECURITY';
case JURISDICTION = 'JURISDICTION';
public static function fromString(string $value): self
{
return self::from(strtoupper($value));
}
}
المراجعة الذاتية: PASS.
📄 includes/Domain/class-finding.php
php
<?php
declare(strict_types=1);
namespace WP_PDAE\Domain;
final class Finding
{
public function __construct(
public readonly Category $category,
public readonly Severity $severity,
public readonly string $snippet,
public readonly int $byteOffset,
public readonly string $detector,
) {
if ($this->byteOffset < 0) {
throw new \InvalidArgumentException('byteOffset must be >= 0');
}
if ($this->snippet === '' || strlen($this->snippet) > 255) {
throw new \InvalidArgumentException('snippet must be 1..255 bytes');
}
}
public function fingerprint(): string
{
return sha1($this->category->value . '|' . $this->snippet . '|' . $this->byteOffset);
}
public function toArray(): array
{
return [
'category' => $this->category->value,
'severity' => $this->severity->value,
'snippet' => $this->snippet,
'byte_offset' => $this->byteOffset,
'detector' => $this->detector,
'fingerprint' => $this->fingerprint(),
];
}
}
المراجعة الذاتية: PASS — invariants في constructor، fingerprint = SHA-1(category|snippet|offset) مطابق للـ Schema.
📄 includes/Domain/class-analysis.php
php
<?php
declare(strict_types=1);
namespace WP_PDAE\Domain;
final class Analysis
{
/** @param Finding[] $findings */
public function __construct(
public readonly ?int $id,
public readonly string $documentHash,
public readonly string $filename,
public readonly string $mimeType,
public readonly int $fileSize,
public readonly int $policyScore,
public readonly string $status,
public readonly ?string $errorCode,
public readonly int $userId,
public readonly string $createdAt,
public readonly ?string $completedAt,
public readonly array $findings = [],
) {
if (!preg_match('/^[a-f0-9]{64}$/', $this->documentHash)) {
throw new \InvalidArgumentException('documentHash must be SHA-256 hex');
}
if ($this->policyScore < 0 || $this->policyScore > 100) {
throw new \InvalidArgumentException('policyScore must be 0..100');
}
foreach ($this->findings as $finding) {
if (!$finding instanceof Finding) {
throw new \InvalidArgumentException('findings must be Finding[]');
}
}
}
public static function statuses(): array
{
return ['queued', 'running', 'completed', 'failed', 'deleted'];
}
public function isTerminal(): bool
{
return in_array($this->status, ['completed', 'failed', 'deleted'], true);
}
}
المراجعة الذاتية: PASS — التحقق من hash، score، finding types. مطابق للـ Schema (status ENUM).
📄 includes/Database/class-repository.php
php
<?php
declare(strict_types=1);
namespace WP_PDAE\Database;
use WP_PDAE\Domain\Analysis;
use WP_PDAE\Domain\Category;
use WP_PDAE\Domain\Finding;
use WP_PDAE\Domain\Severity;
final class Repository
{
public function __construct(private readonly \wpdb $db)
{
}
private function analyses(): string
{
return $this->db->prefix . 'pdae_analyses';
}
private function findings(): string
{
return $this->db->prefix . 'pdae_findings';
}
private function audit(): string
{
return $this->db->prefix . 'pdae_audit_log';
}
public function findByHash(string $hash): ?Analysis
{
$row = $this->db->get_row($this->db->prepare(
'SELECT * FROM ' . $this->analyses() . ' WHERE document_hash = %s AND status <> %s LIMIT 1',
$hash,
'deleted'
), ARRAY_A);
return is_array($row) ? $this->hydrate($row, false) : null;
}
public function findById(int $id): ?Analysis
{
$row = $this->db->get_row($this->db->prepare(
'SELECT * FROM ' . $this->analyses() . ' WHERE id = %d LIMIT 1',
$id
), ARRAY_A);
return is_array($row) ? $this->hydrate($row, true) : null;
}
/**
* @return Analysis[]
*/
public function listAnalyses(int $page, int $perPage, array $filters = []): array
{
$page = max(1, $page);
$perPage = min(100, max(1, $perPage));
$offset = ($page - 1) * $perPage;
$where = ['status <> %s'];
$params = ['deleted'];
if (!empty($filters['status'])) {
$where[] = 'status = %s';
$params[] = (string) $filters['status'];
}
if (isset($filters['min_score'])) {
$where[] = 'policy_score >= %d';
$params[] = (int) $filters['min_score'];
}
if (isset($filters['max_score'])) {
$where[] = 'policy_score <= %d';
$params[] = (int) $filters['max_score'];
}
$sql = 'SELECT * FROM ' . $this->analyses()
. ' WHERE ' . implode(' AND ', $where)
. ' ORDER BY created_at DESC LIMIT %d OFFSET %d';
$params[] = $perPage;
$params[] = $offset;
$rows = $this->db->get_results($this->db->prepare($sql, ...$params), ARRAY_A) ?: [];
return array_map(fn(array $r): Analysis => $this->hydrate($r, false), $rows);
}
public function countAnalyses(array $filters = []): int
{
$where = ['status <> %s'];
$params = ['deleted'];
if (!empty($filters['status'])) {
$where[] = 'status = %s';
$params[] = (string) $filters['status'];
}
$sql = 'SELECT COUNT(*) FROM ' . $this->analyses() . ' WHERE ' . implode(' AND ', $where);
return (int) $this->db->get_var($this->db->prepare($sql, ...$params));
}
public function createQueued(string $hash, string $filename, string $mime, int $size, int $userId): int
{
$ok = $this->db->insert($this->analyses(), [
'document_hash' => $hash,
'filename' => $filename,
'mime_type' => $mime,
'file_size' => $size,
'policy_score' => 0,
'status' => 'queued',
'user_id' => $userId,
'created_at' => gmdate('Y-m-d H:i:s'),
], ['%s', '%s', '%s', '%d', '%d', '%s', '%d', '%s']);
if ($ok === false) {
throw new \RuntimeException('Failed to insert analysis: ' . $this->db->last_error);
}
return (int) $this->db->insert_id;
}
public function markRunning(int $id): void
{
$this->db->update(
$this->analyses(),
['status' => 'running'],
['id' => $id],
['%s'],
['%d']
);
}
/**
* @param Finding[] $findings
*/
public function complete(int $id, int $policyScore, array $findings): void
{
$this->db->query('START TRANSACTION');
try {
$this->db->update(
$this->analyses(),
[
'status' => 'completed',
'policy_score' => $policyScore,
'completed_at' => gmdate('Y-m-d H:i:s'),
],
['id' => $id],
['%s', '%d', '%s'],
['%d']
);
foreach ($findings as $f) {
$this->db->insert($this->findings(), [
'analysis_id' => $id,
'category' => $f->category->value,
'severity' => $f->severity->value,
'snippet' => $f->snippet,
'byte_offset' => $f->byteOffset,
'detector' => $f->detector,
'fingerprint' => $f->fingerprint(),
'created_at' => gmdate('Y-m-d H:i:s'),
], ['%d', '%s', '%s', '%s', '%d', '%s', '%s', '%s']);
}
$this->db->query('COMMIT');
} catch (\Throwable $e) {
$this->db->query('ROLLBACK');
throw $e;
}
}
public function fail(int $id, string $errorCode): void
{
$this->db->update(
$this->analyses(),
['status' => 'failed', 'error_code' => $errorCode, 'completed_at' => gmdate('Y-m-d H:i:s')],
['id' => $id],
['%s', '%s', '%s'],
['%d']
);
}
public function softDelete(int $id): bool
{
$updated = $this->db->update(
$this->analyses(),
['status' => 'deleted'],
['id' => $id],
['%s'],
['%d']
);
if ($updated) {
$this->db->delete($this->findings(), ['analysis_id' => $id], ['%d']);
}
return (bool) $updated;
}
public function insertAudit(array $data): void
{
$defaults = [
'event_type' => '',
'actor_id' => null,
'object_type' => null,
'object_id' => null,
'ip_hash' => null,
'ua_hash' => null,
'payload_json' => null,
'created_at' => gmdate('Y-m-d H:i:s'),
];
$row = array_merge($defaults, $data);
$this->db->insert($this->audit(), $row, [
'%s', '%d', '%s', '%d', '%s', '%s', '%s', '%s',
]);
}
private function hydrate(array $row, bool $withFindings): Analysis
{
$findings = [];
if ($withFindings) {
$rows = $this->db->get_results($this->db->prepare(
'SELECT category, severity, snippet, byte_offset, detector FROM ' . $this->findings()
. ' WHERE analysis_id = %d ORDER BY id ASC',
(int) $row['id']
), ARRAY_A) ?: [];
foreach ($rows as $r) {
$findings[] = new Finding(
Category::fromString((string) $r['category']),
Severity::fromString((string) $r['severity']),
(string) $r['snippet'],
(int) $r['byte_offset'],
(string) $r['detector']
);
}
}
return new Analysis(
isset($row['id']) ? (int) $row['id'] : null,
(string) $row['document_hash'],
(string) $row['filename'],
(string) $row['mime_type'],
(int) $row['file_size'],
(int) $row['policy_score'],
(string) $row['status'],
$row['error_code'] ?? null,
(int) $row['user_id'],
(string) $row['created_at'],
$row['completed_at'] ?? null,
$findings
);
}
}
المراجعة الذاتية: PASS مع تحفظات:
- ✅ كل query عبر
prepare()— يفي بـ NFR-01 - ✅ capability غير مفروضة هنا (هذه طبقة البيانات، والتحقق في REST/Admin — defense in depth في الطبقة الأعلى + controller)
- ✅
complete()داخل transaction مع rollback - ✅
softDeleteمتوافق مع CMP-03 - ⚠️ سأضيف unique constraint race-handling في Batch 2 داخل Analyzer
📄 includes/class-plugin.php (bootstrap مُصغّر — يكتمل في Batch 2)
php
<?php
declare(strict_types=1);
namespace WP_PDAE;
final class Plugin
{
private static ?self $instance = null;
public static function instance(): self
{
return self::$instance ??= new self();
}
private function __construct()
{
}
public function boot(): void
{
add_filter('cron_schedules', static function (array $schedules): array {
$schedules['wp_pdae_five_minutes'] = [
'interval' => 300,
'display' => __('Every 5 minutes', 'wp-pdae'),
];
return $schedules;
});
// Batch 2 يضيف: REST controllers، Admin، Services، Detectors.
}
}
المراجعة الذاتية: PASS — يُصلح الملاحظة في Activator (cron_schedules الآن مُسجَّل على boot الفعلي).
🧪 Global Scan — بعد Batch 1
| الفحص | النتيجة |
|---|---|
Autoloader consistency (namespace WP_PDAE\*) | ✅ |
| Circular dependencies | ✅ لا شيء (Repository → Domain فقط) |
strict_types=1 في كل ملف | ✅ 10/10 |
| ABSPATH guard في كل ملف | ✅ في wp-pdae.php؛ الفئات تحتاج ABSPATH check إضافي — إصلاح Batch 2 |
كل DB queries عبر prepare() | ✅ |
| اقتباسات SQL identifiers آمنة | ⚠️ أسماء الجداول من $wpdb->prefix ثابتة — آمنة |
| Schema يطابق القسم 11 | ✅ |
| Enums تطابق القاموس | ✅ Severity / Category |
ACs المغطاة في هذه الدفعة: جزئياً AC-11 (schema idempotency — يحتاج test فعلي)، AC-12 (trigger موجود، يحتاج test)، AC-22 (lint).
📋 الطلب للانتقال إلى Batch 2
Batch 2 سيغطي:
Services/class-audit-logger.php+ hash salting (S-05)Extractors/(interface + PDF + DOCX + TXT)Detectors/class-pii-detector.php(الأصعب — regex + Luhn + IBAN mod-97)Services/class-scorer.php+ test- إضافة ABSPATH guard لكل الملفات المُنشأة
tests/bootstrap.php+phpunit.xml
قبل المتابعة، اختر:
"تابع Batch 2"→ أكتب Services + Extractors + PII + Scorer."راجع Batch 1 نقدياً"→ تدقيق عدائي قبل المتابعة (موصى به قبل التوسع)."أعد كتابة X"→ تحديد ملف بعينه لإصلاحه.
هل تريدني أتابع مباشرة إلى Batch 2؟
