BxBaseServices.php 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaBaseView UNA Base Representation Classes
  7. * @{
  8. */
  9. /**
  10. * System services.
  11. */
  12. class BxBaseServices extends BxDol implements iBxDolProfileService
  13. {
  14. public function __construct()
  15. {
  16. parent::__construct();
  17. }
  18. public function serviceIsPublicService($s)
  19. {
  20. $sService = bx_gen_method_name($s);
  21. $aServices = $this->serviceGetPublicServices();
  22. return isset($aServices[$sService]);
  23. }
  24. public function serviceGetPublicServices()
  25. {
  26. return array (
  27. 'GetProductsNames' => 'BxBaseServices',
  28. 'GetPageByRequest' => 'BxBaseServicePages',
  29. );
  30. }
  31. public function serviceIsSafeService($s)
  32. {
  33. $sService = bx_gen_method_name($s);
  34. $aSafeServices = $this->serviceGetSafeServices();
  35. return isset($aSafeServices[$sService]);
  36. }
  37. public function serviceGetSafeServices()
  38. {
  39. return array(
  40. 'GetMenu' => 'BxBaseServices',
  41. 'GetCreatePostForm' => 'BxBaseServices',
  42. 'GetProductsNames' => 'BxBaseServices',
  43. 'KeywordSearch' => 'BxBaseServices',
  44. 'GetDataSearchApi' => 'BxBaseServices',
  45. 'Cmts' => 'BxBaseServices',
  46. 'GetFooter' => 'BxBaseServices',
  47. 'SetBadges' => 'BxBaseServices',
  48. 'GetPageContentByRequest' => 'BxBaseServicePages',
  49. 'GetPageBlockData' => 'BxBaseServicePages',
  50. 'SetPageBlockData' => 'BxBaseServicePages',
  51. 'GetPageBlockImageData' => 'BxBaseServicePages',
  52. 'GetUrlInfo' => 'BxBaseServicePages',
  53. 'CreateAccountForm' => 'BxBaseServiceAccount',
  54. 'AccountSettingsEmail' => 'BxBaseServiceAccount',
  55. 'AccountSettingsPassword' => 'BxBaseServiceAccount',
  56. 'AccountSettingsDelAccount' => 'BxBaseServiceAccount',
  57. 'AccountSettingsInfo' => 'BxBaseServiceAccount',
  58. 'ForgotPassword' => 'BxBaseServiceAccount',
  59. 'SwitchProfile' => 'BxBaseServiceAccount',
  60. 'AccountProfileSwitcher' => 'BxBaseServiceAccount',
  61. 'EmailConfirmation' => 'BxBaseServiceAccount',
  62. 'ConfirmEmail' => 'BxBaseServiceAccount',
  63. 'CategoriesList' => 'BxBaseServiceCategory',
  64. 'Test' => 'BxBaseServiceLogin',
  65. 'MemberAuthCode' => 'BxBaseServiceLogin',
  66. 'LoginForm' => 'BxBaseServiceLogin',
  67. 'LoginFormOnly' => 'BxBaseServiceLogin',
  68. 'Logout' => 'BxBaseServiceLogin',
  69. 'KeywordsCloud' => 'BxBaseServiceMetatags',
  70. 'AccountProfileSwitcher' => 'BxBaseServiceProfiles',
  71. 'ProfileMembership' => 'BxBaseServiceProfiles',
  72. 'ProfileNotifications' => 'BxBaseServiceProfiles',
  73. 'GetCountOnlineProfiles' => 'BxBaseServiceProfiles',
  74. 'BrowseRecommendationsFriends' => 'BxBaseServiceProfiles',
  75. 'BrowseRecommendationsSubscriptions' => 'BxBaseServiceProfiles',
  76. 'BrowseFriends' => 'BxBaseServiceProfiles',
  77. 'SetMembership' => 'BxBaseServiceProfiles',
  78. 'ResetMembership' => 'BxBaseServiceProfiles',
  79. 'BrowseFriendRequests' => 'BxBaseServiceProfiles',
  80. 'BrowseFriendRequested' => 'BxBaseServiceProfiles',
  81. 'BrowseSubscribedMe' => 'BxBaseServiceProfiles',
  82. 'BrowseSubscriptions' => 'BxBaseServiceProfiles',
  83. 'BrowseMembers' => 'BxBaseServiceProfiles',
  84. 'BrowseInvitations' => 'BxBaseServiceProfiles',
  85. 'UpdateSettings' => 'BxBaseServiceProfiles',
  86. 'Befriend' => 'BxBaseServiceProfiles',
  87. 'ProfileCounters' => 'BxBaseServiceProfiles',
  88. 'ProfileInfo' => 'BxBaseServiceProfiles',
  89. 'GetChartGrowth' => 'BxBaseChartServices',
  90. 'GetChartStats' => 'BxBaseChartServices',
  91. 'GetDataByInterval' => 'BxBaseChartServices',
  92. 'GetCartItemsCount' => 'BxBasePaymentsServices',
  93. 'GetOrdersCount' => 'BxBasePaymentsServices',
  94. 'Do' => 'BxBaseReportServices',
  95. 'GetPerformedBy' => 'BxBaseReportServices',
  96. 'Do' => 'BxBaseVoteServices',
  97. 'GetPerformedBy' => 'BxBaseVoteServices',
  98. 'Perform' => 'BxBaseFeatureServices',
  99. 'Perform' => 'BxBaseFavoriteServices',
  100. 'GetPerformedBy' => 'BxBaseFavoriteServices',
  101. 'Perform' => 'BxBaseServiceConnections',
  102. 'Perform' => 'BxBaseServiceRecommendations',
  103. 'GetDataApi' => 'BxBaseCmtsServices',
  104. 'GetDataApi' => 'BxBaseUploaderServices',
  105. 'GetUploadToken' => 'BxBaseUploaderServices',
  106. 'GetStatBlock' => 'BxBaseDashboardServices',
  107. 'PerfomActionApi' => 'BxBaseServiceGrid',
  108. 'GetLabels' => 'BxBaseLabelsServices',
  109. 'GetForm' => 'BxBaseSearchExtendedServices',
  110. 'GetResults' => 'BxBaseSearchExtendedServices',
  111. 'WikiAction' => 'BxBaseServiceWiki',
  112. 'AiChat' => 'BxBaseServices',
  113. 'AiChatUpload' => 'BxBaseServices',
  114. 'GetBlockAiAgentOperator' => 'BxBaseServices',
  115. 'GetAiChatThreads' => 'BxBaseServices',
  116. 'GetAiChatThread' => 'BxBaseServices',
  117. 'GetAiAgents' => 'BxBaseServices',
  118. 'GetBlockAiAgentsAdmin' => 'BxBaseServices',
  119. 'SetAiAgentActive' => 'BxBaseServices',
  120. 'GetAiAgentActivity' => 'BxBaseServices',
  121. 'GetAiAgentChatThreads' => 'BxBaseServices',
  122. 'GetAiAgentChatThread' => 'BxBaseServices',
  123. 'GetMockupBlock' => 'BxBaseServices',
  124. );
  125. }
  126. public function serviceGetPreloaderContent($sName) {
  127. $sResult = '';
  128. switch($sName) {
  129. case 'icons_css':
  130. if(($sCss = BxDolIconset::getObjectInstance()->getPreloaderCss()) !== false)
  131. $sResult = $sCss;
  132. break;
  133. case 'icons_js':
  134. if(($sJs = BxDolIconset::getObjectInstance()->getPreloaderJs()) !== false)
  135. $sResult = $sJs;
  136. break;
  137. case 'tailwind':
  138. $sFile = getParam('sys_css_tailwind_default');
  139. if(empty($sFile))
  140. $sFile = 'tailwind.min.css';
  141. $sPath = '{dir_plugins_public}tailwind/css/|';
  142. if($sFile == 'cdn')
  143. $sResult = [
  144. 'https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4',
  145. $sPath . 'tailwind.min.css' //TODO: Replace this with correct file name.
  146. ];
  147. else
  148. $sResult = $sPath . $sFile;
  149. break;
  150. }
  151. return $sResult;
  152. }
  153. /**
  154. * @page service Service Calls
  155. * @section bx_system_general System Services
  156. * @subsection bx_system_general-general General
  157. * @subsubsection bx_system_general-module_check_for_update module_check_for_update
  158. *
  159. * @code bx_srv('system', 'module_check_for_update', ["bx_posts"]); @endcode
  160. * @code bx_srv('system', 'module_check_for_update', ["bx_posts"], 'TemplServices'); @endcode
  161. * @code {{~system:module_check_for_update:TemplServices["bx_posts"]~}} @endcode
  162. *
  163. * Checks whether an update is available for requested module or not.
  164. * @param $mixedModule - module ID/name to check the updates for.
  165. * @return array with information about the update, false if nothing was found
  166. *
  167. * @see BxBaseServices::serviceModuleCheckForUpdate
  168. */
  169. /**
  170. * @ref bx_system_general-module_check_for_update "module_check_for_update"
  171. */
  172. public function serviceModuleCheckForUpdate($mixedModule)
  173. {
  174. $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
  175. if(empty($aModule) || !is_array($aModule))
  176. return false;
  177. $aUpdates = BxDolStudioInstallerUtils::getInstance()->checkUpdatesByModule($aModule['name']);
  178. if(empty($aUpdates) || !is_array($aUpdates))
  179. return false;
  180. $aUpdate = array_shift($aUpdates);
  181. return array(
  182. 'version_from' => $aUpdate['file_version'],
  183. 'version_to' => $aUpdate['file_version_to'],
  184. 'file_id' => $aUpdate['file_id']
  185. );
  186. }
  187. /**
  188. * @page service Service Calls
  189. * @section bx_system_general System Services
  190. * @subsection bx_system_general-general General
  191. * @subsubsection bx_system_general-module_update module_update
  192. *
  193. * @code bx_srv('system', 'module_update', ["bx_posts"]); @endcode
  194. * @code bx_srv('system', 'module_update', ["bx_posts"], 'TemplServices'); @endcode
  195. * @code {{~system:module_update:TemplServices["bx_posts"]~}} @endcode
  196. *
  197. * Download and install an update for requested module. The operation may be performed
  198. * immediately or by Transient Cron task. The second way is more common.
  199. * @param $mixedModule - module ID/name to check the updates for.
  200. * @return integer value determining the result of the operation. It can be one of the following values:
  201. * BX_DOL_STUDIO_IU_RC_SUCCESS, BX_DOL_STUDIO_IU_RC_FAILED or BX_DOL_STUDIO_IU_RC_SCHEDULED.
  202. *
  203. * @see BxBaseServices::serviceModuleUpdate
  204. */
  205. /**
  206. * @ref bx_system_general-module_update "module_update"
  207. */
  208. public function serviceModuleUpdate($mixedModule)
  209. {
  210. $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
  211. if(empty($aModule) || !is_array($aModule))
  212. return BX_DOL_STUDIO_IU_RC_FAILED;
  213. $aResult = BxDolStudioInstallerUtils::getInstance()->downloadUpdatePublic($aModule['name'], true);
  214. return $aResult['code'];
  215. }
  216. /**
  217. * @page service Service Calls
  218. * @section bx_system_general System Services
  219. * @subsection bx_system_general-general General
  220. * @subsubsection bx_system_general-module_delete module_delete
  221. *
  222. * @code bx_srv('system', 'module_delete', ["bx_posts"]); @endcode
  223. * @code bx_srv('system', 'module_delete', ["bx_posts", true], 'TemplServices'); @endcode
  224. * @code {{~system:module_delete:TemplServices["bx_posts"]~}} @endcode
  225. *
  226. * Delete the requested module. By default only uninstalled module can be deleted.
  227. * The operation may be performed immediately or by Transient Cron task. The second way is more common.
  228. * @param $sModule - module name to delete.
  229. * @param $bForceUninstall - if 'true' is passed the module will be uninstalled before deletion.
  230. * @return integer value determining the result of the operation. It can be one of the following values:
  231. * BX_DOL_STUDIO_IU_RC_SUCCESS, BX_DOL_STUDIO_IU_RC_FAILED or BX_DOL_STUDIO_IU_RC_SCHEDULED.
  232. *
  233. * @see BxBaseServices::serviceModuleDelete
  234. */
  235. /**
  236. * @ref bx_system_general-module_delete "module_delete"
  237. */
  238. public function serviceModuleDelete($sModule, $bForceUninstall = false)
  239. {
  240. $sModulePath = '';
  241. $oInstallerUtils = BxDolStudioInstallerUtils::getInstance();
  242. $aModule = BxDolModuleQuery::getInstance()->getModuleByName($sModule, false);
  243. if(!empty($aModule) && is_array($aModule)) {
  244. if(!$bForceUninstall)
  245. return BX_DOL_STUDIO_IU_RC_FAILED;
  246. $sModulePath = $aModule['path'];
  247. $aResult = $oInstallerUtils->perform($sModulePath, 'uninstall', array('auto_disable' => $bForceUninstall));
  248. if($aResult['code'] != BX_DOL_STUDIO_IU_RC_SUCCESS)
  249. return BX_DOL_STUDIO_IU_RC_FAILED;
  250. }
  251. else {
  252. $aModules = $oInstallerUtils->getModules(false);
  253. if(!isset($aModules[$sModule]))
  254. return BX_DOL_STUDIO_IU_RC_FAILED;
  255. $sModulePath = $aModules[$sModule]['dir'];
  256. }
  257. $aResult = $oInstallerUtils->perform($sModulePath, 'delete');
  258. return $aResult['code'];
  259. }
  260. /**
  261. * @page service Service Calls
  262. * @section bx_system_general System Services
  263. * @subsection bx_system_general-general General
  264. * @subsubsection bx_system_general-module_install module_install
  265. *
  266. * @code bx_srv('system', 'module_install', ["bx_posts"]); @endcode
  267. * @code bx_srv('system', 'module_install', ["bx_posts", true], 'TemplServices'); @endcode
  268. * @code {{~system:module_install:TemplServices["bx_posts"]~}} @endcode
  269. *
  270. * Install the requested module. By default the module will be installed only.
  271. * @param $sModule - module name to install.
  272. * @param $bForceEnable - if 'true' is passed the module will be automatically enabled after installation.
  273. * @return boolean value determining the result of the operation.
  274. *
  275. * @see BxBaseServices::serviceModuleInstall
  276. */
  277. /**
  278. * @ref bx_system_general-module_install "module_install"
  279. */
  280. public function serviceModuleInstall($sModule, $bForceEnable = false)
  281. {
  282. $oInstallerUtils = BxDolStudioInstallerUtils::getInstance();
  283. $aModules = $oInstallerUtils->getModules(false);
  284. if(!isset($aModules[$sModule]))
  285. return false;
  286. $aResult = $oInstallerUtils->perform($aModules[$sModule]['dir'], 'install', array('auto_enable' => $bForceEnable));
  287. if($aResult['code'] != BX_DOL_STUDIO_IU_RC_SUCCESS)
  288. return false;
  289. return true;
  290. }
  291. /**
  292. * @page service Service Calls
  293. * @section bx_system_general System Services
  294. * @subsection bx_system_general-general General
  295. * @subsubsection bx_system_general-module_uninstall module_uninstall
  296. *
  297. * @code bx_srv('system', 'module_uninstall', ["bx_posts"]); @endcode
  298. * @code bx_srv('system', 'module_uninstall', ["bx_posts", true], 'TemplServices'); @endcode
  299. * @code {{~system:module_uninstall:TemplServices["bx_posts"]~}} @endcode
  300. *
  301. * Uninstall the requested module. By default only disabled module can be uninstalled.
  302. * @param $mixedModule - module ID/name to uninstall.
  303. * @param $bForceDisable - if 'true' is passed the module will be automatically disabled before uninstallation.
  304. * @return boolean value determining the result of the operation.
  305. *
  306. * @see BxBaseServices::serviceModuleUninstall
  307. */
  308. /**
  309. * @ref bx_system_general-module_uninstall "module_uninstall"
  310. */
  311. public function serviceModuleUninstall($mixedModule, $bForceDisable = false)
  312. {
  313. $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
  314. if(empty($aModule) || !is_array($aModule))
  315. return false;
  316. if((int)$aModule['enabled'] != 0 && !$bForceDisable)
  317. return false;
  318. $aResult = BxDolStudioInstallerUtils::getInstance()->perform($aModule['path'], 'uninstall', array('auto_disable' => $bForceDisable));
  319. if($aResult['code'] != BX_DOL_STUDIO_IU_RC_SUCCESS)
  320. return false;
  321. return true;
  322. }
  323. /**
  324. * @page service Service Calls
  325. * @section bx_system_general System Services
  326. * @subsection bx_system_general-general General
  327. * @subsubsection bx_system_general-module_enable module_enable
  328. *
  329. * @code bx_srv('system', 'module_enable', ["bx_posts"]); @endcode
  330. * @code bx_srv('system', 'module_enable', ["bx_posts"], 'TemplServices'); @endcode
  331. * @code {{~system:module_enable:TemplServices["bx_posts"]~}} @endcode
  332. *
  333. * Enable the requested module.
  334. * @param $mixedModule - module ID/name to enable.
  335. * @return boolean value determining the result of the operation.
  336. *
  337. * @see BxBaseServices::serviceModuleEnable
  338. */
  339. /**
  340. * @ref bx_system_general-module_enable "module_enable"
  341. */
  342. public function serviceModuleEnable($mixedModule)
  343. {
  344. $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
  345. if(empty($aModule) || !is_array($aModule))
  346. return false;
  347. if((int)$aModule['enabled'] != 0)
  348. return false;
  349. $aResult = BxDolStudioInstallerUtils::getInstance()->perform($aModule['path'], 'enable');
  350. if($aResult['code'] != BX_DOL_STUDIO_IU_RC_SUCCESS)
  351. return false;
  352. return true;
  353. }
  354. /**
  355. * @page service Service Calls
  356. * @section bx_system_general System Services
  357. * @subsection bx_system_general-general General
  358. * @subsubsection bx_system_general-module_disable module_disable
  359. *
  360. * @code bx_srv('system', 'module_disable', ["bx_posts"]); @endcode
  361. * @code bx_srv('system', 'module_disable', ["bx_posts"], 'TemplServices'); @endcode
  362. * @code {{~system:module_disable:TemplServices["bx_posts"]~}} @endcode
  363. *
  364. * Disable the requested module.
  365. * @param $mixedModule - module ID/name to disable.
  366. * @return boolean value determining the result of the operation.
  367. *
  368. * @see BxBaseServices::serviceModuleDisable
  369. */
  370. /**
  371. * @ref bx_system_general-module_disable "module_disable"
  372. */
  373. public function serviceModuleDisable($mixedModule)
  374. {
  375. $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
  376. if(empty($aModule) || !is_array($aModule))
  377. return false;
  378. if((int)$aModule['enabled'] == 0)
  379. return false;
  380. $aResult = BxDolStudioInstallerUtils::getInstance()->perform($aModule['path'], 'disable');
  381. if($aResult['code'] != BX_DOL_STUDIO_IU_RC_SUCCESS)
  382. return false;
  383. return true;
  384. }
  385. /**
  386. * @page service Service Calls
  387. * @section bx_system_general System Services
  388. * @subsection bx_system_general-general General
  389. * @subsubsection bx_system_general-is_module_installed is_module_installed
  390. *
  391. * @code bx_srv('system', 'is_module_installed', ["bx_posts"]); @endcode
  392. * @code bx_srv('system', 'is_module_installed', ["bx_posts"], 'TemplServices'); @endcode
  393. * @code {{~system:is_module_installed:TemplServices["bx_posts"]~}} @endcode
  394. *
  395. * Checks whether the requested module is installed or not.
  396. * @param $mixedModule - module ID/name to check.
  397. * @return boolean value determining the result of the operation.
  398. *
  399. * @see BxBaseServices::serviceIsModuleInstalled
  400. */
  401. /**
  402. * @ref bx_system_general-is_module_installed "is_module_installed"
  403. */
  404. public function serviceIsModuleInstalled($mixedModule)
  405. {
  406. $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
  407. return !empty($aModule) && is_array($aModule);
  408. }
  409. /**
  410. * @page service Service Calls
  411. * @section bx_system_general System Services
  412. * @subsection bx_system_general-general General
  413. * @subsubsection bx_system_general-is_module_enabled is_module_enabled
  414. *
  415. * @code bx_srv('system', 'is_module_enabled', ["bx_posts"]); @endcode
  416. * @code bx_srv('system', 'is_module_enabled', ["bx_posts"], 'TemplServices'); @endcode
  417. * @code {{~system:is_module_enabled:TemplServices["bx_posts"]~}} @endcode
  418. *
  419. * Checks whether the requested module is enabled or not.
  420. * @param $mixedModule - module ID/name to check.
  421. * @return boolean value determining the result of the operation.
  422. *
  423. * @see BxBaseServices::serviceIsModuleEnabled
  424. */
  425. /**
  426. * @ref bx_system_general-is_module_enabled "is_module_enabled"
  427. */
  428. public function serviceIsModuleEnabled($mixedModule)
  429. {
  430. $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
  431. return !empty($aModule) && is_array($aModule) && (int)$aModule['enabled'] != 0;
  432. }
  433. /**
  434. * Checks whether a module is a 'Content' module or not.
  435. *
  436. * @param string $mixedModule - module name or an instance of Module class.
  437. * @return boolean result of operation.
  438. */
  439. public function serviceIsModuleContent($mixedModule)
  440. {
  441. if($mixedModule instanceof BxDolModule)
  442. $mixedModule = $mixedModule->getName();
  443. return BxDolModuleQuery::getInstance()->isModuleContent($mixedModule);
  444. }
  445. /**
  446. * Checks whether a module is a 'Context' module or not.
  447. *
  448. * @param string $mixedModule - module name or an instance of Module class.
  449. * @return boolean result of operation.
  450. */
  451. public function serviceIsModuleContext($mixedModule)
  452. {
  453. if($mixedModule instanceof BxDolModule)
  454. $mixedModule = $mixedModule->getName();
  455. return BxDolModuleQuery::getInstance()->isModuleContext($mixedModule);
  456. }
  457. /**
  458. * Checks whether a module is a 'Profile' module or not.
  459. *
  460. * @param string $mixedModule - module name or an instance of Module class.
  461. * @return boolean result of operation.
  462. */
  463. public function serviceIsModuleProfile($mixedModule)
  464. {
  465. if($mixedModule instanceof BxDolModule)
  466. $mixedModule = $mixedModule->getName();
  467. return BxDolModuleQuery::getInstance()->isModuleProfile($mixedModule);
  468. }
  469. /**
  470. * Get modules by type. Available types are 'content', 'context', 'profile'.
  471. *
  472. * @param type $sType - string with type.
  473. * @return array of modules.
  474. */
  475. public function serviceGetModulesByType($sType, $aParams = [])
  476. {
  477. $oModuleQuery = BxDolModuleQuery::getInstance();
  478. if(!$oModuleQuery->checkModulesSubtypes()) {
  479. $oInstallerUtils = new BxDolInstallerUtils();
  480. $aModules = $oModuleQuery->getModulesBy(['type' => 'modules']);
  481. foreach($aModules as $aModule)
  482. if(($iModuleSubtypes = $oInstallerUtils->getSubtypes($aModule['name'])) != 0)
  483. $oModuleQuery->updateModule(['subtypes' => $iModuleSubtypes], ['id' => $aModule['id']]);
  484. }
  485. $iSubtypes = 0;
  486. switch($sType) {
  487. case 'content':
  488. $iSubtypes = BX_DOL_MODULE_SUBTYPE_TEXT;
  489. break;
  490. case 'context':
  491. $iSubtypes = BX_DOL_MODULE_SUBTYPE_CONTEXT;
  492. break;
  493. case 'profile':
  494. $iSubtypes = BX_DOL_MODULE_SUBTYPE_PROFILE;
  495. break;
  496. }
  497. $aResults = $oModuleQuery->getModulesBy(array_merge([
  498. 'type' => 'modules_subtypes',
  499. 'value' => $iSubtypes,
  500. 'active' => 1
  501. ], array_intersect_key($aParams, array_flip(['id_as_key', 'name_as_key']))));
  502. return $aResults;
  503. }
  504. public function serviceGetModulesBySubtypeSimple($sType)
  505. {
  506. $a = $this->serviceGetModulesByType($sType, ['name_as_key' => true]);
  507. return array_map(function ($r) {
  508. return $r['title'];
  509. }, $a);
  510. }
  511. public function serviceProfileUnit ($iContentId, $aParams = array())
  512. {
  513. return $this->_serviceProfileFunc('getUnit', $iContentId, $aParams);
  514. }
  515. public function serviceProfileUnitApi ($iContentId, $aParams = [])
  516. {
  517. return $this->_serviceProfileFunc('getUnitApi', $iContentId, $aParams);
  518. }
  519. public function serviceHasImage ($iContentId)
  520. {
  521. return false;
  522. }
  523. public function serviceProfilePicture ($iContentId)
  524. {
  525. return $this->_serviceProfileFunc('getPicture', $iContentId);
  526. }
  527. public function serviceProfileAvatar ($iContentId)
  528. {
  529. return $this->_serviceProfileFunc('getAvatar', $iContentId);
  530. }
  531. public function serviceProfileAvatarBig ($iContentId)
  532. {
  533. return $this->_serviceProfileFunc('getAvatarBig', $iContentId);
  534. }
  535. public function serviceProfileCover ($iContentId)
  536. {
  537. return '';
  538. }
  539. public function serviceProfileEditUrl ($iContentId)
  540. {
  541. return bx_absolute_url(BxDolPermalinks::getInstance()->permalink('page.php?i=account-settings-info'));
  542. }
  543. public function serviceProfileThumb ($iContentId)
  544. {
  545. return $this->_serviceProfileFunc('getThumb', $iContentId);
  546. }
  547. public function serviceProfileIcon ($iContentId)
  548. {
  549. return $this->_serviceProfileFunc('getIcon', $iContentId);
  550. }
  551. public function serviceProfileName ($iContentId)
  552. {
  553. return $this->_serviceProfileFunc('getDisplayName', $iContentId);
  554. }
  555. public function serviceProfileUrl ($iContentId)
  556. {
  557. return $this->_serviceProfileFunc('getUrl', $iContentId);
  558. }
  559. /**
  560. * @see iBxDolProfileService::serviceCheckAllowedProfileView
  561. */
  562. public function serviceCheckAllowedProfileView($iContentId)
  563. {
  564. return _t('_Access denied');
  565. }
  566. /**
  567. * @see iBxDolProfileService::serviceCheckAllowedProfileContact
  568. */
  569. public function serviceCheckAllowedProfileContact($iContentId)
  570. {
  571. return _t('_Access denied');
  572. }
  573. /**
  574. * @see iBxDolProfileService::serviceCheckAllowedPostInProfile
  575. */
  576. public function serviceCheckAllowedPostInProfile($iContentId, $sPostModule = '')
  577. {
  578. return _t('_Access denied');
  579. }
  580. /**
  581. * @see iBxDolProfileService::serviceCheckAllowedModuleActionInProfile
  582. */
  583. public function serviceCheckAllowedModuleActionInProfile($iContentId, $sPostModule, $sActionName)
  584. {
  585. return _t('_Access denied');
  586. }
  587. /**
  588. * @see iBxDolProfileService::serviceGetSpaceTitle
  589. */
  590. public function serviceGetSpaceTitle()
  591. {
  592. return '';
  593. }
  594. /**
  595. * @see iBxDolProfileService::serviceGetParticipatingProfiles
  596. */
  597. public function serviceGetParticipatingProfiles($iProfileId, $aConnectionObject = false)
  598. {
  599. return array();
  600. }
  601. /**
  602. * @page service Service Calls
  603. * @section bx_system_general System Services
  604. * @subsection bx_system_general-general General
  605. * @subsubsection bx_system_general-get_create_post_form get_create_post_form
  606. *
  607. * @code bx_srv('system', 'get_create_post_form', [false, "bx_posts"], 'TemplServices'); @endcode
  608. * @code {{~system:get_create_post_form:TemplServices[false,"bx_posts"]~}} @endcode
  609. *
  610. * Get United Create Post form.
  611. * @param $mixedContextId - context which the post will be created in:
  612. * - false = 'Public' post form;
  613. * - 0 = 'Profile' post form, which allows to post in your own profile and connections;
  614. * - n = 'Context' post form, which allows to post in context (3d party profile, group, event, etc).
  615. * @param $sDefault - tab selected by default.
  616. * @param $aCustom - an array with custom paramaters.
  617. * @return string with form content
  618. *
  619. * @see BxBaseServices::serviceGetCreatePostForm
  620. */
  621. /**
  622. * @ref bx_system_general-get_create_post_form "get_create_post_form"
  623. */
  624. public function serviceGetCreatePostForm($mixedContextId = false, $sDefault = '', $aCustom = array())
  625. {
  626. if(!isLogged() || ($mixedContextId !== false && !is_numeric($mixedContextId)))
  627. return '';
  628. $oProfile = BxDolProfile::getInstance();
  629. if(!$oProfile)
  630. return '';
  631. if($mixedContextId !== false)
  632. $mixedContextId = (int)(!empty($mixedContextId) ? -$mixedContextId : $oProfile->id());
  633. $oMenu = BxDolMenu::getObjectInstance('sys_create_post');
  634. if(!$oMenu)
  635. return '';
  636. $oMenu->setContextId($mixedContextId);
  637. $aMenuItems = $oMenu->getMenuItems();
  638. if(empty($aMenuItems) || !is_array($aMenuItems))
  639. return '';
  640. if(empty($sDefault)) {
  641. $aDefault = array_shift($aMenuItems);
  642. $sDefault = !empty($aDefault['module']) ? $aDefault['module'] : $aDefault['name'];
  643. }
  644. $oMenu->setSelected($sDefault, $sDefault);
  645. $oContext = false;
  646. $bContext = $mixedContextId !== false;
  647. if($bContext && ($oContext = BxDolProfile::getInstance(abs($mixedContextId))) !== false)
  648. if(bx_srv($oContext->getModule(), 'check_allowed_post_in_profile', [$oContext->getContentId(), $sDefault]) !== CHECK_ACTION_RESULT_ALLOWED)
  649. return '';
  650. $sTitle = '_sys_page_block_title_create_post';
  651. if(!$bContext)
  652. $sTitle = _t($sTitle . '_public');
  653. else if($mixedContextId < 0) {
  654. $sTitle = _t($sTitle . '_context');
  655. if($oContext)
  656. $sTitle = bx_replace_markers($sTitle, [
  657. 'display_name' => $oContext->getDisplayName()
  658. ]);
  659. }
  660. else
  661. $sTitle = _t($sTitle);
  662. $sPlaceholder = _t('_sys_txt_create_post_placeholder', $oProfile->getDisplayName());
  663. $oDbModules = BxDolModuleQuery::getInstance();
  664. $oTemplate = BxDolTemplate::getInstance();
  665. $oTemplate->addJs(['BxDolCreatePost.js']);
  666. $aPreloadingList = [];
  667. $aModules = explode(',', getParam('sys_create_post_form_preloading_list'));
  668. if(!empty($aModules))
  669. foreach($aModules as $sModule) {
  670. $aModule = $oDbModules->getModuleByName($sModule);
  671. if(empty($aModule) || !is_array($aModule))
  672. continue;
  673. $aPreloadingList[$sModule] = $aModule['uri'];
  674. }
  675. if(bx_is_api()) {
  676. return [
  677. 'title' => $sTitle,
  678. 'content' => [
  679. bx_api_get_block('get_create_post_form', [
  680. 'menu' => $oMenu->getCodeAPI(),
  681. 'params' => ['context_id' => $mixedContextId]])
  682. ]
  683. ];
  684. }
  685. $sJsObject = 'oBxDolCreatePost';
  686. $sJsContent = $oTemplate->_wrapInTagJsCode("var " . $sJsObject . " = new BxDolCreatePost(" . json_encode([
  687. 'sObjName' => $sJsObject,
  688. 'sRootUrl' => BX_DOL_URL_ROOT,
  689. 'sDefault' => $sDefault,
  690. 'iContextId' => $bContext ? $mixedContextId : 0,
  691. 'oPreloadingList' => $aPreloadingList,
  692. 'oCustom' => $aCustom
  693. ]) . ");");
  694. return [
  695. 'title' => $sTitle,
  696. 'content' => $oTemplate->parseHtmlByName('create_post_form.html', [
  697. 'default' => $sDefault,
  698. 'placeholder' => $sPlaceholder,
  699. 'user_thumb' => $oProfile->getUnit(0, ['template' => 'unit_wo_info_links']),
  700. 'form' => bx_srv($sDefault, 'get_create_post_form', [[
  701. 'context_id' => $mixedContextId,
  702. 'ajax_mode' => true,
  703. 'absolute_action_url' => true,
  704. 'custom' => $aCustom
  705. ]]),
  706. 'js_object' => $sJsObject,
  707. 'js_content' => $sJsContent
  708. ]),
  709. 'menu' => $oMenu->getMenuItemsCount() > 1 ? $oMenu : ''
  710. ];
  711. }
  712. public function serviceGetOptionsCreatePostFormPreloadingList()
  713. {
  714. $oMenu = BxDolMenu::getObjectInstance('sys_create_post');
  715. if(!$oMenu)
  716. return [];
  717. $aMenuItems = $oMenu->getMenuItems();
  718. $aResult = [];
  719. foreach($aMenuItems as $aMenuItem) {
  720. $sModule = !empty($aMenuItem['module']) ? $aMenuItem['module'] : $aMenuItem['name'];
  721. if(!bx_srv('system', 'is_module_enabled', [$sModule]))
  722. continue;
  723. $aResult[] = [
  724. 'key' => $sModule,
  725. 'value' => _t('_' . $sModule)
  726. ];
  727. }
  728. return $aResult;
  729. }
  730. public function serviceGetBlockStatic($sBlockName)
  731. {
  732. $bIsApi = bx_is_api();
  733. if(!$bIsApi)
  734. return '';
  735. return [bx_api_get_block('static', [
  736. 'element' => $sBlockName
  737. ])];
  738. }
  739. public function serviceGetBlockAuthor($sModule, $iContentId = 0)
  740. {
  741. if(!$iContentId && bx_get('id') !== false)
  742. $iContentId = (int)bx_get('id');
  743. $sMethodGetAuthor = 'get_author';
  744. if(!$sModule || !$iContentId || !BxDolRequest::serviceExists($sModule, $sMethodGetAuthor))
  745. return '';
  746. $iAuthor = bx_srv($sModule, $sMethodGetAuthor, [$iContentId]);
  747. if(!$iAuthor)
  748. return '';
  749. $oAuthor = BxDolProfile::getInstance($iAuthor);
  750. if(!$oAuthor)
  751. return '';
  752. $sModuleAuthor = $oAuthor->getModule();
  753. $sMethodGetCover = 'entity_cover';
  754. if(!BxDolRequest::serviceExists($sModuleAuthor, $sMethodGetCover))
  755. return '';
  756. return bx_srv($sModuleAuthor, $sMethodGetCover, [$oAuthor->getContentId(), [
  757. 'use_as_author' => true,
  758. 'show_text' => false
  759. ]]);
  760. }
  761. /**
  762. * AI agent chat block.
  763. *
  764. * Studio / `bx_srv('system', 'get_block_ai_agent', [...], 'TemplServices')`:
  765. *
  766. * array (
  767. * 'module' => 'system',
  768. * 'method' => 'get_block_ai_agent',
  769. * 'params' =>
  770. * array (
  771. * 0 => 6, // agent id
  772. * 1 => array (
  773. * 'context' => false, // profile id, or false = resolve from the page
  774. * 'require_post' => false, // only accept a page/post as context
  775. * 'allow_images' => true, // composer image attachments
  776. * 'allow_new' => false, // "Start new" extra threads (`?chat=`)
  777. * 'show_history' => false, // "Chats" panel with the viewer's earlier threads (App only; operator block turns it on)
  778. * ),
  779. * ),
  780. * 'class' => 'TemplServices',
  781. * )
  782. *
  783. * Legacy positional params still work: (id, context, require_post, allow_images, allow_new, show_history).
  784. *
  785. * @param int $iId Agent id
  786. * @param array|int|false $aParams Named options (preferred) or legacy context pid
  787. */
  788. public function serviceGetBlockAiAgent($iId = 0, $aParams = [], ...$aLegacy)
  789. {
  790. $bIsApi = bx_is_api();
  791. $aAgent = BxDolAiQuery::getAgentObject($iId);
  792. if(!$aAgent || !is_array($aAgent))
  793. return $bIsApi ? [] : '';
  794. $aParams = $this->_normalizeAiAgentBlockParams($aParams, $aLegacy);
  795. $mixedContextPid = $aParams['context'];
  796. $bRequirePost = $aParams['require_post'];
  797. $oAi = BxDolAi::getInstance();
  798. $oChat = BxDolAiChat::getInstance();
  799. if ($mixedContextPid === false || $mixedContextPid === null || $mixedContextPid === '')
  800. $iContextPid = $oAi ? (int)$oChat->resolveChatHistoryContextPidFromPage($bRequirePost) : 0;
  801. else
  802. $iContextPid = $oAi ? $oChat->filterContextPid((int)$mixedContextPid, $bRequirePost) : 0;
  803. if ($bIsApi)
  804. return [bx_api_get_block('ai_agent', [
  805. 'agent_id' => $iId,
  806. 'agent_profile' => BxDolProfile::getData($aAgent['profile_id']),
  807. 'context_profile_id' => $iContextPid,
  808. 'hidden_first_message' => (string)($aAgent['hidden_first_message'] ?? ''),
  809. 'allow_images' => $aParams['allow_images'] ? 1 : 0,
  810. 'allow_new' => $aParams['allow_new'] ? 1 : 0,
  811. 'show_history' => $aParams['show_history'] ? 1 : 0,
  812. 'max_images' => BxDolAiChatImages::MAX_PER_TURN,
  813. 'max_input_chars' => (int)($aAgent['max_input_chars'] ?? 0),
  814. ])];
  815. $sEndpoint = BX_DOL_URL_ROOT . 'sys-ai-chat/' . (int)$iId;
  816. if ($iContextPid > 0)
  817. $sEndpoint .= '&context=' . $iContextPid;
  818. $oTemplate = BxDolTemplate::getInstance();
  819. $oTemplate->addJs([BX_DOL_URL_ROOT . 'plugins_public/bundle.js']);
  820. return $oTemplate->parseHtmlByName('agent_ai_chat.html', [
  821. 'id' => (int)$iId,
  822. 'context_profile_id' => (int)$iContextPid,
  823. 'endpoint_js' => json_encode($sEndpoint),
  824. 'bundle_url' => BX_DOL_URL_ROOT . 'plugins_public/bundle.js',
  825. ]);
  826. }
  827. /**
  828. * Operator AI agent block: the single definition of "which agent, with which
  829. * settings" for site operators. The Dashboard page block and the App floating
  830. * bubble both call this service with no params, so they can never diverge.
  831. *
  832. * Agent id comes from Studio > Settings > Agents (`sys_agents_operator_agent`).
  833. * Block params are fixed here — change them here, and only here. This is the one
  834. * block with the "Chats" history panel (`show_history`): operators come back to
  835. * the same agent again and again, and need to find what it did last time.
  836. *
  837. * Studio: `{"module":"system","method":"get_block_ai_agent_operator","class":"TemplServices"}`
  838. * API: `api.php?r=system/get_block_ai_agent_operator/TemplServices`
  839. */
  840. public function serviceGetBlockAiAgentOperator()
  841. {
  842. $bIsApi = bx_is_api();
  843. $iId = (int)getParam('sys_agents_operator_agent');
  844. if ($iId <= 0)
  845. return $bIsApi ? [] : '';
  846. $aAgent = BxDolAiQuery::getAgentObject($iId);
  847. $oAi = BxDolAi::getInstance();
  848. if (!$aAgent || !is_array($aAgent) || !$oAi || !$oAi->canChatDirectly($aAgent))
  849. return $bIsApi ? [] : '';
  850. return $this->serviceGetBlockAiAgent($iId, [
  851. 'context' => false,
  852. 'require_post' => false,
  853. 'allow_images' => true,
  854. 'allow_new' => true,
  855. 'show_history' => true,
  856. ]);
  857. }
  858. /**
  859. * Studio > Settings select for `sys_agents_operator_agent`: active agents
  860. * that can be chatted with directly (see BxDolAi::canChatDirectly).
  861. */
  862. public function serviceGetOptionsOperatorAgent()
  863. {
  864. $aResult = [
  865. ['key' => '', 'value' => _t('_Select_one')],
  866. ];
  867. $aAgents = BxDolDb::getInstance()->getAll("SELECT `id`, `name` FROM `sys_agents_agents` WHERE `active` = 1 AND `trigger` IN ('manual', 'message') ORDER BY `name` ASC");
  868. foreach ($aAgents as $aAgent) {
  869. $aResult[] = [
  870. 'key' => (int)$aAgent['id'],
  871. 'value' => $aAgent['name'] . ' (#' . (int)$aAgent['id'] . ')',
  872. ];
  873. }
  874. return $aResult;
  875. }
  876. /**
  877. * Named options for {@see serviceGetBlockAiAgent}, plus legacy positional args.
  878. *
  879. * @return array{context:mixed,require_post:bool,allow_images:bool,allow_new:bool,show_history:bool}
  880. */
  881. protected function _normalizeAiAgentBlockParams($mixedParams, array $aLegacy = [])
  882. {
  883. $isOn = function ($v) {
  884. return $v === true || $v === 1 || $v === '1' || $v === 'true' || $v === 'on' || $v === 'yes';
  885. };
  886. $aOut = [
  887. 'context' => false,
  888. 'require_post' => false,
  889. 'allow_images' => false,
  890. 'allow_new' => false,
  891. 'show_history' => false,
  892. ];
  893. $aNamedKeys = ['context', 'context_profile_id', 'require_post', 'allow_images', 'allow_new', 'show_history'];
  894. $bNamed = is_array($mixedParams);
  895. if ($bNamed && $mixedParams) {
  896. $bNamed = false;
  897. foreach ($aNamedKeys as $sKey) {
  898. if (array_key_exists($sKey, $mixedParams)) {
  899. $bNamed = true;
  900. break;
  901. }
  902. }
  903. }
  904. if ($bNamed) {
  905. if (array_key_exists('context', $mixedParams))
  906. $aOut['context'] = $mixedParams['context'];
  907. elseif (array_key_exists('context_profile_id', $mixedParams))
  908. $aOut['context'] = $mixedParams['context_profile_id'];
  909. if (array_key_exists('require_post', $mixedParams))
  910. $aOut['require_post'] = $mixedParams['require_post'];
  911. if (array_key_exists('allow_images', $mixedParams))
  912. $aOut['allow_images'] = $mixedParams['allow_images'];
  913. if (array_key_exists('allow_new', $mixedParams))
  914. $aOut['allow_new'] = $mixedParams['allow_new'];
  915. if (array_key_exists('show_history', $mixedParams))
  916. $aOut['show_history'] = $mixedParams['show_history'];
  917. } else {
  918. $aOut['context'] = $mixedParams;
  919. if (array_key_exists(0, $aLegacy))
  920. $aOut['require_post'] = $aLegacy[0];
  921. if (array_key_exists(1, $aLegacy))
  922. $aOut['allow_images'] = $aLegacy[1];
  923. if (array_key_exists(2, $aLegacy))
  924. $aOut['allow_new'] = $aLegacy[2];
  925. if (array_key_exists(3, $aLegacy))
  926. $aOut['show_history'] = $aLegacy[3];
  927. }
  928. $aOut['require_post'] = $isOn($aOut['require_post']);
  929. $aOut['allow_images'] = $isOn($aOut['allow_images']);
  930. $aOut['allow_new'] = $isOn($aOut['allow_new']);
  931. $aOut['show_history'] = $isOn($aOut['show_history']);
  932. return $aOut;
  933. }
  934. public function serviceGetMenu($aParams)
  935. {
  936. $bIsApi = bx_is_api();
  937. $mixedResulEmpty = $bIsApi ? [] : '';
  938. if($bIsApi && is_string($aParams))
  939. $aParams = bx_api_get_browse_params($aParams);
  940. if(!isset($aParams['object']))
  941. return $mixedResulEmpty;
  942. $oMenu = BxDolMenu::getObjectInstance($aParams['object']);
  943. if(!$oMenu)
  944. return $mixedResulEmpty;
  945. if(!empty($aParams['params']) && is_array($aParams['params']))
  946. $oMenu->setContentParams($aParams['params']);
  947. return $bIsApi ? $oMenu->getCodeAPI() : $oMenu->getCode();
  948. }
  949. /**
  950. * @page service Service Calls
  951. * @section bx_system_general System Services
  952. * @subsection bx_system_general-general General
  953. * @subsubsection bx_system_general-get_site_submenu get_site_submenu
  954. *
  955. * @code bx_srv('system', 'get_site_submenu', [], 'TemplServices'); @endcode
  956. * @code {{~system:get_site_submenu:TemplServices[]~}} @endcode
  957. *
  958. * Get Site Submenu code.
  959. * @see BxBaseServices::serviceGetSiteSubmenu
  960. */
  961. /**
  962. * @ref bx_system_general-get_site_submenu "get_site_submenu"
  963. */
  964. public function serviceGetSiteSubmenu()
  965. {
  966. $oMenu = BxDolMenu::getObjectInstance('sys_site_submenu');
  967. return $oMenu ? $oMenu->getCode() : '';
  968. }
  969. /**
  970. * @page service Service Calls
  971. * @section bx_system_general System Services
  972. * @subsection bx_system_general-general General
  973. * @subsubsection bx_system_general-get_products_names get_products_names
  974. *
  975. * @code bx_srv('system', 'get_products_names', [], 'TemplServices');
  976. *
  977. * @code http://example.com/m/oauth2/com/get_products_names?module=system&class=BaseServices @endcode
  978. * @code http://hihi.una.io/modules/?r=oauth2/com/get_products_names&module=system&class=BaseServices @endcode
  979. *
  980. * Get an array of products names from all modules with payments functionality.
  981. * @param $iVendorId filter products by vendor ID.
  982. * @param $iLimit limit number of records from one module.
  983. * @return array of products where key id product name and value is module name
  984. *
  985. * @see BxBaseServices::serviceGetProductsNames
  986. */
  987. /**
  988. * @ref bx_system_general-get_products_names "get_products_names"
  989. */
  990. public function serviceGetProductsNames($iVendorId = 0, $iLimit = 1000)
  991. {
  992. $o = BxDolPayments::getInstance();
  993. if (!$o)
  994. return array();
  995. return $o->getProductsNames($iVendorId, $iLimit);
  996. }
  997. /**
  998. * @see iBxDolProfileService::serviceCheckSpacePrivacy
  999. */
  1000. public function serviceCheckSpacePrivacy($iContentId)
  1001. {
  1002. return _t('_Access denied');
  1003. }
  1004. public function serviceFormsHelper ()
  1005. {
  1006. return new BxTemplAccountForms();
  1007. }
  1008. public function serviceActAsProfile ()
  1009. {
  1010. return false;
  1011. }
  1012. public function serviceGetModerators($iContentId)
  1013. {
  1014. $aModerators = BxDolAclQuery::getInstance()->getProfilesByMembership([
  1015. MEMBERSHIP_ID_MODERATOR,
  1016. MEMBERSHIP_ID_ADMINISTRATOR
  1017. ]);
  1018. $aIds = [];
  1019. array_walk($aModerators, function ($aItem, $iKey, $aParams) {
  1020. if(!empty($aItem['id']))
  1021. $aParams[0][] = (int)$aItem['id'];
  1022. }, [&$aIds]);
  1023. return $aIds;
  1024. }
  1025. public function servicePrepareFields ($aFieldsProfile)
  1026. {
  1027. return $aFieldsProfile;
  1028. }
  1029. public function serviceProfilesSearch ($sTerm, $iLimit)
  1030. {
  1031. $oDb = BxDolAccountQuery::getInstance();
  1032. $aRet = array();
  1033. $a = $oDb->searchByTerm($sTerm, $iLimit);
  1034. foreach ($a as $r)
  1035. $aRet[] = array ('label' => $this->serviceProfileName($r['content_id']), 'value' => $r['profile_id']);
  1036. return $aRet;
  1037. }
  1038. /**
  1039. * @page service Service Calls
  1040. * @section bx_system_general System Services
  1041. * @subsection bx_system_general-general General
  1042. * @subsubsection bx_system_general-keyword_search keyword_search
  1043. *
  1044. * @code bx_srv('system', 'keyword_search', ["bx_posts", ["keyword" => "test"}], 'TemplServices'); @endcode
  1045. *
  1046. * @code {{~system:keyword_search:TemplServices["bx_posts", {"keyword":"test"}]~}} @endcode
  1047. * @code {{~system:keyword_search:TemplServices["bx_albums", {"meta_type": "location_country", "keyword": "AU"}, "unit.html"]~}} @endcode
  1048. * @code {{~system:keyword_search:TemplServices["bx_albums", {"meta_type": "location_country_state", "state":"NSW", "keyword": "AU"}, "unit.html"]~}} @endcode
  1049. * @code {{~system:keyword_search:TemplServices["bx_albums", {"meta_type": "location_country_city", "state":"NSW", "city":"Manly", "keyword": "AU"}, "unit.html"]~}} @endcode
  1050. * @code {{~system:keyword_search:TemplServices["bx_posts", {"meta_type": "mention", "keyword": 2}, "unit_gallery.html"]~}} @endcode
  1051. * @code {{~system:keyword_search:TemplServices["bx_posts", {"cat": "bx_posts_cats", "keyword": 3}, "unit_gallery.html"]~}} @endcode
  1052. *
  1053. * Search by keyword
  1054. * @param $sSection - search object to search in, usually module name, for example: bx_posts
  1055. * @param $aCondition - condition for search, supported conditions:
  1056. * - search by keyword: ["keyword" => "test"]
  1057. * - search by country: ["meta_type" => "location_country", "keyword" => "AU"]
  1058. * - search by country and state: ["meta_type": "location_country_state", "state":"NSW", "keyword": "AU"]
  1059. * - search by country, state and city: ["meta_type": "location_country_city", "state":"NSW", "city":"Manly", "keyword": "AU"]
  1060. * - search for mentions: ["meta_type" => "mention", "keyword" => 2]
  1061. * - search in category: ["cat": "bx_posts_cats", "keyword": 3]
  1062. * @param $sTemplate - template for displaying search results, for example: unit.html
  1063. * @param $iStart - paginate, display records starting from this number
  1064. * @param $iPerPage - paginate, display this number of records per page
  1065. * @param $bLiveSearch - search results like in live search
  1066. *
  1067. * @see BxBaseServices::serviceKeywordSearch
  1068. */
  1069. /**
  1070. * @ref bx_system_general-keyword_search "keyword_search"
  1071. */
  1072. public function serviceKeywordSearch ($sSection, $aCondition, $sTemplate = '', $iStart = 0, $iPerPage = 0, $bLiveSearch = 0, $bPaginate = false)
  1073. {
  1074. if (!$sSection || !isset($aCondition['keyword']))
  1075. return '';
  1076. $sClass = 'BxTemplSearch';
  1077. $sElsName = 'bx_elasticsearch';
  1078. $sElsMethod = 'is_configured';
  1079. if(BxDolRequest::serviceExists($sElsName, $sElsMethod) && BxDolService::call($sElsName, $sElsMethod)) {
  1080. $oModule = BxDolModule::getInstance($sElsName);
  1081. bx_import('Search', $oModule->_aModule);
  1082. $sClass = 'BxElsSearch';
  1083. }
  1084. $oSearch = new $sClass(array($sSection));
  1085. $oSearch->setLiveSearch($bLiveSearch);
  1086. $oSearch->setMetaType(isset($aCondition['meta_type']) ? $aCondition['meta_type'] : '');
  1087. $oSearch->setCategoryObject(isset($aCondition['cat']) ? $aCondition['cat'] : '');
  1088. $oSearch->setCustomSearchCondition($aCondition);
  1089. if (!$bPaginate)
  1090. $oSearch->setRawProcessing(true);
  1091. $oSearch->setCustomCurrentCondition(array(
  1092. 'paginate' => array (
  1093. 'start' => $iStart,
  1094. 'perPage' => $iPerPage ? $iPerPage : BX_DOL_SEARCH_RESULTS_PER_PAGE_DEFAULT,
  1095. )));
  1096. if ($sTemplate)
  1097. $oSearch->setUnitTemplate($sTemplate);
  1098. return $oSearch->response();
  1099. }
  1100. /**
  1101. * @page service Service Calls
  1102. * @section bx_system_general System Services
  1103. * @subsection bx_system_general-general General
  1104. * @subsubsection bx_system_general-keyword_search keyword_search
  1105. *
  1106. * @code bx_srv('system', 'search_keyword_form', 'TemplServices'); @endcode
  1107. *
  1108. * Block with Search by Keywords Form
  1109. *
  1110. * @see BxBaseServices::serviceSearchKeywordForm
  1111. */
  1112. /**
  1113. * @ref bx_system_general-keyword_search "keyword_search"
  1114. */
  1115. public function serviceSearchKeywordForm ()
  1116. {
  1117. return $this->_getSearchObject()->getForm(BX_DB_PADDING_DEF, false, true);
  1118. }
  1119. /**
  1120. * @page service Service Calls
  1121. * @section bx_system_general System Services
  1122. * @subsection bx_system_general-general General
  1123. * @subsubsection bx_system_general-keyword_search keyword_search
  1124. *
  1125. * @code bx_srv('system', 'search_keyword_result', 'TemplServices'); @endcode
  1126. *
  1127. * Block with Search by Keywords Results
  1128. *
  1129. * @see BxBaseServices::serviceSearchKeywordResult
  1130. */
  1131. /**
  1132. * @ref bx_system_general-keyword_search "keyword_search"
  1133. */
  1134. public function serviceSearchKeywordResult ()
  1135. {
  1136. $sType = bx_process_input(bx_get('type'));
  1137. $sKeyword = bx_process_input(bx_get('keyword'));
  1138. $bKeyword = $sKeyword !== false;
  1139. if(bx_is_api())
  1140. return $this->serviceGetDataSearchApi(['params' => [
  1141. 'type' => $sType,
  1142. 'keyword' => $sKeyword,
  1143. 'section' => bx_process_input(bx_get('section')),
  1144. 'cat' => bx_process_input(bx_get('cat'))
  1145. ]]);
  1146. $sCode = '';
  1147. if($bKeyword) {
  1148. $oSearch = $this->_getSearchObject();
  1149. if(($sCode = $oSearch->response()))
  1150. $sCode = BxDolTemplate::getInstance()->parseHtmlByName('search_result_block.html', [
  1151. 'html_id' => 'bx-search-results-keyword',
  1152. 'class' => 'bx-search-results-container',
  1153. 'attrs' => '',
  1154. 'content' => $sCode,
  1155. 'bx_if:do_center' => [
  1156. 'condition' => false,
  1157. 'content' => [
  1158. 'html_id' => '',
  1159. 'selector_content' => ''
  1160. ]
  1161. ]
  1162. ]);
  1163. else
  1164. $sCode = $oSearch->getEmptyResult();
  1165. }
  1166. return $sCode;
  1167. }
  1168. /**
  1169. * @ref bx_system_general-get_date_search_api "get_date_search_api"
  1170. * @api @ref bx_system_general-get_date_search_api "get_date_search_api"
  1171. */
  1172. public function serviceGetDataSearchApi ($aParams)
  1173. {
  1174. if(!bx_is_api())
  1175. return false;
  1176. if(is_string($aParams))
  1177. $aParams = bx_api_get_browse_params($aParams);
  1178. $bForceAll = ($aParams['params']['type'] ?? '') == 'keyword';
  1179. $aSectionsAvail = explode(',', getParam('sys_api_search_sections'));
  1180. $aSectionsAll = BxDolDb::getInstance()->fromCache(
  1181. 'sys_global_search_pairs',
  1182. 'getPairs',
  1183. 'SELECT `ObjectName` AS `name`, `Title` AS `title` FROM `sys_objects_search` WHERE `GlobalSearch`=\'1\' ORDER BY `Order` ASC',
  1184. 'name', 'title'
  1185. );
  1186. $aSections = [];
  1187. foreach($aSectionsAll as $sSectionName => $sSectionTitle)
  1188. if(in_array($sSectionName, $aSectionsAvail) || $bForceAll)
  1189. $aSections[$sSectionName] = [
  1190. 'name' => $sSectionName,
  1191. 'title' => _t($sSectionTitle)
  1192. ];
  1193. $aParamsBrowse = array_merge([
  1194. 'keyword' => '',
  1195. 'section' => '',
  1196. 'sections' => array_values($aSections),
  1197. 'start' => 0,
  1198. 'per_page' => 12
  1199. ], !empty($aParams['params']) && is_array($aParams['params']) ? $aParams['params'] : []);
  1200. if(empty($aParamsBrowse['section']))
  1201. $aParamsBrowse['section'] = array_keys($aSections);
  1202. else if(is_string($aParamsBrowse['section']))
  1203. $aParamsBrowse['section'] = explode(',', $aParamsBrowse['section']);
  1204. $sClass = 'BxTemplSearch';
  1205. $sSections = $aParamsBrowse['section'];
  1206. if ($aParamsBrowse['live'] !== true && count($sSections) > 1){
  1207. $aParamsBrowse['section'] = [];
  1208. $aParamsBrowse['sections'] = [];
  1209. $aDataRv = [];
  1210. foreach ($sSections as $sSection) {
  1211. $oSearch = new $sClass($sSection);
  1212. $oSearch->setLiveSearch(true);
  1213. $oSearch->setDataProcessing(true);
  1214. $oSearch->setCustomSearchCondition(['keyword' => $aParamsBrowse['keyword']]);
  1215. $oSearch->setCustomCurrentCondition([
  1216. 'paginate' => [
  1217. 'forceStart' => $aParamsBrowse['start'],
  1218. 'perPage' => $aParamsBrowse['per_page'],
  1219. ]
  1220. ]);
  1221. $aData = $oSearch->response();
  1222. if(count($aData) > $aParamsBrowse['per_page'])
  1223. $aData = array_slice($aData, $aParamsBrowse['start'], $aParamsBrowse['per_page']);
  1224. if (count($aData) > 0) {
  1225. $oSearchResult = $oSearch->getSearchResultObject($sSection);
  1226. $sSectionTitle = $oSearchResult->aCurrent['title'];
  1227. $aParamsBrowse['section'][] = $sSection;
  1228. $aParamsBrowse['sections'][] = ['name' => $sSection, 'title' => $sSectionTitle];
  1229. $aDataRv[] = [
  1230. 'section' => $sSection,
  1231. 'section_name' => $sSectionTitle,
  1232. 'data' => $aData,
  1233. 'is_profile' => bx_srv('system', 'is_module_profile', [$oSearchResult->aCurrent['module_name']])
  1234. ];
  1235. }
  1236. }
  1237. return [bx_api_get_block('search_sections', [
  1238. 'data' => $aDataRv,
  1239. 'params' => $aParamsBrowse
  1240. ])];
  1241. }
  1242. else{
  1243. $oSearch = new $sClass($aParamsBrowse['section']);
  1244. $oSearch->setLiveSearch(true);
  1245. $oSearch->setDataProcessing(true);
  1246. $oSearch->setCustomSearchCondition(['keyword' => $aParamsBrowse['keyword']]);
  1247. $oSearch->setCustomCurrentCondition([
  1248. 'paginate' => [
  1249. 'forceStart' => $aParamsBrowse['start'],
  1250. 'perPage' => $aParamsBrowse['per_page'],
  1251. ]
  1252. ]);
  1253. $aData = $oSearch->response();
  1254. if(count($aData) > $aParamsBrowse['per_page'])
  1255. $aData = array_slice($aData, $aParamsBrowse['start'], $aParamsBrowse['per_page']);
  1256. return [
  1257. bx_api_get_block('browse', [
  1258. 'unit' => 'search-results',
  1259. 'request_url' => '/api.php?r=system/get_data_search_api/TemplServices&params[]=',
  1260. 'params' => $aParamsBrowse,
  1261. 'data' => $aData
  1262. ])
  1263. ];
  1264. }
  1265. }
  1266. /**
  1267. * @page service Service Calls
  1268. * @section bx_system_general System Services
  1269. * @subsection bx_system_general-general General
  1270. * @subsubsection bx_system_general-cmts cmts
  1271. *
  1272. * @code bx_srv('system', 'cmts', ["sys_blocks", 1], 'TemplServices'); @endcode
  1273. *
  1274. * @code {{~system:cmts:TemplServices["sys_blocks", 1]~}} @endcode
  1275. *
  1276. * Comments block
  1277. * @param $sObject - comments object name
  1278. * @param $sId - content id assiciated tith the comments
  1279. *
  1280. * @see BxBaseServices::serviceCmts
  1281. */
  1282. /**
  1283. * @ref bx_system_general-cmts "cmts"
  1284. */
  1285. public function serviceCmts ($sObject, $sId)
  1286. {
  1287. $o = BxDolCmts::getObjectInstance($sObject, $sId);
  1288. if (!$o || !$o->isEnabled())
  1289. return '';
  1290. return $o->getCommentsBlock(array(), array('in_designbox' => false, 'show_empty' => true));
  1291. }
  1292. public function _serviceProfileFunc ($sFunc, $iContentId, $aParams = array())
  1293. {
  1294. if (!$iContentId)
  1295. return false;
  1296. if (!($oAccount = BxDolAccount::getInstance($iContentId)))
  1297. return false;
  1298. return $oAccount->$sFunc(false, $aParams);
  1299. }
  1300. public function serviceAlertResponseProcessInstalled()
  1301. {
  1302. BxDolTranscoderImage::registerHandlersSystem();
  1303. }
  1304. public function serviceAlertResponseProcessStorageChange ($oAlert)
  1305. {
  1306. if ('sys_storage_default' != $oAlert->aExtras['option'])
  1307. return;
  1308. $aStorages = BxDolStorageQuery::getStorageObjects();
  1309. foreach ($aStorages as $r) {
  1310. if (0 == $r['current_size'] && 0 == $r['current_number'] && ($oStorage = BxDolStorage::getObjectInstance($r['object'])))
  1311. $oStorage->changeStorageEngine($oAlert->aExtras['value']);
  1312. }
  1313. }
  1314. public function serviceGetOptionsProfileBot()
  1315. {
  1316. $aResult = array(
  1317. array('key' => '', 'value' => _t('_Select_one'))
  1318. );
  1319. $aAccountsIds = BxDolAccountQuery::getInstance()->getOperators();
  1320. foreach($aAccountsIds as $iAccountId) {
  1321. $aProfilesIds = BxDolAccount::getInstance($iAccountId)->getProfilesIds(true, false);
  1322. foreach($aProfilesIds as $iProfileId) {
  1323. $oProfile = BxDolProfile::getInstance($iProfileId);
  1324. $aResult[] = array(
  1325. 'key' => $iProfileId,
  1326. 'value' => _t('_sys_profile_with_type', $oProfile->getDisplayName(), $oProfile->getModule()),
  1327. );
  1328. }
  1329. }
  1330. return $aResult;
  1331. }
  1332. public function serviceGetOptionsModuleListForPrivacySelector()
  1333. {
  1334. $aResult = array();
  1335. $BxDolModuleQuery = BxDolModuleQuery::getInstance();
  1336. $aModules = $BxDolModuleQuery->getModulesBy(array('type' => 'modules', 'active' => 1));
  1337. foreach($aModules as $aModule){
  1338. $oModule = BxDolModule::getInstance($aModule['name']);
  1339. if($oModule instanceof iBxDolContentInfoService){
  1340. if (!BxDolRequest::serviceExists($aModule['name'], 'act_as_profile'))
  1341. continue;
  1342. $aResult[$aModule['name']] = $aModule['title'];
  1343. }
  1344. }
  1345. return $aResult;
  1346. }
  1347. public function serviceGetOptionsCaptchaDefault()
  1348. {
  1349. $aResults = [];
  1350. $aObjects = BxDolCaptchaQuery::getObjects();
  1351. foreach($aObjects as $aObject)
  1352. $aResults[$aObject['object']] = $aObject['title'];
  1353. return $aResults;
  1354. }
  1355. public function serviceGetOptionsEmbedDefault()
  1356. {
  1357. $aResults = array(
  1358. '' => _t('_None')
  1359. );
  1360. $aObjects = BxDolEmbedQuery::getObjects();
  1361. foreach($aObjects as $aObject)
  1362. $aResults[$aObject['object']] = _t($aObject['title']);
  1363. return $aResults;
  1364. }
  1365. public function serviceGetOptionsLocationFieldDefault()
  1366. {
  1367. $aResults = array();
  1368. $aObjects = BxDolLocationFieldQuery::getObjects();
  1369. foreach($aObjects as $aObject)
  1370. $aResults[$aObject['object']] = _t($aObject['title']);
  1371. return $aResults;
  1372. }
  1373. public function serviceGetOptionsLocationMapDefault()
  1374. {
  1375. $aResults = array();
  1376. $aObjects = BxDolLocationMapQuery::getObjects();
  1377. foreach($aObjects as $aObject)
  1378. $aResults[$aObject['object']] = _t($aObject['title']);
  1379. return $aResults;
  1380. }
  1381. public function serviceGetOptionsPushDefault()
  1382. {
  1383. $aResults = [
  1384. '' => _t('_None')
  1385. ];
  1386. $aObjects = BxDolPushQuery::getObjects();
  1387. foreach($aObjects as $aObject)
  1388. $aResults[$aObject['object']] = $aObject['title'];
  1389. return $aResults;
  1390. }
  1391. public function serviceGetOptionsSmsDefault()
  1392. {
  1393. $aResults = [
  1394. '' => _t('_None')
  1395. ];
  1396. $aObjects = BxDolSmsQuery::getObjects();
  1397. foreach($aObjects as $aObject)
  1398. $aResults[$aObject['object']] = $aObject['title'];
  1399. return $aResults;
  1400. }
  1401. public function serviceGetOptionsSocketsFieldDefault()
  1402. {
  1403. $aResults = [];
  1404. $aObjects = ['sys_sockets_disabled', 'sys_sockets_soketi'];
  1405. foreach($aObjects as $sObject)
  1406. $aResults[$sObject] = _t('_adm_stg_cpt_option_sys_sockets_type_' . $sObject);
  1407. return $aResults;
  1408. }
  1409. public function serviceGetOptionsLocationLeafletGetProviders()
  1410. {
  1411. return BxDolLocationMapLeaflet::getProviders();
  1412. }
  1413. public function serviceGetOptionsRelations()
  1414. {
  1415. $aModules = BxDolModuleQuery::getInstance()->getModulesBy(array('type' => 'modules', 'active' => 1));
  1416. $aProfiles = array();
  1417. foreach($aModules as $aModule) {
  1418. $sMethod = 'act_as_profile';
  1419. if(!BxDolRequest::serviceExists($aModule['name'], $sMethod) || !BxDolService::call($aModule['name'], $sMethod))
  1420. continue;
  1421. $aProfiles[$aModule['name']] = _t('_' . $aModule['name']);
  1422. }
  1423. $aResults = array();
  1424. foreach($aProfiles as $sName1 => $sTitle1)
  1425. foreach($aProfiles as $sName2 => $sTitle2)
  1426. $aResults[$sName1 . '_' . $sName2] = $sTitle1 . ' - ' . $sTitle2;
  1427. return $aResults;
  1428. }
  1429. public function serviceGetOptionsCfProhibited()
  1430. {
  1431. return BxDolFormQuery::getDataItems('sys_content_filter');
  1432. }
  1433. public function serviceGetOptionsCfUnauthenticated()
  1434. {
  1435. return BxDolFormQuery::getDataItems('sys_content_filter');
  1436. }
  1437. public function serviceGetOptionsTaiwindDefault()
  1438. {
  1439. $sPath = BX_DIRECTORY_PATH_PLUGINS_PUBLIC . 'tailwind/css';
  1440. $aExcludes = ['.', '..', 'tailwind.css'];
  1441. $aResults = [];
  1442. if(($oHandle = opendir($sPath)) !== false) {
  1443. while(($sFile = readdir($oHandle)) !== false) {
  1444. if(in_array($sFile, $aExcludes))
  1445. continue;
  1446. if(($oHandlerFile = fopen($sPath . '/' . $sFile, 'r')) === false)
  1447. continue;
  1448. if(($sContent = fread($oHandlerFile, 1024)) !== false && strpos($sContent, '@tailwind base') === false)
  1449. $aResults[$sFile] = $sFile;
  1450. fclose($oHandlerFile);
  1451. }
  1452. closedir($oHandle);
  1453. }
  1454. /**
  1455. * Disabled for now, because CDN and custom compiled build with own styles
  1456. * don't work correctly together.
  1457. *
  1458. * $aResults['cdn'] = _t('_adm_stg_cpt_option_sys_css_tailwind_default_cdn');
  1459. */
  1460. return $aResults;
  1461. }
  1462. public function serviceGetOptionsIconsetDefault()
  1463. {
  1464. $aObjects = BxDolIconsetQuery::getObjects();
  1465. foreach($aObjects as $aObject)
  1466. $aResults[$aObject['object']] = $aObject['title'];
  1467. return $aResults;
  1468. }
  1469. public function serviceGetOptionsApiRootPageGuest()
  1470. {
  1471. $sKey = '_adm_stg_cpt_option_sys_api_root_page_';
  1472. return [
  1473. 'home' => _t($sKey .'home'),
  1474. 'splash' => _t($sKey . 'splash')
  1475. ];
  1476. }
  1477. public function serviceGetOptionsApiRootPageMember()
  1478. {
  1479. $sKey = '_adm_stg_cpt_option_sys_api_root_page_';
  1480. return [
  1481. 'home' => _t($sKey .'home'),
  1482. 'dashboard' => _t($sKey . 'dashboard'),
  1483. 'profile' => _t($sKey . 'profile')
  1484. ];
  1485. }
  1486. public function serviceGetOptionsApiMenuTop()
  1487. {
  1488. $aMenus = BxDolMenuQuery::getMenuObjects();
  1489. $aResults = ['' => _t('_sys_please_select')];
  1490. foreach($aMenus as $aMenu)
  1491. if($aMenu['module'] == 'system')
  1492. $aResults[$aMenu['object']] = _t($aMenu['title']);
  1493. return $aResults;
  1494. }
  1495. public function serviceGetOptionsApiContextSwitcher()
  1496. {
  1497. $aContexts = bx_srv('system', 'get_modules_by_type', ['context']);
  1498. $aResults = ['' => _t('_None')];
  1499. foreach($aContexts as $aContext)
  1500. $aResults[$aContext['name']] = _t('_' . $aContext['name']);
  1501. return $aResults;
  1502. }
  1503. public function serviceGetOptionsApiContextConnection()
  1504. {
  1505. $aConnections = ['subscriptions', 'fans', 'participants'];
  1506. $aResults = ['' => _t('_sys_please_select')];
  1507. foreach($aConnections as $sConnection)
  1508. $aResults[$sConnection] = _t('_adm_stg_cpt_option_sys_api_cnt_cnn_' . $sConnection);
  1509. return $aResults;
  1510. }
  1511. public function serviceGetOptionsAgentsModel()
  1512. {
  1513. return ['' => _t('_Select_one')] + BxDolAi::getInstance()->getModels(['active' => true]);
  1514. }
  1515. public function serviceGetOptionsAgentsProfile($bSelectOne = true, $sSelectOneLangKey = '_Select_one')
  1516. {
  1517. $aResult = [];
  1518. if($bSelectOne)
  1519. $aResult[] = ['key' => '', 'value' => _t($sSelectOneLangKey)];
  1520. $aAccountsIds = BxDolAccountQuery::getInstance()->getOperators();
  1521. foreach($aAccountsIds as $iAccountId) {
  1522. $aProfilesIds = BxDolAccount::getInstance($iAccountId)->getProfilesIds(true, false);
  1523. foreach($aProfilesIds as $iProfileId) {
  1524. $oProfile = BxDolProfile::getInstance($iProfileId);
  1525. $sProfileModule = false === $oProfile ? '' : $oProfile->getModule();
  1526. if ($sProfileModule && ($sProfileModule != 'system' || ($sProfileModule == 'system' && empty($oProfile->getAccountObject()->getEmail())))) {
  1527. $aResult[] = [
  1528. 'key' => $iProfileId,
  1529. 'value' => _t('_sys_profile_with_type', $oProfile->getDisplayName(), $sProfileModule === 'system' ? 'System' : _t('_' . $sProfileModule))
  1530. ];
  1531. }
  1532. }
  1533. }
  1534. return $aResult;
  1535. }
  1536. public function serviceRedirect($sUrl = false)
  1537. {
  1538. if (!getParam('sys_confirmation_before_redirect')) {
  1539. BxDolTemplate::getInstance()->displayPageNotFound();
  1540. exit;
  1541. }
  1542. if (false === $sUrl)
  1543. $sUrl = bx_get('url');
  1544. if (!$sUrl || !preg_match('@^https?://@', $sUrl)) {
  1545. http_response_code(500);
  1546. return MsgBox(_t('_error occured'));
  1547. }
  1548. else {
  1549. $bSpam = null;
  1550. /**
  1551. * @hooks
  1552. * @hookdef hook-system-check_spam_url 'system', 'check_spam_url' - hook to override sClass for search
  1553. * - $unit_name - equals `system`
  1554. * - $action - equals `check_spam_url`
  1555. * - $object_id - not used
  1556. * - $sender_id - logged account id
  1557. * - $extra_params - array of additional params with the following array keys:
  1558. * - `is_spam` - [bool] by ref, spam url or not, can be overridden in hook processing
  1559. * - `content` - [string] by ref, url of link, can be overridden in hook processing
  1560. * - `where` - [string] equal redirect
  1561. * @hook @ref hook-system-check_spam_url
  1562. */
  1563. bx_alert('system', 'check_spam_url', 0, getLoggedId(), array(
  1564. 'is_spam' => &$bSpam,
  1565. 'content' => &$sUrl,
  1566. 'is_spam_ref' => &$bSpam,
  1567. 'content_ref' => &$sUrl,
  1568. 'where' => 'redirect'
  1569. ));
  1570. $sLangKey = $bSpam ? '_sys_redirect_confirmation_harmful' : '_sys_redirect_confirmation';
  1571. return BxDolTemplate::getInstance()->parseHtmlByName('redirect.html', [
  1572. 'text' => _t($sLangKey, bx_process_output($sUrl), getParam('site_title')),
  1573. 'url' => bx_js_string($sUrl, BX_ESCAPE_STR_APOS),
  1574. ]);
  1575. }
  1576. }
  1577. public function serviceSetBadges($iContentId, $sBadgesIds, $sModule)
  1578. {
  1579. $aSelectedBadges = explode(",", $sBadgesIds);
  1580. $iPerformerId = bx_get_logged_profile_id();
  1581. $aCheck = checkActionModule($iPerformerId, 'set badge', 'system', false);
  1582. if(!isAdmin() && $aCheck[CHECK_ACTION_RESULT] !== CHECK_ACTION_RESULT_ALLOWED)
  1583. return false;
  1584. $oBadges = BxDolBadges::getInstance();
  1585. $oBadges->delete([
  1586. 'type' => 'by_module&object',
  1587. 'object_id' => $iContentId,
  1588. 'module' => $sModule
  1589. ]);
  1590. foreach ($aSelectedBadges as $iSelectedBadge)
  1591. $oBadges->add($iSelectedBadge, $iContentId, $sModule);
  1592. checkActionModule($iPerformerId, 'set badge', 'system', true);
  1593. return true;
  1594. }
  1595. public function serviceGetBadge($aBadge, $bIsCompact = false)
  1596. {
  1597. $sClass = '';
  1598. $sStyleFont = '';
  1599. $sStyleBg = '';
  1600. if ($aBadge['color'] == '')
  1601. $aBadge['color'] = 'purple-600';
  1602. if ($bIsCompact && $aBadge['icon'] != ''){
  1603. $aBadge['is_icon_only'] = 1;
  1604. }
  1605. if ($aBadge['is_icon_only'] == 1){
  1606. $sClass .= ' bx-badge-compact';
  1607. if (substr_count($aBadge['color'], 'rgb('))
  1608. $sStyleFont = 'color: ' . $aBadge['color'];
  1609. else
  1610. $sClass .= ' text-' . $aBadge['color'];
  1611. }
  1612. else{
  1613. if (substr_count($aBadge['color'], 'rgb('))
  1614. $sStyleBg = 'background-color: ' . $aBadge['color'];
  1615. else
  1616. $sClass .= ' bg-' . $aBadge['color'];
  1617. }
  1618. return BxDolTemplate::getInstance()->parseHtmlByName('badge.html', array(
  1619. 'bx_if:content' => array(
  1620. 'condition' => $aBadge['is_icon_only'] != '1',
  1621. 'content' => array('content' => _t($aBadge['text'])),
  1622. ),
  1623. 'bx_if:icon' => array(
  1624. 'condition' => $aBadge['icon'] != '',
  1625. 'content' => array('content' => BxDolTemplate::getInstance()->getIcon($aBadge['icon'], array('class' => 'bx-badge-icon sys-colored', 'style' => $sStyleFont))),
  1626. ),
  1627. 'title' => $aBadge['text'],
  1628. 'style_font' => $sStyleFont,
  1629. 'style_bg' => $sStyleBg,
  1630. 'class' => $sClass,
  1631. )
  1632. );
  1633. }
  1634. public function serviceGetFooter()
  1635. {
  1636. return BxDolTemplate::getInstance()->parseHtmlByName('footer.html', []);
  1637. }
  1638. private function _getSearchObject()
  1639. {
  1640. $sClass = 'BxTemplSearch';
  1641. $sElsName = 'bx_elasticsearch';
  1642. $sElsMethod = 'is_configured';
  1643. if(BxDolRequest::serviceExists($sElsName, $sElsMethod) && BxDolService::call($sElsName, $sElsMethod) && !bx_get('cat') && !bx_get('type')) {
  1644. $oModule = BxDolModule::getInstance($sElsName);
  1645. bx_import('Search', $oModule->_aModule);
  1646. $sClass = 'BxElsSearch';
  1647. }
  1648. /**
  1649. * @hooks
  1650. * @hookdef hook-system-search_keyword 'system', 'search_keyword' - hook to override sClass for search
  1651. * - $unit_name - equals `system`
  1652. * - $action - equals `search_keyword`
  1653. * - $object_id - not used
  1654. * - $sender_id - not used
  1655. * - $extra_params - array of additional params with the following array keys:
  1656. * - `override_result` - [string] by ref, class name for search, can be overridden in hook processing
  1657. * @hook @ref hook-system-search_keyword
  1658. */
  1659. bx_alert('system', 'search_keyword', 0, 0, array('class' => &$sClass, 'class_name_ref' => &$sClass));
  1660. $oSearch = new $sClass(bx_get('section'));
  1661. $oSearch->setLiveSearch(bx_get('live_search') ? 1 : 0);
  1662. $oSearch->setMetaType(bx_process_input(bx_get('type')));
  1663. $oSearch->setCategoryObject(bx_process_input(bx_get('cat')));
  1664. return $oSearch;
  1665. }
  1666. public function serviceHomeRedirect()
  1667. {
  1668. header("Location:" . BX_DOL_URL_ROOT, true, 301);
  1669. exit;
  1670. }
  1671. public function serviceProcessEmbed()
  1672. {
  1673. BxDolEmbed::getObjectInstance()->process();
  1674. }
  1675. public function serviceCallAgent($sType, $aAgent, $aParams)
  1676. {
  1677. $oAi = BxDolAi::getInstance();
  1678. $mixedReply = $oAi->callAgent($sType, $aAgent, $aParams);
  1679. // Async messenger agents run here from a background job: post the reply, nobody else will.
  1680. if ('message' === $sType && is_string($mixedReply) && $mixedReply !== '')
  1681. BxDolAiTrigger::getInstance('message')->replyToMessage($aAgent, $aParams, $mixedReply);
  1682. return $mixedReply;
  1683. }
  1684. public function serviceCallAgentForFormInput($iAgentId)
  1685. {
  1686. return BxDolAiTrigger::getInstance('form-input')->handle($iAgentId);
  1687. }
  1688. public function serviceAiChat($iAgentId)
  1689. {
  1690. return BxDolAiTrigger::getInstance('chat')->handle($iAgentId);
  1691. }
  1692. /**
  1693. * Composer image upload for the chat widget (`$_FILES['file']`).
  1694. * → `{file_id, url, mime}` or `{error}`; the client sends the URL back as an image part of its next message.
  1695. */
  1696. public function serviceAiChatUpload($iAgentId)
  1697. {
  1698. return BxDolAiTrigger::getInstance('chat')->upload($iAgentId);
  1699. }
  1700. /**
  1701. * The caller's own conversations with an agent — the "Chats" panel of the App
  1702. * chat widget. Any context, base thread and `?chat=` partitions, newest first.
  1703. *
  1704. * API: `api.php?r=system/get_ai_chat_threads/TemplServices&params[]=<agent id>`
  1705. * → `{threads: [{thread_id, chat, context_pid, context_name, status, closed_reason,
  1706. * title, preview, messages_count, created_ts, updated_ts}]}`.
  1707. * The row whose `chat` / context matches the widget (or the open one, when the
  1708. * widget has no `?chat=`) is the live conversation; the rest are read-only —
  1709. * see serviceGetAiChatThread.
  1710. */
  1711. public function serviceGetAiChatThreads($iAgentId)
  1712. {
  1713. return BxDolAiTrigger::getInstance('chat')->listThreads($iAgentId);
  1714. }
  1715. /**
  1716. * One of the caller's earlier conversations, read-only.
  1717. *
  1718. * API: `api.php?r=system/get_ai_chat_thread/TemplServices&params[]=<agent id>&params[]=<thread id>`
  1719. * → `{messages, status, closed_reason, artifacts}`; 403 for a thread of someone else.
  1720. */
  1721. public function serviceGetAiChatThread($iAgentId, $sThreadId = '')
  1722. {
  1723. return BxDolAiTrigger::getInstance('chat')->getThread($iAgentId, $sThreadId);
  1724. }
  1725. /**
  1726. * a cut-down Studio > Agents for operators:
  1727. * the list with on/off, chat history for manual/message agents and the
  1728. * activity history (what the agent did) for event-driven ones.
  1729. *
  1730. * API: `api.php?r=system/get_ai_agents/TemplServices`
  1731. * → `{agents: [{id, name, title, description, trigger, trigger_title, alert, active, async,
  1732. * has_chat, model, profile: {id, name, url, thumb}, activity_count, activity_last, added}], studio_url}`
  1733. */
  1734. public function serviceGetAiAgents()
  1735. {
  1736. if (!isAdmin())
  1737. return ['error' => _t('_sys_agents_unauthorized'), 'code' => 403];
  1738. $oDb = BxDolDb::getInstance();
  1739. $aRows = $oDb->getAll("SELECT `a`.*, `m`.`title` AS `model_title` FROM `sys_agents_agents` AS `a` LEFT JOIN `sys_agents_models` AS `m` ON `m`.`id` = `a`.`model_id` ORDER BY `a`.`added` DESC, `a`.`id` DESC");
  1740. $aStats = BxDolAiActivity::statsByAgent();
  1741. $aAgents = [];
  1742. foreach ($aRows as $aRow) {
  1743. $iId = (int)$aRow['id'];
  1744. $aAgents[] = [
  1745. 'id' => $iId,
  1746. 'name' => (string)$aRow['name'],
  1747. 'title' => (string)(!empty($aRow['title']) ? $aRow['title'] : $aRow['name']),
  1748. 'description' => (string)($aRow['description'] ?? ''),
  1749. 'trigger' => (string)$aRow['trigger'],
  1750. 'trigger_title' => $this->_aiAgentTriggerTitle((string)$aRow['trigger']),
  1751. 'alert' => (string)($aRow['alert'] ?? ''),
  1752. 'active' => (int)$aRow['active'],
  1753. 'async' => (int)($aRow['async'] ?? 0),
  1754. 'has_chat' => in_array($aRow['trigger'], ['manual', 'message'], true) ? 1 : 0,
  1755. 'model' => (string)($aRow['model_title'] ?? ''),
  1756. 'profile' => $this->_aiAgentProfileInfo((int)$aRow['profile_id']),
  1757. 'activity_count' => (int)($aStats[$iId]['count'] ?? 0),
  1758. 'activity_last' => (int)($aStats[$iId]['last'] ?? 0),
  1759. 'added' => (int)($aRow['added'] ?? 0),
  1760. ];
  1761. }
  1762. return [
  1763. 'agents' => $aAgents,
  1764. 'studio_url' => bx_absolute_url('studio/agents.php?page=agents'),
  1765. ];
  1766. }
  1767. /**
  1768. * Page block with the same list, for operators only (everyone else gets an
  1769. * empty block). Put it on the Dashboard or any page in Studio > Pages:
  1770. * `{"module":"system","method":"get_block_ai_agents_admin","class":"TemplServices"}`.
  1771. * The App renders it as the `ai_agents_admin` element; there is no HTML version.
  1772. */
  1773. public function serviceGetBlockAiAgentsAdmin()
  1774. {
  1775. if (!bx_is_api())
  1776. return '';
  1777. if (!isAdmin())
  1778. return [];
  1779. $aList = $this->serviceGetAiAgents();
  1780. if (!is_array($aList) || isset($aList['error']))
  1781. return [];
  1782. // the operator chat (Studio > Settings > Agents) rides along as the first tab of
  1783. // the same block, so the Dashboard needs one block, not two
  1784. $aList['chat'] = null;
  1785. $aList['chat_title'] = '';
  1786. $iOperator = (int)getParam('sys_agents_operator_agent');
  1787. if ($iOperator > 0) {
  1788. $aOperatorBlock = $this->serviceGetBlockAiAgentOperator();
  1789. if (is_array($aOperatorBlock) && !empty($aOperatorBlock[0]['data']) && is_array($aOperatorBlock[0]['data'])) {
  1790. $aList['chat'] = $aOperatorBlock[0]['data'];
  1791. $aOperator = BxDolAiQuery::getAgentObject($iOperator);
  1792. $aList['chat_title'] = (string)(!empty($aOperator['title']) ? $aOperator['title'] : ($aOperator['name'] ?? ''));
  1793. }
  1794. }
  1795. return [bx_api_get_block('ai_agents_admin', $aList)];
  1796. }
  1797. /**
  1798. * API: `api.php?r=system/set_ai_agent_active/TemplServices&params[]=<agent id>&params[]=<0|1>`
  1799. */
  1800. public function serviceSetAiAgentActive($iAgentId, $iActive = 1)
  1801. {
  1802. if (!isAdmin())
  1803. return ['error' => _t('_sys_agents_unauthorized'), 'code' => 403];
  1804. $iAgentId = (int)$iAgentId;
  1805. $aAgent = $iAgentId ? BxDolAiQuery::getAgentObject($iAgentId) : false;
  1806. if (!$aAgent)
  1807. return ['error' => _t('_sys_agents_agent_not_found'), 'code' => 404];
  1808. $iActive = (int)$iActive ? 1 : 0;
  1809. $oDb = BxDolDb::getInstance();
  1810. $oDb->query("UPDATE `sys_agents_agents` SET `active` = :active WHERE `id` = :id", ['active' => $iActive, 'id' => $iAgentId]);
  1811. $oDb->cleanCache('sys_agents_with_alert');
  1812. $oDb->cleanMemory('sys_agents_with_form_' . (string)($aAgent['form_object'] ?? ''));
  1813. return ['id' => $iAgentId, 'active' => $iActive];
  1814. }
  1815. /**
  1816. * API: `api.php?r=system/get_ai_agent_activity/TemplServices&params[]=<agent id>&params[]=<start>&params[]=<limit>`
  1817. * → `{items: [{id, action, tool, ok, text, summary, unit, object_id, url, added, added_formatted}], has_more}`
  1818. */
  1819. public function serviceGetAiAgentActivity($iAgentId, $iStart = 0, $iLimit = 50)
  1820. {
  1821. if (!isAdmin())
  1822. return ['error' => _t('_sys_agents_unauthorized'), 'code' => 403];
  1823. $iAgentId = (int)$iAgentId;
  1824. if (!$iAgentId || !BxDolAiQuery::getAgentObject($iAgentId))
  1825. return ['error' => _t('_sys_agents_agent_not_found'), 'code' => 404];
  1826. $iLimit = max(1, min(200, (int)$iLimit));
  1827. $aItems = BxDolAiActivity::listForAgent($iAgentId, (int)$iStart, $iLimit + 1);
  1828. $bMore = count($aItems) > $iLimit;
  1829. if ($bMore)
  1830. array_pop($aItems);
  1831. return ['items' => $aItems, 'has_more' => $bMore ? 1 : 0];
  1832. }
  1833. /**
  1834. * Every conversation of an agent (all people, guests, contexts) — operators
  1835. * only; the App counterpart of the Studio chat popup. Transcripts are not
  1836. * included, see serviceGetAiAgentChatThread.
  1837. *
  1838. * API: `api.php?r=system/get_ai_agent_chat_threads/TemplServices&params[]=<agent id>`
  1839. * → `{threads: [{thread_id, title, status, closed_reason, created_at, updated_at, messages_count, preview}]}`
  1840. */
  1841. public function serviceGetAiAgentChatThreads($iAgentId)
  1842. {
  1843. if (!isAdmin())
  1844. return ['error' => _t('_sys_agents_unauthorized'), 'code' => 403];
  1845. $iAgentId = (int)$iAgentId;
  1846. $aAgent = $iAgentId ? BxDolAiQuery::getAgentObject($iAgentId) : false;
  1847. if (!$aAgent)
  1848. return ['error' => _t('_sys_agents_agent_not_found'), 'code' => 404];
  1849. $aThreads = BxDolAiChat::getInstance()->listAgentChatThreads($aAgent);
  1850. $aOut = [];
  1851. foreach ($aThreads as $aThread) {
  1852. $aMessages = is_array($aThread['messages'] ?? null) ? $aThread['messages'] : [];
  1853. if (!$aMessages)
  1854. continue;
  1855. $sPreview = '';
  1856. foreach (array_reverse($aMessages) as $aMessage) {
  1857. foreach ((array)($aMessage['parts'] ?? []) as $aPart) {
  1858. if (($aPart['type'] ?? '') === 'text' && trim((string)($aPart['content'] ?? '')) !== '') {
  1859. $sPreview = trim(strip_tags((string)$aPart['content']));
  1860. break 2;
  1861. }
  1862. }
  1863. }
  1864. if (mb_strlen($sPreview) > 160)
  1865. $sPreview = mb_substr($sPreview, 0, 159) . '…';
  1866. $aOut[] = [
  1867. 'thread_id' => (string)$aThread['thread_id'],
  1868. 'title' => (string)$aThread['title'],
  1869. 'status' => (string)($aThread['status'] ?? 'opened'),
  1870. 'closed_reason' => (string)($aThread['closed_reason'] ?? ''),
  1871. 'created_at' => (string)($aThread['created_at'] ?? ''),
  1872. 'updated_at' => (string)($aThread['updated_at'] ?? ''),
  1873. 'messages_count' => count($aMessages),
  1874. 'preview' => $sPreview,
  1875. ];
  1876. }
  1877. return ['threads' => $aOut];
  1878. }
  1879. /**
  1880. * API: `api.php?r=system/get_ai_agent_chat_thread/TemplServices&params[]=<agent id>&params[]=<thread id>`
  1881. * → `{messages, status, closed_reason, artifacts}` — same message shape as get_ai_chat_thread.
  1882. */
  1883. public function serviceGetAiAgentChatThread($iAgentId, $sThreadId = '')
  1884. {
  1885. if (!isAdmin())
  1886. return ['error' => _t('_sys_agents_unauthorized'), 'code' => 403];
  1887. $iAgentId = (int)$iAgentId;
  1888. $aAgent = $iAgentId ? BxDolAiQuery::getAgentObject($iAgentId) : false;
  1889. if (!$aAgent)
  1890. return ['error' => _t('_sys_agents_agent_not_found'), 'code' => 404];
  1891. $oChat = BxDolAiChat::getInstance();
  1892. $sThreadId = trim((string)$sThreadId);
  1893. if ($sThreadId === '')
  1894. return ['error' => _t('_sys_agents_agent_not_found'), 'code' => 404];
  1895. $aMessages = $oChat->getChatHistoryUiMessagesByThread($aAgent, $sThreadId);
  1896. if ($aMessages === false)
  1897. return ['error' => _t('_sys_agents_agent_not_found'), 'code' => 404];
  1898. $sReason = '';
  1899. $oDb = BxDolDb::getInstance();
  1900. if ($oDb->isFieldExists('sys_agents_chat_history', 'closed_reason'))
  1901. $sReason = trim((string)$oDb->getOne("SELECT `closed_reason` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", ['t' => $sThreadId]));
  1902. return [
  1903. 'messages' => is_array($aMessages) ? $aMessages : [],
  1904. 'status' => $sReason !== '' ? 'closed' : 'opened',
  1905. 'closed_reason' => $sReason,
  1906. 'artifacts' => $oChat->getChatHistoryArtifactsByThread($aAgent, $sThreadId),
  1907. ];
  1908. }
  1909. protected function _aiAgentTriggerTitle($sTrigger)
  1910. {
  1911. $sKey = '_sys_agents_field_trigger_' . str_replace('-', '_', (string)$sTrigger);
  1912. $s = _t($sKey);
  1913. return $s !== $sKey ? $s : (string)$sTrigger;
  1914. }
  1915. protected function _aiAgentProfileInfo($iProfileId)
  1916. {
  1917. $iProfileId = (int)$iProfileId;
  1918. $oProfile = $iProfileId ? BxDolProfile::getInstance($iProfileId) : false;
  1919. if (!$oProfile)
  1920. return ['id' => $iProfileId, 'display_name' => $iProfileId ? '#' . $iProfileId : '', 'url' => false, 'url_avatar' => '', 'module' => ''];
  1921. // same shape as the ai_agent block's agent_profile, so the App's Profile molecule can render it
  1922. return BxDolProfile::getData($oProfile);
  1923. }
  1924. /**
  1925. * Agent-written NEO mockup block (Studio: system / get_mockup_block / TemplServices).
  1926. * The tree is written by the `mockup_upsert` tool into sys_pages_blocks_data for this block;
  1927. * BxBasePage::_getBlockService passes the block id as the only param.
  1928. * @param int $iBlockId sys_pages_blocks.id
  1929. * @return array API block of type `mockup`
  1930. */
  1931. public function serviceGetMockupBlock($iBlockId = 0)
  1932. {
  1933. $aTree = BxDolAIToolMockup::getTree((int)$iBlockId);
  1934. if (!$aTree) {
  1935. $aTree = [
  1936. 'type' => 'view',
  1937. 'className' => 'gap-4 w-full',
  1938. 'children' => [
  1939. [
  1940. 'type' => 'text',
  1941. 'className' => 'text-muted-foreground',
  1942. 'text' => 'No mockup yet. Ask the mockup agent to generate one for this page.',
  1943. ],
  1944. ],
  1945. ];
  1946. }
  1947. return [bx_api_get_block('mockup', $aTree)];
  1948. }
  1949. }
  1950. /** @} */