BxBaseServices.php 75 KB

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