BxBaseServices.php 72 KB

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