| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978 |
- <?php defined('BX_DOL') or die('hack attempt');
- /**
- * Copyright (c) UNA, Inc - https://una.io
- * MIT License - https://opensource.org/licenses/MIT
- *
- * @defgroup UnaBaseView UNA Base Representation Classes
- * @{
- */
- /**
- * System services.
- */
- class BxBaseServices extends BxDol implements iBxDolProfileService
- {
- public function __construct()
- {
- parent::__construct();
- }
- public function serviceIsPublicService($s)
- {
- $sService = bx_gen_method_name($s);
- $aServices = $this->serviceGetPublicServices();
- return isset($aServices[$sService]);
- }
- public function serviceGetPublicServices()
- {
- return array (
- 'GetProductsNames' => 'BxBaseServices',
- 'GetPageByRequest' => 'BxBaseServicePages',
- );
- }
- public function serviceIsSafeService($s)
- {
- $sService = bx_gen_method_name($s);
- $aSafeServices = $this->serviceGetSafeServices();
- return isset($aSafeServices[$sService]);
- }
- public function serviceGetSafeServices()
- {
- return array(
- 'GetMenu' => 'BxBaseServices',
- 'GetCreatePostForm' => 'BxBaseServices',
- 'GetProductsNames' => 'BxBaseServices',
- 'KeywordSearch' => 'BxBaseServicesSearch',
- 'GetDataSearchApi' => 'BxBaseServicesSearch',
- 'SearchParse' => 'BxBaseServicesSearch',
- 'GetBlockSearchAi' => 'BxBaseServicesSearch',
- 'SearchAiResults' => 'BxBaseServicesSearch',
- 'Cmts' => 'BxBaseServices',
- 'GetFooter' => 'BxBaseServices',
- 'SetBadges' => 'BxBaseServices',
- 'GetPageContentByRequest' => 'BxBaseServicePages',
- 'GetPageBlockData' => 'BxBaseServicePages',
- 'SetPageBlockData' => 'BxBaseServicePages',
- 'GetPageBlockImageData' => 'BxBaseServicePages',
- 'GetUrlInfo' => 'BxBaseServicePages',
- 'CreateAccountForm' => 'BxBaseServiceAccount',
- 'AccountSettingsEmail' => 'BxBaseServiceAccount',
- 'AccountSettingsPassword' => 'BxBaseServiceAccount',
- 'AccountSettingsDelAccount' => 'BxBaseServiceAccount',
- 'AccountSettingsInfo' => 'BxBaseServiceAccount',
- 'ForgotPassword' => 'BxBaseServiceAccount',
- 'SwitchProfile' => 'BxBaseServiceAccount',
- 'AccountProfileSwitcher' => 'BxBaseServiceAccount',
- 'EmailConfirmation' => 'BxBaseServiceAccount',
- 'ConfirmEmail' => 'BxBaseServiceAccount',
-
- 'CategoriesList' => 'BxBaseServiceCategory',
- 'Test' => 'BxBaseServiceLogin',
- 'MemberAuthCode' => 'BxBaseServiceLogin',
- 'LoginForm' => 'BxBaseServiceLogin',
- 'LoginFormOnly' => 'BxBaseServiceLogin',
- 'Logout' => 'BxBaseServiceLogin',
-
- 'KeywordsCloud' => 'BxBaseServiceMetatags',
- 'AccountProfileSwitcher' => 'BxBaseServiceProfiles',
- 'ProfileMembership' => 'BxBaseServiceProfiles',
- 'ProfileNotifications' => 'BxBaseServiceProfiles',
- 'GetCountOnlineProfiles' => 'BxBaseServiceProfiles',
- 'BrowseRecommendationsFriends' => 'BxBaseServiceProfiles',
- 'BrowseRecommendationsSubscriptions' => 'BxBaseServiceProfiles',
- 'BrowseFriends' => 'BxBaseServiceProfiles',
- 'SetMembership' => 'BxBaseServiceProfiles',
- 'ResetMembership' => 'BxBaseServiceProfiles',
- 'BrowseFriendRequests' => 'BxBaseServiceProfiles',
- 'BrowseFriendRequested' => 'BxBaseServiceProfiles',
- 'BrowseSubscribedMe' => 'BxBaseServiceProfiles',
- 'BrowseSubscriptions' => 'BxBaseServiceProfiles',
- 'BrowseMembers' => 'BxBaseServiceProfiles',
- 'BrowseInvitations' => 'BxBaseServiceProfiles',
- 'UpdateSettings' => 'BxBaseServiceProfiles',
- 'Befriend' => 'BxBaseServiceProfiles',
- 'ProfileCounters' => 'BxBaseServiceProfiles',
- 'ProfileInfo' => 'BxBaseServiceProfiles',
-
- 'GetChartGrowth' => 'BxBaseChartServices',
- 'GetChartStats' => 'BxBaseChartServices',
- 'GetDataByInterval' => 'BxBaseChartServices',
-
- 'GetCartItemsCount' => 'BxBasePaymentsServices',
- 'GetOrdersCount' => 'BxBasePaymentsServices',
- 'Do' => 'BxBaseReportServices',
- 'GetPerformedBy' => 'BxBaseReportServices',
- 'Do' => 'BxBaseVoteServices',
- 'GetPerformedBy' => 'BxBaseVoteServices',
- 'Perform' => 'BxBaseFeatureServices',
-
- 'Perform' => 'BxBaseFavoriteServices',
- 'GetPerformedBy' => 'BxBaseFavoriteServices',
- 'Perform' => 'BxBaseServiceConnections',
- 'Perform' => 'BxBaseServiceRecommendations',
- 'GetDataApi' => 'BxBaseCmtsServices',
- 'GetDataApi' => 'BxBaseUploaderServices',
- 'GetUploadToken' => 'BxBaseUploaderServices',
- 'GetStatBlock' => 'BxBaseDashboardServices',
- 'GetAdminBlock' => 'BxBaseDashboardServices',
- 'PerfomActionApi' => 'BxBaseServiceGrid',
- 'GetLabels' => 'BxBaseLabelsServices',
- 'GetForm' => 'BxBaseSearchExtendedServices',
- 'GetResults' => 'BxBaseSearchExtendedServices',
- 'WikiAction' => 'BxBaseServiceWiki',
- 'AiChat' => 'BxBaseServices',
- 'AiChatUpload' => 'BxBaseServices',
- 'GetBlockAiAgentOperator' => 'BxBaseServices',
- 'GetAiChatThreads' => 'BxBaseServices',
- 'GetAiChatThread' => 'BxBaseServices',
- 'GetAiAgents' => 'BxBaseServices',
- 'GetBlockAiAgentsAdmin' => 'BxBaseServices',
- 'SetAiAgentActive' => 'BxBaseServices',
- 'GetAiAgentActivity' => 'BxBaseServices',
- 'GetAiAgentChatThreads' => 'BxBaseServices',
- 'GetAiAgentChatThread' => 'BxBaseServices',
- 'GetMockupBlock' => 'BxBaseServices',
- );
- }
- public function serviceGetPreloaderContent($sName) {
- $sResult = '';
- switch($sName) {
- case 'icons_css':
- if(($sCss = BxDolIconset::getObjectInstance()->getPreloaderCss()) !== false)
- $sResult = $sCss;
- break;
- case 'icons_js':
- if(($sJs = BxDolIconset::getObjectInstance()->getPreloaderJs()) !== false)
- $sResult = $sJs;
- break;
- case 'tailwind':
- $sFile = getParam('sys_css_tailwind_default');
- if(empty($sFile))
- $sFile = 'tailwind.min.css';
- $sPath = '{dir_plugins_public}tailwind/css/|';
- if($sFile == 'cdn')
- $sResult = [
- 'https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4',
- $sPath . 'tailwind.min.css' //TODO: Replace this with correct file name.
- ];
- else
- $sResult = $sPath . $sFile;
- break;
- }
- return $sResult;
- }
-
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-module_check_for_update module_check_for_update
- *
- * @code bx_srv('system', 'module_check_for_update', ["bx_posts"]); @endcode
- * @code bx_srv('system', 'module_check_for_update', ["bx_posts"], 'TemplServices'); @endcode
- * @code {{~system:module_check_for_update:TemplServices["bx_posts"]~}} @endcode
- *
- * Checks whether an update is available for requested module or not.
- * @param $mixedModule - module ID/name to check the updates for.
- * @return array with information about the update, false if nothing was found
- *
- * @see BxBaseServices::serviceModuleCheckForUpdate
- */
- /**
- * @ref bx_system_general-module_check_for_update "module_check_for_update"
- */
- public function serviceModuleCheckForUpdate($mixedModule)
- {
- $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
- if(empty($aModule) || !is_array($aModule))
- return false;
- $aUpdates = BxDolStudioInstallerUtils::getInstance()->checkUpdatesByModule($aModule['name']);
- if(empty($aUpdates) || !is_array($aUpdates))
- return false;
- $aUpdate = array_shift($aUpdates);
- return array(
- 'version_from' => $aUpdate['file_version'],
- 'version_to' => $aUpdate['file_version_to'],
- 'file_id' => $aUpdate['file_id']
- );
- }
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-module_update module_update
- *
- * @code bx_srv('system', 'module_update', ["bx_posts"]); @endcode
- * @code bx_srv('system', 'module_update', ["bx_posts"], 'TemplServices'); @endcode
- * @code {{~system:module_update:TemplServices["bx_posts"]~}} @endcode
- *
- * Download and install an update for requested module. The operation may be performed
- * immediately or by Transient Cron task. The second way is more common.
- * @param $mixedModule - module ID/name to check the updates for.
- * @return integer value determining the result of the operation. It can be one of the following values:
- * BX_DOL_STUDIO_IU_RC_SUCCESS, BX_DOL_STUDIO_IU_RC_FAILED or BX_DOL_STUDIO_IU_RC_SCHEDULED.
- *
- * @see BxBaseServices::serviceModuleUpdate
- */
- /**
- * @ref bx_system_general-module_update "module_update"
- */
- public function serviceModuleUpdate($mixedModule)
- {
- $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
- if(empty($aModule) || !is_array($aModule))
- return BX_DOL_STUDIO_IU_RC_FAILED;
- $aResult = BxDolStudioInstallerUtils::getInstance()->downloadUpdatePublic($aModule['name'], true);
- return $aResult['code'];
- }
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-module_delete module_delete
- *
- * @code bx_srv('system', 'module_delete', ["bx_posts"]); @endcode
- * @code bx_srv('system', 'module_delete', ["bx_posts", true], 'TemplServices'); @endcode
- * @code {{~system:module_delete:TemplServices["bx_posts"]~}} @endcode
- *
- * Delete the requested module. By default only uninstalled module can be deleted.
- * The operation may be performed immediately or by Transient Cron task. The second way is more common.
- * @param $sModule - module name to delete.
- * @param $bForceUninstall - if 'true' is passed the module will be uninstalled before deletion.
- * @return integer value determining the result of the operation. It can be one of the following values:
- * BX_DOL_STUDIO_IU_RC_SUCCESS, BX_DOL_STUDIO_IU_RC_FAILED or BX_DOL_STUDIO_IU_RC_SCHEDULED.
- *
- * @see BxBaseServices::serviceModuleDelete
- */
- /**
- * @ref bx_system_general-module_delete "module_delete"
- */
- public function serviceModuleDelete($sModule, $bForceUninstall = false)
- {
- $sModulePath = '';
- $oInstallerUtils = BxDolStudioInstallerUtils::getInstance();
- $aModule = BxDolModuleQuery::getInstance()->getModuleByName($sModule, false);
- if(!empty($aModule) && is_array($aModule)) {
- if(!$bForceUninstall)
- return BX_DOL_STUDIO_IU_RC_FAILED;
- $sModulePath = $aModule['path'];
- $aResult = $oInstallerUtils->perform($sModulePath, 'uninstall', array('auto_disable' => $bForceUninstall));
- if($aResult['code'] != BX_DOL_STUDIO_IU_RC_SUCCESS)
- return BX_DOL_STUDIO_IU_RC_FAILED;
- }
- else {
- $aModules = $oInstallerUtils->getModules(false);
- if(!isset($aModules[$sModule]))
- return BX_DOL_STUDIO_IU_RC_FAILED;
-
- $sModulePath = $aModules[$sModule]['dir'];
- }
- $aResult = $oInstallerUtils->perform($sModulePath, 'delete');
- return $aResult['code'];
- }
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-module_install module_install
- *
- * @code bx_srv('system', 'module_install', ["bx_posts"]); @endcode
- * @code bx_srv('system', 'module_install', ["bx_posts", true], 'TemplServices'); @endcode
- * @code {{~system:module_install:TemplServices["bx_posts"]~}} @endcode
- *
- * Install the requested module. By default the module will be installed only.
- * @param $sModule - module name to install.
- * @param $bForceEnable - if 'true' is passed the module will be automatically enabled after installation.
- * @return boolean value determining the result of the operation.
- *
- * @see BxBaseServices::serviceModuleInstall
- */
- /**
- * @ref bx_system_general-module_install "module_install"
- */
- public function serviceModuleInstall($sModule, $bForceEnable = false)
- {
- $oInstallerUtils = BxDolStudioInstallerUtils::getInstance();
- $aModules = $oInstallerUtils->getModules(false);
- if(!isset($aModules[$sModule]))
- return false;
- $aResult = $oInstallerUtils->perform($aModules[$sModule]['dir'], 'install', array('auto_enable' => $bForceEnable));
- if($aResult['code'] != BX_DOL_STUDIO_IU_RC_SUCCESS)
- return false;
- return true;
- }
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-module_uninstall module_uninstall
- *
- * @code bx_srv('system', 'module_uninstall', ["bx_posts"]); @endcode
- * @code bx_srv('system', 'module_uninstall', ["bx_posts", true], 'TemplServices'); @endcode
- * @code {{~system:module_uninstall:TemplServices["bx_posts"]~}} @endcode
- *
- * Uninstall the requested module. By default only disabled module can be uninstalled.
- * @param $mixedModule - module ID/name to uninstall.
- * @param $bForceDisable - if 'true' is passed the module will be automatically disabled before uninstallation.
- * @return boolean value determining the result of the operation.
- *
- * @see BxBaseServices::serviceModuleUninstall
- */
- /**
- * @ref bx_system_general-module_uninstall "module_uninstall"
- */
- public function serviceModuleUninstall($mixedModule, $bForceDisable = false)
- {
- $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
- if(empty($aModule) || !is_array($aModule))
- return false;
- if((int)$aModule['enabled'] != 0 && !$bForceDisable)
- return false;
- $aResult = BxDolStudioInstallerUtils::getInstance()->perform($aModule['path'], 'uninstall', array('auto_disable' => $bForceDisable));
- if($aResult['code'] != BX_DOL_STUDIO_IU_RC_SUCCESS)
- return false;
- return true;
- }
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-module_enable module_enable
- *
- * @code bx_srv('system', 'module_enable', ["bx_posts"]); @endcode
- * @code bx_srv('system', 'module_enable', ["bx_posts"], 'TemplServices'); @endcode
- * @code {{~system:module_enable:TemplServices["bx_posts"]~}} @endcode
- *
- * Enable the requested module.
- * @param $mixedModule - module ID/name to enable.
- * @return boolean value determining the result of the operation.
- *
- * @see BxBaseServices::serviceModuleEnable
- */
- /**
- * @ref bx_system_general-module_enable "module_enable"
- */
- public function serviceModuleEnable($mixedModule)
- {
- $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
- if(empty($aModule) || !is_array($aModule))
- return false;
- if((int)$aModule['enabled'] != 0)
- return false;
- $aResult = BxDolStudioInstallerUtils::getInstance()->perform($aModule['path'], 'enable');
- if($aResult['code'] != BX_DOL_STUDIO_IU_RC_SUCCESS)
- return false;
- return true;
- }
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-module_disable module_disable
- *
- * @code bx_srv('system', 'module_disable', ["bx_posts"]); @endcode
- * @code bx_srv('system', 'module_disable', ["bx_posts"], 'TemplServices'); @endcode
- * @code {{~system:module_disable:TemplServices["bx_posts"]~}} @endcode
- *
- * Disable the requested module.
- * @param $mixedModule - module ID/name to disable.
- * @return boolean value determining the result of the operation.
- *
- * @see BxBaseServices::serviceModuleDisable
- */
- /**
- * @ref bx_system_general-module_disable "module_disable"
- */
- public function serviceModuleDisable($mixedModule)
- {
- $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
- if(empty($aModule) || !is_array($aModule))
- return false;
- if((int)$aModule['enabled'] == 0)
- return false;
- $aResult = BxDolStudioInstallerUtils::getInstance()->perform($aModule['path'], 'disable');
- if($aResult['code'] != BX_DOL_STUDIO_IU_RC_SUCCESS)
- return false;
- return true;
- }
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-is_module_installed is_module_installed
- *
- * @code bx_srv('system', 'is_module_installed', ["bx_posts"]); @endcode
- * @code bx_srv('system', 'is_module_installed', ["bx_posts"], 'TemplServices'); @endcode
- * @code {{~system:is_module_installed:TemplServices["bx_posts"]~}} @endcode
- *
- * Checks whether the requested module is installed or not.
- * @param $mixedModule - module ID/name to check.
- * @return boolean value determining the result of the operation.
- *
- * @see BxBaseServices::serviceIsModuleInstalled
- */
- /**
- * @ref bx_system_general-is_module_installed "is_module_installed"
- */
- public function serviceIsModuleInstalled($mixedModule)
- {
- $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
- return !empty($aModule) && is_array($aModule);
- }
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-is_module_enabled is_module_enabled
- *
- * @code bx_srv('system', 'is_module_enabled', ["bx_posts"]); @endcode
- * @code bx_srv('system', 'is_module_enabled', ["bx_posts"], 'TemplServices'); @endcode
- * @code {{~system:is_module_enabled:TemplServices["bx_posts"]~}} @endcode
- *
- * Checks whether the requested module is enabled or not.
- * @param $mixedModule - module ID/name to check.
- * @return boolean value determining the result of the operation.
- *
- * @see BxBaseServices::serviceIsModuleEnabled
- */
- /**
- * @ref bx_system_general-is_module_enabled "is_module_enabled"
- */
- public function serviceIsModuleEnabled($mixedModule)
- {
- $aModule = BxDolModuleQuery::getInstance()->{'getModuleBy' . (is_numeric($mixedModule) ? 'Id' : 'Name')}($mixedModule, false);
- return !empty($aModule) && is_array($aModule) && (int)$aModule['enabled'] != 0;
- }
- /**
- * Checks whether a module is a 'Content' module or not.
- *
- * @param string $mixedModule - module name or an instance of Module class.
- * @return boolean result of operation.
- */
- public function serviceIsModuleContent($mixedModule)
- {
- if($mixedModule instanceof BxDolModule)
- $mixedModule = $mixedModule->getName();
- return BxDolModuleQuery::getInstance()->isModuleContent($mixedModule);
- }
- /**
- * Checks whether a module is a 'Context' module or not.
- *
- * @param string $mixedModule - module name or an instance of Module class.
- * @return boolean result of operation.
- */
- public function serviceIsModuleContext($mixedModule)
- {
- if($mixedModule instanceof BxDolModule)
- $mixedModule = $mixedModule->getName();
- return BxDolModuleQuery::getInstance()->isModuleContext($mixedModule);
- }
- /**
- * Checks whether a module is a 'Profile' module or not.
- *
- * @param string $mixedModule - module name or an instance of Module class.
- * @return boolean result of operation.
- */
- public function serviceIsModuleProfile($mixedModule)
- {
- if($mixedModule instanceof BxDolModule)
- $mixedModule = $mixedModule->getName();
- return BxDolModuleQuery::getInstance()->isModuleProfile($mixedModule);
- }
- /**
- * Get modules by type. Available types are 'content', 'context', 'profile'.
- *
- * @param type $sType - string with type.
- * @return array of modules.
- */
- public function serviceGetModulesByType($sType, $aParams = [])
- {
- $oModuleQuery = BxDolModuleQuery::getInstance();
- if(!$oModuleQuery->checkModulesSubtypes()) {
- $oInstallerUtils = new BxDolInstallerUtils();
- $aModules = $oModuleQuery->getModulesBy(['type' => 'modules']);
- foreach($aModules as $aModule)
- if(($iModuleSubtypes = $oInstallerUtils->getSubtypes($aModule['name'])) != 0)
- $oModuleQuery->updateModule(['subtypes' => $iModuleSubtypes], ['id' => $aModule['id']]);
- }
- $iSubtypes = 0;
- switch($sType) {
- case 'content':
- $iSubtypes = BX_DOL_MODULE_SUBTYPE_TEXT;
- break;
- case 'context':
- $iSubtypes = BX_DOL_MODULE_SUBTYPE_CONTEXT;
- break;
- case 'profile':
- $iSubtypes = BX_DOL_MODULE_SUBTYPE_PROFILE;
- break;
- }
- $aResults = $oModuleQuery->getModulesBy(array_merge([
- 'type' => 'modules_subtypes',
- 'value' => $iSubtypes,
- 'active' => 1
- ], array_intersect_key($aParams, array_flip(['id_as_key', 'name_as_key']))));
- return $aResults;
- }
- public function serviceGetModulesBySubtypeSimple($sType)
- {
- $a = $this->serviceGetModulesByType($sType, ['name_as_key' => true]);
- return array_map(function ($r) {
- return $r['title'];
- }, $a);
- }
- public function serviceProfileUnit ($iContentId, $aParams = array())
- {
- return $this->_serviceProfileFunc('getUnit', $iContentId, $aParams);
- }
-
- public function serviceProfileUnitApi ($iContentId, $aParams = [])
- {
- return $this->_serviceProfileFunc('getUnitApi', $iContentId, $aParams);
- }
- public function serviceHasImage ($iContentId)
- {
- return false;
- }
- public function serviceProfilePicture ($iContentId)
- {
- return $this->_serviceProfileFunc('getPicture', $iContentId);
- }
- public function serviceProfileAvatar ($iContentId)
- {
- return $this->_serviceProfileFunc('getAvatar', $iContentId);
- }
- public function serviceProfileAvatarBig ($iContentId)
- {
- return $this->_serviceProfileFunc('getAvatarBig', $iContentId);
- }
- public function serviceProfileCover ($iContentId)
- {
- return '';
- }
- public function serviceProfileEditUrl ($iContentId)
- {
- return bx_absolute_url(BxDolPermalinks::getInstance()->permalink('page.php?i=account-settings-info'));
- }
- public function serviceProfileThumb ($iContentId)
- {
- return $this->_serviceProfileFunc('getThumb', $iContentId);
- }
- public function serviceProfileIcon ($iContentId)
- {
- return $this->_serviceProfileFunc('getIcon', $iContentId);
- }
- public function serviceProfileName ($iContentId)
- {
- return $this->_serviceProfileFunc('getDisplayName', $iContentId);
- }
- public function serviceProfileUrl ($iContentId)
- {
- return $this->_serviceProfileFunc('getUrl', $iContentId);
- }
- /**
- * @see iBxDolProfileService::serviceCheckAllowedProfileView
- */
- public function serviceCheckAllowedProfileView($iContentId)
- {
- return _t('_Access denied');
- }
- /**
- * @see iBxDolProfileService::serviceCheckAllowedProfileContact
- */
- public function serviceCheckAllowedProfileContact($iContentId)
- {
- return _t('_Access denied');
- }
- /**
- * @see iBxDolProfileService::serviceCheckAllowedPostInProfile
- */
- public function serviceCheckAllowedPostInProfile($iContentId, $sPostModule = '')
- {
- return _t('_Access denied');
- }
- /**
- * @see iBxDolProfileService::serviceCheckAllowedModuleActionInProfile
- */
- public function serviceCheckAllowedModuleActionInProfile($iContentId, $sPostModule, $sActionName)
- {
- return _t('_Access denied');
- }
- /**
- * @see iBxDolProfileService::serviceGetSpaceTitle
- */
- public function serviceGetSpaceTitle()
- {
- return '';
- }
- /**
- * @see iBxDolProfileService::serviceGetParticipatingProfiles
- */
- public function serviceGetParticipatingProfiles($iProfileId, $aConnectionObject = false)
- {
- return array();
- }
-
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-get_create_post_form get_create_post_form
- *
- * @code bx_srv('system', 'get_create_post_form', [false, "bx_posts"], 'TemplServices'); @endcode
- * @code {{~system:get_create_post_form:TemplServices[false,"bx_posts"]~}} @endcode
- *
- * Get United Create Post form.
- * @param $mixedContextId - context which the post will be created in:
- * - false = 'Public' post form;
- * - 0 = 'Profile' post form, which allows to post in your own profile and connections;
- * - n = 'Context' post form, which allows to post in context (3d party profile, group, event, etc).
- * @param $sDefault - tab selected by default.
- * @param $aCustom - an array with custom paramaters.
- * @return string with form content
- *
- * @see BxBaseServices::serviceGetCreatePostForm
- */
- /**
- * @ref bx_system_general-get_create_post_form "get_create_post_form"
- */
- public function serviceGetCreatePostForm($mixedContextId = false, $sDefault = '', $aCustom = array())
- {
- if(!isLogged() || ($mixedContextId !== false && !is_numeric($mixedContextId)))
- return '';
- $oProfile = BxDolProfile::getInstance();
- if(!$oProfile)
- return '';
- if($mixedContextId !== false)
- $mixedContextId = (int)(!empty($mixedContextId) ? -$mixedContextId : $oProfile->id());
- $oMenu = BxDolMenu::getObjectInstance('sys_create_post');
- if(!$oMenu)
- return '';
- $oMenu->setContextId($mixedContextId);
- $aMenuItems = $oMenu->getMenuItems();
- if(empty($aMenuItems) || !is_array($aMenuItems))
- return '';
- if(empty($sDefault)) {
- $aDefault = array_shift($aMenuItems);
- $sDefault = !empty($aDefault['module']) ? $aDefault['module'] : $aDefault['name'];
- }
- $oMenu->setSelected($sDefault, $sDefault);
- $oContext = false;
- $bContext = $mixedContextId !== false;
- if($bContext && ($oContext = BxDolProfile::getInstance(abs($mixedContextId))) !== false)
- if(bx_srv($oContext->getModule(), 'check_allowed_post_in_profile', [$oContext->getContentId(), $sDefault]) !== CHECK_ACTION_RESULT_ALLOWED)
- return '';
- $sTitle = '_sys_page_block_title_create_post';
- if(!$bContext)
- $sTitle = _t($sTitle . '_public');
- else if($mixedContextId < 0) {
- $sTitle = _t($sTitle . '_context');
- if($oContext)
- $sTitle = bx_replace_markers($sTitle, [
- 'display_name' => $oContext->getDisplayName()
- ]);
- }
- else
- $sTitle = _t($sTitle);
- $sPlaceholder = _t('_sys_txt_create_post_placeholder', $oProfile->getDisplayName());
- $oDbModules = BxDolModuleQuery::getInstance();
- $oTemplate = BxDolTemplate::getInstance();
- $oTemplate->addJs(['BxDolCreatePost.js']);
- $aPreloadingList = [];
- $aModules = explode(',', getParam('sys_create_post_form_preloading_list'));
- if(!empty($aModules))
- foreach($aModules as $sModule) {
- $aModule = $oDbModules->getModuleByName($sModule);
- if(empty($aModule) || !is_array($aModule))
- continue;
- $aPreloadingList[$sModule] = $aModule['uri'];
- }
- if(bx_is_api()) {
- return [
- 'title' => $sTitle,
- 'content' => [
- bx_api_get_block('get_create_post_form', [
- 'menu' => $oMenu->getCodeAPI(),
- 'params' => ['context_id' => $mixedContextId]])
- ]
- ];
- }
- $sJsObject = 'oBxDolCreatePost';
- $sJsContent = $oTemplate->_wrapInTagJsCode("var " . $sJsObject . " = new BxDolCreatePost(" . json_encode([
- 'sObjName' => $sJsObject,
- 'sRootUrl' => BX_DOL_URL_ROOT,
- 'sDefault' => $sDefault,
- 'iContextId' => $bContext ? $mixedContextId : 0,
- 'oPreloadingList' => $aPreloadingList,
- 'oCustom' => $aCustom
- ]) . ");");
- return [
- 'title' => $sTitle,
- 'content' => $oTemplate->parseHtmlByName('create_post_form.html', [
- 'default' => $sDefault,
- 'placeholder' => $sPlaceholder,
- 'user_thumb' => $oProfile->getUnit(0, ['template' => 'unit_wo_info_links']),
- 'form' => bx_srv($sDefault, 'get_create_post_form', [[
- 'context_id' => $mixedContextId,
- 'ajax_mode' => true,
- 'absolute_action_url' => true,
- 'custom' => $aCustom
- ]]),
- 'js_object' => $sJsObject,
- 'js_content' => $sJsContent
- ]),
- 'menu' => $oMenu->getMenuItemsCount() > 1 ? $oMenu : ''
- ];
- }
- public function serviceGetOptionsCreatePostFormPreloadingList()
- {
- $oMenu = BxDolMenu::getObjectInstance('sys_create_post');
- if(!$oMenu)
- return [];
- $aMenuItems = $oMenu->getMenuItems();
- $aResult = [];
- foreach($aMenuItems as $aMenuItem) {
- $sModule = !empty($aMenuItem['module']) ? $aMenuItem['module'] : $aMenuItem['name'];
- if(!bx_srv('system', 'is_module_enabled', [$sModule]))
- continue;
- $aResult[] = [
- 'key' => $sModule,
- 'value' => _t('_' . $sModule)
- ];
- }
- return $aResult;
- }
- public function serviceGetBlockStatic($sBlockName)
- {
- $bIsApi = bx_is_api();
- if(!$bIsApi)
- return '';
- return [bx_api_get_block('static', [
- 'element' => $sBlockName
- ])];
- }
- public function serviceGetBlockAuthor($sModule, $iContentId = 0)
- {
- if(!$iContentId && bx_get('id') !== false)
- $iContentId = (int)bx_get('id');
- $sMethodGetAuthor = 'get_author';
- if(!$sModule || !$iContentId || !BxDolRequest::serviceExists($sModule, $sMethodGetAuthor))
- return '';
- $iAuthor = bx_srv($sModule, $sMethodGetAuthor, [$iContentId]);
- if(!$iAuthor)
- return '';
- $oAuthor = BxDolProfile::getInstance($iAuthor);
- if(!$oAuthor)
- return '';
- $sModuleAuthor = $oAuthor->getModule();
- $sMethodGetCover = 'entity_cover';
- if(!BxDolRequest::serviceExists($sModuleAuthor, $sMethodGetCover))
- return '';
- return bx_srv($sModuleAuthor, $sMethodGetCover, [$oAuthor->getContentId(), [
- 'use_as_author' => true,
- 'show_text' => false
- ]]);
- }
- /**
- * AI agent chat block.
- *
- * Studio / `bx_srv('system', 'get_block_ai_agent', [...], 'TemplServices')`:
- *
- * array (
- * 'module' => 'system',
- * 'method' => 'get_block_ai_agent',
- * 'params' =>
- * array (
- * 0 => 6, // agent id
- * 1 => array (
- * 'context' => false, // profile id, or false = resolve from the page
- * 'require_post' => false, // only accept a page/post as context
- * 'allow_images' => true, // composer image attachments
- * 'allow_new' => false, // "Start new" extra threads (`?chat=`)
- * 'show_history' => false, // "Chats" panel with the viewer's earlier threads (App only; operator block turns it on)
- * ),
- * ),
- * 'class' => 'TemplServices',
- * )
- *
- * Legacy positional params still work: (id, context, require_post, allow_images, allow_new, show_history).
- *
- * @param int $iId Agent id
- * @param array|int|false $aParams Named options (preferred) or legacy context pid
- */
- public function serviceGetBlockAiAgent($iId = 0, $aParams = [], ...$aLegacy)
- {
- $bIsApi = bx_is_api();
- $aAgent = BxDolAiQuery::getAgentObject($iId);
- if(!$aAgent || !is_array($aAgent))
- return $bIsApi ? [] : '';
- $aParams = $this->_normalizeAiAgentBlockParams($aParams, $aLegacy);
- $mixedContextPid = $aParams['context'];
- $bRequirePost = $aParams['require_post'];
- $oAi = BxDolAi::getInstance();
- $oChat = BxDolAiChat::getInstance();
- if ($mixedContextPid === false || $mixedContextPid === null || $mixedContextPid === '')
- $iContextPid = $oAi ? (int)$oChat->resolveChatHistoryContextPidFromPage($bRequirePost) : 0;
- else
- $iContextPid = $oAi ? $oChat->filterContextPid((int)$mixedContextPid, $bRequirePost) : 0;
- if ($bIsApi)
- return [bx_api_get_block('ai_agent', [
- 'agent_id' => $iId,
- 'agent_profile' => BxDolProfile::getData($aAgent['profile_id']),
- 'context_profile_id' => $iContextPid,
- 'hidden_first_message' => (string)($aAgent['hidden_first_message'] ?? ''),
- 'allow_images' => $aParams['allow_images'] ? 1 : 0,
- 'allow_new' => $aParams['allow_new'] ? 1 : 0,
- 'show_history' => $aParams['show_history'] ? 1 : 0,
- 'max_images' => BxDolAiChatImages::MAX_PER_TURN,
- 'max_input_chars' => (int)($aAgent['max_input_chars'] ?? 0),
- ])];
- $sEndpoint = BX_DOL_URL_ROOT . 'sys-ai-chat/' . (int)$iId;
- if ($iContextPid > 0)
- $sEndpoint .= '&context=' . $iContextPid;
- $oTemplate = BxDolTemplate::getInstance();
- $oTemplate->addJs([BX_DOL_URL_ROOT . 'plugins_public/bundle.js']);
- return $oTemplate->parseHtmlByName('agent_ai_chat.html', [
- 'id' => (int)$iId,
- 'context_profile_id' => (int)$iContextPid,
- 'endpoint_js' => json_encode($sEndpoint),
- 'bundle_url' => BX_DOL_URL_ROOT . 'plugins_public/bundle.js',
- ]);
- }
- /**
- * Operator AI agent block: the single definition of "which agent, with which
- * settings" for site operators. The Dashboard page block and the App floating
- * bubble both call this service with no params, so they can never diverge.
- *
- * Agent id comes from Studio > Settings > Agents (`sys_agents_operator_agent`).
- * Block params are fixed here — change them here, and only here. This is the one
- * block with the "Chats" history panel (`show_history`): operators come back to
- * the same agent again and again, and need to find what it did last time.
- *
- * Studio: `{"module":"system","method":"get_block_ai_agent_operator","class":"TemplServices"}`
- * API: `api.php?r=system/get_block_ai_agent_operator/TemplServices`
- */
- public function serviceGetBlockAiAgentOperator()
- {
- $bIsApi = bx_is_api();
- $iId = (int)getParam('sys_agents_operator_agent');
- if ($iId <= 0)
- return $bIsApi ? [] : '';
- $aAgent = BxDolAiQuery::getAgentObject($iId);
- $oAi = BxDolAi::getInstance();
- if (!$aAgent || !is_array($aAgent) || !$oAi || !$oAi->canChatDirectly($aAgent))
- return $bIsApi ? [] : '';
- return $this->serviceGetBlockAiAgent($iId, [
- 'context' => false,
- 'require_post' => false,
- 'allow_images' => true,
- 'allow_new' => true,
- 'show_history' => true,
- ]);
- }
- /**
- * Studio > Settings select for `sys_agents_operator_agent`: active agents
- * that can be chatted with directly (see BxDolAi::canChatDirectly).
- */
- public function serviceGetOptionsOperatorAgent()
- {
- $aResult = [
- ['key' => '', 'value' => _t('_Select_one')],
- ];
- $aAgents = BxDolDb::getInstance()->getAll("SELECT `id`, `name` FROM `sys_agents_agents` WHERE `active` = 1 AND `trigger` IN ('manual', 'message') ORDER BY `name` ASC");
- foreach ($aAgents as $aAgent) {
- $aResult[] = [
- 'key' => (int)$aAgent['id'],
- 'value' => $aAgent['name'] . ' (#' . (int)$aAgent['id'] . ')',
- ];
- }
- return $aResult;
- }
- /**
- * Named options for {@see serviceGetBlockAiAgent}, plus legacy positional args.
- *
- * @return array{context:mixed,require_post:bool,allow_images:bool,allow_new:bool,show_history:bool}
- */
- protected function _normalizeAiAgentBlockParams($mixedParams, array $aLegacy = [])
- {
- $isOn = function ($v) {
- return $v === true || $v === 1 || $v === '1' || $v === 'true' || $v === 'on' || $v === 'yes';
- };
- $aOut = [
- 'context' => false,
- 'require_post' => false,
- 'allow_images' => false,
- 'allow_new' => false,
- 'show_history' => false,
- ];
- $aNamedKeys = ['context', 'context_profile_id', 'require_post', 'allow_images', 'allow_new', 'show_history'];
- $bNamed = is_array($mixedParams);
- if ($bNamed && $mixedParams) {
- $bNamed = false;
- foreach ($aNamedKeys as $sKey) {
- if (array_key_exists($sKey, $mixedParams)) {
- $bNamed = true;
- break;
- }
- }
- }
- if ($bNamed) {
- if (array_key_exists('context', $mixedParams))
- $aOut['context'] = $mixedParams['context'];
- elseif (array_key_exists('context_profile_id', $mixedParams))
- $aOut['context'] = $mixedParams['context_profile_id'];
- if (array_key_exists('require_post', $mixedParams))
- $aOut['require_post'] = $mixedParams['require_post'];
- if (array_key_exists('allow_images', $mixedParams))
- $aOut['allow_images'] = $mixedParams['allow_images'];
- if (array_key_exists('allow_new', $mixedParams))
- $aOut['allow_new'] = $mixedParams['allow_new'];
- if (array_key_exists('show_history', $mixedParams))
- $aOut['show_history'] = $mixedParams['show_history'];
- } else {
- $aOut['context'] = $mixedParams;
- if (array_key_exists(0, $aLegacy))
- $aOut['require_post'] = $aLegacy[0];
- if (array_key_exists(1, $aLegacy))
- $aOut['allow_images'] = $aLegacy[1];
- if (array_key_exists(2, $aLegacy))
- $aOut['allow_new'] = $aLegacy[2];
- if (array_key_exists(3, $aLegacy))
- $aOut['show_history'] = $aLegacy[3];
- }
- $aOut['require_post'] = $isOn($aOut['require_post']);
- $aOut['allow_images'] = $isOn($aOut['allow_images']);
- $aOut['allow_new'] = $isOn($aOut['allow_new']);
- $aOut['show_history'] = $isOn($aOut['show_history']);
- return $aOut;
- }
- public function serviceGetMenu($aParams)
- {
- $bIsApi = bx_is_api();
- $mixedResulEmpty = $bIsApi ? [] : '';
- if($bIsApi && is_string($aParams))
- $aParams = bx_api_get_browse_params($aParams);
- if(!isset($aParams['object']))
- return $mixedResulEmpty;
- $oMenu = BxDolMenu::getObjectInstance($aParams['object']);
- if(!$oMenu)
- return $mixedResulEmpty;
- if(!empty($aParams['params']) && is_array($aParams['params']))
- $oMenu->setContentParams($aParams['params']);
- return $bIsApi ? $oMenu->getCodeAPI() : $oMenu->getCode();
- }
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-get_site_submenu get_site_submenu
- *
- * @code bx_srv('system', 'get_site_submenu', [], 'TemplServices'); @endcode
- * @code {{~system:get_site_submenu:TemplServices[]~}} @endcode
- *
- * Get Site Submenu code.
- * @see BxBaseServices::serviceGetSiteSubmenu
- */
- /**
- * @ref bx_system_general-get_site_submenu "get_site_submenu"
- */
- public function serviceGetSiteSubmenu()
- {
- $oMenu = BxDolMenu::getObjectInstance('sys_site_submenu');
- return $oMenu ? $oMenu->getCode() : '';
- }
-
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-get_products_names get_products_names
- *
- * @code bx_srv('system', 'get_products_names', [], 'TemplServices');
- *
- * @code http://example.com/m/oauth2/com/get_products_names?module=system&class=BaseServices @endcode
- * @code http://hihi.una.io/modules/?r=oauth2/com/get_products_names&module=system&class=BaseServices @endcode
- *
- * Get an array of products names from all modules with payments functionality.
- * @param $iVendorId filter products by vendor ID.
- * @param $iLimit limit number of records from one module.
- * @return array of products where key id product name and value is module name
- *
- * @see BxBaseServices::serviceGetProductsNames
- */
- /**
- * @ref bx_system_general-get_products_names "get_products_names"
- */
- public function serviceGetProductsNames($iVendorId = 0, $iLimit = 1000)
- {
- $o = BxDolPayments::getInstance();
- if (!$o)
- return array();
- return $o->getProductsNames($iVendorId, $iLimit);
- }
- /**
- * @see iBxDolProfileService::serviceCheckSpacePrivacy
- */
- public function serviceCheckSpacePrivacy($iContentId)
- {
- return _t('_Access denied');
- }
-
- public function serviceFormsHelper ()
- {
- return new BxTemplAccountForms();
- }
- public function serviceActAsProfile ()
- {
- return false;
- }
- public function serviceGetModerators($iContentId)
- {
- $aModerators = BxDolAclQuery::getInstance()->getProfilesByMembership([
- MEMBERSHIP_ID_MODERATOR,
- MEMBERSHIP_ID_ADMINISTRATOR
- ]);
- $aIds = [];
- array_walk($aModerators, function ($aItem, $iKey, $aParams) {
- if(!empty($aItem['id']))
- $aParams[0][] = (int)$aItem['id'];
- }, [&$aIds]);
- return $aIds;
- }
- public function servicePrepareFields ($aFieldsProfile)
- {
- return $aFieldsProfile;
- }
- public function serviceProfilesSearch ($sTerm, $iLimit)
- {
- $oDb = BxDolAccountQuery::getInstance();
- $aRet = array();
- $a = $oDb->searchByTerm($sTerm, $iLimit);
- foreach ($a as $r)
- $aRet[] = array ('label' => $this->serviceProfileName($r['content_id']), 'value' => $r['profile_id']);
- return $aRet;
- }
- /**
- * @page service Service Calls
- * @section bx_system_general System Services
- * @subsection bx_system_general-general General
- * @subsubsection bx_system_general-cmts cmts
- *
- * @code bx_srv('system', 'cmts', ["sys_blocks", 1], 'TemplServices'); @endcode
- *
- * @code {{~system:cmts:TemplServices["sys_blocks", 1]~}} @endcode
- *
- * Comments block
- * @param $sObject - comments object name
- * @param $sId - content id assiciated tith the comments
- *
- * @see BxBaseServices::serviceCmts
- */
- /**
- * @ref bx_system_general-cmts "cmts"
- */
- public function serviceCmts ($sObject, $sId)
- {
- $o = BxDolCmts::getObjectInstance($sObject, $sId);
- if (!$o || !$o->isEnabled())
- return '';
- return $o->getCommentsBlock(array(), array('in_designbox' => false, 'show_empty' => true));
- }
- public function _serviceProfileFunc ($sFunc, $iContentId, $aParams = array())
- {
- if (!$iContentId)
- return false;
- if (!($oAccount = BxDolAccount::getInstance($iContentId)))
- return false;
- return $oAccount->$sFunc(false, $aParams);
- }
- public function serviceAlertResponseProcessInstalled()
- {
- BxDolTranscoderImage::registerHandlersSystem();
- }
- public function serviceAlertResponseProcessStorageChange ($oAlert)
- {
- if ('sys_storage_default' != $oAlert->aExtras['option'])
- return;
- $aStorages = BxDolStorageQuery::getStorageObjects();
- foreach ($aStorages as $r) {
- if (0 == $r['current_size'] && 0 == $r['current_number'] && ($oStorage = BxDolStorage::getObjectInstance($r['object'])))
- $oStorage->changeStorageEngine($oAlert->aExtras['value']);
- }
- }
- public function serviceGetOptionsProfileBot()
- {
- $aResult = array(
- array('key' => '', 'value' => _t('_Select_one'))
- );
- $aAccountsIds = BxDolAccountQuery::getInstance()->getOperators();
- foreach($aAccountsIds as $iAccountId) {
- $aProfilesIds = BxDolAccount::getInstance($iAccountId)->getProfilesIds(true, false);
- foreach($aProfilesIds as $iProfileId) {
- $oProfile = BxDolProfile::getInstance($iProfileId);
- $aResult[] = array(
- 'key' => $iProfileId,
- 'value' => _t('_sys_profile_with_type', $oProfile->getDisplayName(), $oProfile->getModule()),
- );
- }
- }
- return $aResult;
- }
-
- public function serviceGetOptionsModuleListForPrivacySelector()
- {
- $aResult = array();
- $BxDolModuleQuery = BxDolModuleQuery::getInstance();
- $aModules = $BxDolModuleQuery->getModulesBy(array('type' => 'modules', 'active' => 1));
- foreach($aModules as $aModule){
- $oModule = BxDolModule::getInstance($aModule['name']);
- if($oModule instanceof iBxDolContentInfoService){
- if (!BxDolRequest::serviceExists($aModule['name'], 'act_as_profile'))
- continue;
- $aResult[$aModule['name']] = $aModule['title'];
- }
- }
- return $aResult;
- }
-
- public function serviceGetOptionsCaptchaDefault()
- {
- $aResults = [];
- $aObjects = BxDolCaptchaQuery::getObjects();
- foreach($aObjects as $aObject)
- $aResults[$aObject['object']] = $aObject['title'];
- return $aResults;
- }
- public function serviceGetOptionsEmbedDefault()
- {
- $aResults = array(
- '' => _t('_None')
- );
- $aObjects = BxDolEmbedQuery::getObjects();
- foreach($aObjects as $aObject)
- $aResults[$aObject['object']] = _t($aObject['title']);
- return $aResults;
- }
- public function serviceGetOptionsLocationFieldDefault()
- {
- $aResults = array();
- $aObjects = BxDolLocationFieldQuery::getObjects();
- foreach($aObjects as $aObject)
- $aResults[$aObject['object']] = _t($aObject['title']);
- return $aResults;
- }
- public function serviceGetOptionsLocationMapDefault()
- {
- $aResults = array();
- $aObjects = BxDolLocationMapQuery::getObjects();
- foreach($aObjects as $aObject)
- $aResults[$aObject['object']] = _t($aObject['title']);
- return $aResults;
- }
- public function serviceGetOptionsPushDefault()
- {
- $aResults = [
- '' => _t('_None')
- ];
- $aObjects = BxDolPushQuery::getObjects();
- foreach($aObjects as $aObject)
- $aResults[$aObject['object']] = $aObject['title'];
- return $aResults;
- }
- public function serviceGetOptionsSmsDefault()
- {
- $aResults = [
- '' => _t('_None')
- ];
- $aObjects = BxDolSmsQuery::getObjects();
- foreach($aObjects as $aObject)
- $aResults[$aObject['object']] = $aObject['title'];
- return $aResults;
- }
- public function serviceGetOptionsSocketsFieldDefault()
- {
- $aResults = [];
- $aObjects = ['sys_sockets_disabled', 'sys_sockets_soketi'];
- foreach($aObjects as $sObject)
- $aResults[$sObject] = _t('_adm_stg_cpt_option_sys_sockets_type_' . $sObject);
- return $aResults;
- }
- public function serviceGetOptionsLocationLeafletGetProviders()
- {
- return BxDolLocationMapLeaflet::getProviders();
- }
- public function serviceGetOptionsRelations()
- {
- $aModules = BxDolModuleQuery::getInstance()->getModulesBy(array('type' => 'modules', 'active' => 1));
- $aProfiles = array();
- foreach($aModules as $aModule) {
- $sMethod = 'act_as_profile';
- if(!BxDolRequest::serviceExists($aModule['name'], $sMethod) || !BxDolService::call($aModule['name'], $sMethod))
- continue;
- $aProfiles[$aModule['name']] = _t('_' . $aModule['name']);
- }
- $aResults = array();
- foreach($aProfiles as $sName1 => $sTitle1)
- foreach($aProfiles as $sName2 => $sTitle2)
- $aResults[$sName1 . '_' . $sName2] = $sTitle1 . ' - ' . $sTitle2;
- return $aResults;
- }
- public function serviceGetOptionsCfProhibited()
- {
- return BxDolFormQuery::getDataItems('sys_content_filter');
- }
- public function serviceGetOptionsCfUnauthenticated()
- {
- return BxDolFormQuery::getDataItems('sys_content_filter');
- }
- public function serviceGetOptionsTaiwindDefault()
- {
- $sPath = BX_DIRECTORY_PATH_PLUGINS_PUBLIC . 'tailwind/css';
- $aExcludes = ['.', '..', 'tailwind.css'];
- $aResults = [];
- if(($oHandle = opendir($sPath)) !== false) {
- while(($sFile = readdir($oHandle)) !== false) {
- if(in_array($sFile, $aExcludes))
- continue;
- if(($oHandlerFile = fopen($sPath . '/' . $sFile, 'r')) === false)
- continue;
- if(($sContent = fread($oHandlerFile, 1024)) !== false && strpos($sContent, '@tailwind base') === false)
- $aResults[$sFile] = $sFile;
- fclose($oHandlerFile);
- }
- closedir($oHandle);
- }
- /**
- * Disabled for now, because CDN and custom compiled build with own styles
- * don't work correctly together.
- *
- * $aResults['cdn'] = _t('_adm_stg_cpt_option_sys_css_tailwind_default_cdn');
- */
- return $aResults;
- }
- public function serviceGetOptionsIconsetDefault()
- {
- $aObjects = BxDolIconsetQuery::getObjects();
- foreach($aObjects as $aObject)
- $aResults[$aObject['object']] = $aObject['title'];
- return $aResults;
- }
- public function serviceGetOptionsApiRootPageGuest()
- {
- $sKey = '_adm_stg_cpt_option_sys_api_root_page_';
- return [
- 'home' => _t($sKey .'home'),
- 'splash' => _t($sKey . 'splash')
- ];
- }
- public function serviceGetOptionsApiRootPageMember()
- {
- $sKey = '_adm_stg_cpt_option_sys_api_root_page_';
- return [
- 'home' => _t($sKey .'home'),
- 'dashboard' => _t($sKey . 'dashboard'),
- 'profile' => _t($sKey . 'profile')
- ];
- }
- public function serviceGetOptionsApiMenuTop()
- {
- $aMenus = BxDolMenuQuery::getMenuObjects();
- $aResults = ['' => _t('_sys_please_select')];
- foreach($aMenus as $aMenu)
- if($aMenu['module'] == 'system')
- $aResults[$aMenu['object']] = _t($aMenu['title']);
- return $aResults;
- }
- public function serviceGetOptionsApiContextSwitcher()
- {
- $aContexts = bx_srv('system', 'get_modules_by_type', ['context']);
- $aResults = ['' => _t('_None')];
- foreach($aContexts as $aContext)
- $aResults[$aContext['name']] = _t('_' . $aContext['name']);
- return $aResults;
- }
- public function serviceGetOptionsApiContextConnection()
- {
- $aConnections = ['subscriptions', 'fans', 'participants'];
- $aResults = ['' => _t('_sys_please_select')];
- foreach($aConnections as $sConnection)
- $aResults[$sConnection] = _t('_adm_stg_cpt_option_sys_api_cnt_cnn_' . $sConnection);
- return $aResults;
- }
- public function serviceGetOptionsAgentsModel()
- {
- return ['' => _t('_Select_one')] + BxDolAi::getInstance()->getModels(['active' => true]);
- }
- public function serviceGetOptionsAgentsProfile($bSelectOne = true, $sSelectOneLangKey = '_Select_one')
- {
- $aResult = [];
- if($bSelectOne)
- $aResult[] = ['key' => '', 'value' => _t($sSelectOneLangKey)];
- $aAccountsIds = BxDolAccountQuery::getInstance()->getOperators();
- foreach($aAccountsIds as $iAccountId) {
- $aProfilesIds = BxDolAccount::getInstance($iAccountId)->getProfilesIds(true, false);
- foreach($aProfilesIds as $iProfileId) {
- $oProfile = BxDolProfile::getInstance($iProfileId);
- $sProfileModule = false === $oProfile ? '' : $oProfile->getModule();
- if ($sProfileModule && ($sProfileModule != 'system' || ($sProfileModule == 'system' && empty($oProfile->getAccountObject()->getEmail())))) {
- $aResult[] = [
- 'key' => $iProfileId,
- 'value' => _t('_sys_profile_with_type', $oProfile->getDisplayName(), $sProfileModule === 'system' ? 'System' : _t('_' . $sProfileModule))
- ];
- }
- }
- }
- return $aResult;
- }
- public function serviceRedirect($sUrl = false)
- {
- if (!getParam('sys_confirmation_before_redirect')) {
- BxDolTemplate::getInstance()->displayPageNotFound();
- exit;
- }
- if (false === $sUrl)
- $sUrl = bx_get('url');
- if (!$sUrl || !preg_match('@^https?://@', $sUrl)) {
- http_response_code(500);
- return MsgBox(_t('_error occured'));
- }
- else {
- $bSpam = null;
- /**
- * @hooks
- * @hookdef hook-system-check_spam_url 'system', 'check_spam_url' - hook to override sClass for search
- * - $unit_name - equals `system`
- * - $action - equals `check_spam_url`
- * - $object_id - not used
- * - $sender_id - logged account id
- * - $extra_params - array of additional params with the following array keys:
- * - `is_spam` - [bool] by ref, spam url or not, can be overridden in hook processing
- * - `content` - [string] by ref, url of link, can be overridden in hook processing
- * - `where` - [string] equal redirect
- * @hook @ref hook-system-check_spam_url
- */
- bx_alert('system', 'check_spam_url', 0, getLoggedId(), array(
- 'is_spam' => &$bSpam,
- 'content' => &$sUrl,
- 'is_spam_ref' => &$bSpam,
- 'content_ref' => &$sUrl,
- 'where' => 'redirect'
- ));
- $sLangKey = $bSpam ? '_sys_redirect_confirmation_harmful' : '_sys_redirect_confirmation';
- return BxDolTemplate::getInstance()->parseHtmlByName('redirect.html', [
- 'text' => _t($sLangKey, bx_process_output($sUrl), getParam('site_title')),
- 'url' => bx_js_string($sUrl, BX_ESCAPE_STR_APOS),
- ]);
- }
- }
- public function serviceSetBadges($iContentId, $sBadgesIds, $sModule)
- {
- $aSelectedBadges = explode(",", $sBadgesIds);
-
- $iPerformerId = bx_get_logged_profile_id();
- $aCheck = checkActionModule($iPerformerId, 'set badge', 'system', false);
- if(!isAdmin() && $aCheck[CHECK_ACTION_RESULT] !== CHECK_ACTION_RESULT_ALLOWED)
- return false;
- $oBadges = BxDolBadges::getInstance();
- $oBadges->delete([
- 'type' => 'by_module&object',
- 'object_id' => $iContentId,
- 'module' => $sModule
- ]);
- foreach ($aSelectedBadges as $iSelectedBadge)
- $oBadges->add($iSelectedBadge, $iContentId, $sModule);
- checkActionModule($iPerformerId, 'set badge', 'system', true);
- return true;
- }
-
- public function serviceGetBadge($aBadge, $bIsCompact = false)
- {
- $sClass = '';
- $sStyleFont = '';
- $sStyleBg = '';
- if ($aBadge['color'] == '')
- $aBadge['color'] = 'purple-600';
-
- if ($bIsCompact && $aBadge['icon'] != ''){
- $aBadge['is_icon_only'] = 1;
- }
- if ($aBadge['is_icon_only'] == 1){
- $sClass .= ' bx-badge-compact';
- if (substr_count($aBadge['color'], 'rgb('))
- $sStyleFont = 'color: ' . $aBadge['color'];
- else
- $sClass .= ' text-' . $aBadge['color'];
- }
- else{
- if (substr_count($aBadge['color'], 'rgb('))
- $sStyleBg = 'background-color: ' . $aBadge['color'];
- else
- $sClass .= ' bg-' . $aBadge['color'];
- }
-
- return BxDolTemplate::getInstance()->parseHtmlByName('badge.html', array(
- 'bx_if:content' => array(
- 'condition' => $aBadge['is_icon_only'] != '1',
- 'content' => array('content' => _t($aBadge['text'])),
- ),
- 'bx_if:icon' => array(
- 'condition' => $aBadge['icon'] != '',
- 'content' => array('content' => BxDolTemplate::getInstance()->getIcon($aBadge['icon'], array('class' => 'bx-badge-icon sys-colored', 'style' => $sStyleFont))),
- ),
- 'title' => $aBadge['text'],
- 'style_font' => $sStyleFont,
- 'style_bg' => $sStyleBg,
- 'class' => $sClass,
- )
- );
- }
-
- public function serviceGetFooter()
- {
- return BxDolTemplate::getInstance()->parseHtmlByName('footer.html', []);
- }
- public function serviceHomeRedirect()
- {
- header("Location:" . BX_DOL_URL_ROOT, true, 301);
- exit;
- }
- public function serviceProcessEmbed()
- {
- BxDolEmbed::getObjectInstance()->process();
- }
- public function serviceCallAgent($sType, $aAgent, $aParams)
- {
- $oAi = BxDolAi::getInstance();
- $mixedReply = $oAi->callAgent($sType, $aAgent, $aParams);
- // Async messenger agents run here from a background job: post the reply, nobody else will.
- if ('message' === $sType && is_string($mixedReply) && $mixedReply !== '')
- BxDolAiTrigger::getInstance('message')->replyToMessage($aAgent, $aParams, $mixedReply);
- return $mixedReply;
- }
- public function serviceCallAgentForFormInput($iAgentId)
- {
- return BxDolAiTrigger::getInstance('form-input')->handle($iAgentId);
- }
- public function serviceAiChat($iAgentId)
- {
- return BxDolAiTrigger::getInstance('chat')->handle($iAgentId);
- }
- /**
- * Composer image upload for the chat widget (`$_FILES['file']`).
- * → `{file_id, url, mime}` or `{error}`; the client sends the URL back as an image part of its next message.
- */
- public function serviceAiChatUpload($iAgentId)
- {
- return BxDolAiTrigger::getInstance('chat')->upload($iAgentId);
- }
- /**
- * The caller's own conversations with an agent — the "Chats" panel of the App
- * chat widget. Any context, base thread and `?chat=` partitions, newest first.
- *
- * API: `api.php?r=system/get_ai_chat_threads/TemplServices¶ms[]=<agent id>`
- * → `{threads: [{thread_id, chat, context_pid, context_name, status, closed_reason,
- * title, preview, messages_count, created_ts, updated_ts}]}`.
- * The row whose `chat` / context matches the widget (or the open one, when the
- * widget has no `?chat=`) is the live conversation; the rest are read-only —
- * see serviceGetAiChatThread.
- */
- public function serviceGetAiChatThreads($iAgentId)
- {
- return BxDolAiTrigger::getInstance('chat')->listThreads($iAgentId);
- }
- /**
- * One of the caller's earlier conversations, read-only.
- *
- * API: `api.php?r=system/get_ai_chat_thread/TemplServices¶ms[]=<agent id>¶ms[]=<thread id>`
- * → `{messages, status, closed_reason, artifacts}`; 403 for a thread of someone else.
- */
- public function serviceGetAiChatThread($iAgentId, $sThreadId = '')
- {
- return BxDolAiTrigger::getInstance('chat')->getThread($iAgentId, $sThreadId);
- }
- /**
- * a cut-down Studio > Agents for operators:
- * the list with on/off, chat history for manual/message agents and the
- * activity history (what the agent did) for event-driven ones.
- *
- * API: `api.php?r=system/get_ai_agents/TemplServices`
- * → `{agents: [{id, name, title, description, trigger, trigger_title, alert, active, async,
- * has_chat, model, profile: {id, name, url, thumb}, activity_count, activity_last, added}], studio_url}`
- */
- public function serviceGetAiAgents()
- {
- if (!isAdmin())
- return ['error' => _t('_sys_agents_unauthorized'), 'code' => 403];
- $oDb = BxDolDb::getInstance();
- $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");
- $aStats = BxDolAiActivity::statsByAgent();
- $aAgents = [];
- foreach ($aRows as $aRow) {
- $iId = (int)$aRow['id'];
- $aAgents[] = [
- 'id' => $iId,
- 'name' => (string)$aRow['name'],
- 'title' => (string)(!empty($aRow['title']) ? $aRow['title'] : $aRow['name']),
- 'description' => (string)($aRow['description'] ?? ''),
- 'trigger' => (string)$aRow['trigger'],
- 'trigger_title' => $this->_aiAgentTriggerTitle((string)$aRow['trigger']),
- 'alert' => (string)($aRow['alert'] ?? ''),
- 'active' => (int)$aRow['active'],
- 'async' => (int)($aRow['async'] ?? 0),
- 'has_chat' => in_array($aRow['trigger'], ['manual', 'message'], true) ? 1 : 0,
- 'model' => (string)($aRow['model_title'] ?? ''),
- 'profile' => $this->_aiAgentProfileInfo((int)$aRow['profile_id']),
- 'activity_count' => (int)($aStats[$iId]['count'] ?? 0),
- 'activity_last' => (int)($aStats[$iId]['last'] ?? 0),
- 'added' => (int)($aRow['added'] ?? 0),
- ];
- }
- return [
- 'agents' => $aAgents,
- 'studio_url' => bx_absolute_url('studio/agents.php?page=agents'),
- ];
- }
- /**
- * Page block with the same list, for operators only (everyone else gets an
- * empty block). Put it on the Dashboard or any page in Studio > Pages:
- * `{"module":"system","method":"get_block_ai_agents_admin","class":"TemplServices"}`.
- * The App renders it as the `ai_agents_admin` element; there is no HTML version.
- */
- public function serviceGetBlockAiAgentsAdmin()
- {
- if (!bx_is_api())
- return '';
- if (!isAdmin())
- return [];
- $aList = $this->serviceGetAiAgents();
- if (!is_array($aList) || isset($aList['error']))
- return [];
- // the operator chat (Studio > Settings > Agents) rides along as the first tab of
- // the same block, so the Dashboard needs one block, not two
- $aList['chat'] = null;
- $aList['chat_title'] = '';
- $iOperator = (int)getParam('sys_agents_operator_agent');
- if ($iOperator > 0) {
- $aOperatorBlock = $this->serviceGetBlockAiAgentOperator();
- if (is_array($aOperatorBlock) && !empty($aOperatorBlock[0]['data']) && is_array($aOperatorBlock[0]['data'])) {
- $aList['chat'] = $aOperatorBlock[0]['data'];
- $aOperator = BxDolAiQuery::getAgentObject($iOperator);
- $aList['chat_title'] = (string)(!empty($aOperator['title']) ? $aOperator['title'] : ($aOperator['name'] ?? ''));
- }
- }
- return [bx_api_get_block('ai_agents_admin', $aList)];
- }
- /**
- * API: `api.php?r=system/set_ai_agent_active/TemplServices¶ms[]=<agent id>¶ms[]=<0|1>`
- */
- public function serviceSetAiAgentActive($iAgentId, $iActive = 1)
- {
- if (!isAdmin())
- return ['error' => _t('_sys_agents_unauthorized'), 'code' => 403];
- $iAgentId = (int)$iAgentId;
- $aAgent = $iAgentId ? BxDolAiQuery::getAgentObject($iAgentId) : false;
- if (!$aAgent)
- return ['error' => _t('_sys_agents_agent_not_found'), 'code' => 404];
- $iActive = (int)$iActive ? 1 : 0;
- $oDb = BxDolDb::getInstance();
- $oDb->query("UPDATE `sys_agents_agents` SET `active` = :active WHERE `id` = :id", ['active' => $iActive, 'id' => $iAgentId]);
- $oDb->cleanCache('sys_agents_with_alert');
- $oDb->cleanMemory('sys_agents_with_form_' . (string)($aAgent['form_object'] ?? ''));
- return ['id' => $iAgentId, 'active' => $iActive];
- }
- /**
- * API: `api.php?r=system/get_ai_agent_activity/TemplServices¶ms[]=<agent id>¶ms[]=<start>¶ms[]=<limit>`
- * → `{items: [{id, action, tool, ok, text, summary, unit, object_id, url, added, added_formatted}], has_more}`
- */
- public function serviceGetAiAgentActivity($iAgentId, $iStart = 0, $iLimit = 50)
- {
- if (!isAdmin())
- return ['error' => _t('_sys_agents_unauthorized'), 'code' => 403];
- $iAgentId = (int)$iAgentId;
- if (!$iAgentId || !BxDolAiQuery::getAgentObject($iAgentId))
- return ['error' => _t('_sys_agents_agent_not_found'), 'code' => 404];
- $iLimit = max(1, min(200, (int)$iLimit));
- $aItems = BxDolAiActivity::listForAgent($iAgentId, (int)$iStart, $iLimit + 1);
- $bMore = count($aItems) > $iLimit;
- if ($bMore)
- array_pop($aItems);
- return ['items' => $aItems, 'has_more' => $bMore ? 1 : 0];
- }
- /**
- * Every conversation of an agent (all people, guests, contexts) — operators
- * only; the App counterpart of the Studio chat popup. Transcripts are not
- * included, see serviceGetAiAgentChatThread.
- *
- * API: `api.php?r=system/get_ai_agent_chat_threads/TemplServices¶ms[]=<agent id>`
- * → `{threads: [{thread_id, title, status, closed_reason, created_at, updated_at, messages_count, preview}]}`
- */
- public function serviceGetAiAgentChatThreads($iAgentId)
- {
- if (!isAdmin())
- return ['error' => _t('_sys_agents_unauthorized'), 'code' => 403];
- $iAgentId = (int)$iAgentId;
- $aAgent = $iAgentId ? BxDolAiQuery::getAgentObject($iAgentId) : false;
- if (!$aAgent)
- return ['error' => _t('_sys_agents_agent_not_found'), 'code' => 404];
- $aThreads = BxDolAiChat::getInstance()->listAgentChatThreads($aAgent);
- $aOut = [];
- foreach ($aThreads as $aThread) {
- $aMessages = is_array($aThread['messages'] ?? null) ? $aThread['messages'] : [];
- if (!$aMessages)
- continue;
- $sPreview = '';
- foreach (array_reverse($aMessages) as $aMessage) {
- foreach ((array)($aMessage['parts'] ?? []) as $aPart) {
- if (($aPart['type'] ?? '') === 'text' && trim((string)($aPart['content'] ?? '')) !== '') {
- $sPreview = trim(strip_tags((string)$aPart['content']));
- break 2;
- }
- }
- }
- if (mb_strlen($sPreview) > 160)
- $sPreview = mb_substr($sPreview, 0, 159) . '…';
- $aOut[] = [
- 'thread_id' => (string)$aThread['thread_id'],
- 'title' => (string)$aThread['title'],
- 'status' => (string)($aThread['status'] ?? 'opened'),
- 'closed_reason' => (string)($aThread['closed_reason'] ?? ''),
- 'created_at' => (string)($aThread['created_at'] ?? ''),
- 'updated_at' => (string)($aThread['updated_at'] ?? ''),
- 'messages_count' => count($aMessages),
- 'preview' => $sPreview,
- ];
- }
- return ['threads' => $aOut];
- }
- /**
- * API: `api.php?r=system/get_ai_agent_chat_thread/TemplServices¶ms[]=<agent id>¶ms[]=<thread id>`
- * → `{messages, status, closed_reason, artifacts}` — same message shape as get_ai_chat_thread.
- */
- public function serviceGetAiAgentChatThread($iAgentId, $sThreadId = '')
- {
- if (!isAdmin())
- return ['error' => _t('_sys_agents_unauthorized'), 'code' => 403];
- $iAgentId = (int)$iAgentId;
- $aAgent = $iAgentId ? BxDolAiQuery::getAgentObject($iAgentId) : false;
- if (!$aAgent)
- return ['error' => _t('_sys_agents_agent_not_found'), 'code' => 404];
- $oChat = BxDolAiChat::getInstance();
- $sThreadId = trim((string)$sThreadId);
- if ($sThreadId === '')
- return ['error' => _t('_sys_agents_agent_not_found'), 'code' => 404];
- $aMessages = $oChat->getChatHistoryUiMessagesByThread($aAgent, $sThreadId);
- if ($aMessages === false)
- return ['error' => _t('_sys_agents_agent_not_found'), 'code' => 404];
- $sReason = '';
- $oDb = BxDolDb::getInstance();
- if ($oDb->isFieldExists('sys_agents_chat_history', 'closed_reason'))
- $sReason = trim((string)$oDb->getOne("SELECT `closed_reason` FROM `sys_agents_chat_history` WHERE `thread_id` = :t", ['t' => $sThreadId]));
- return [
- 'messages' => is_array($aMessages) ? $aMessages : [],
- 'status' => $sReason !== '' ? 'closed' : 'opened',
- 'closed_reason' => $sReason,
- 'artifacts' => $oChat->getChatHistoryArtifactsByThread($aAgent, $sThreadId),
- ];
- }
- protected function _aiAgentTriggerTitle($sTrigger)
- {
- $sKey = '_sys_agents_field_trigger_' . str_replace('-', '_', (string)$sTrigger);
- $s = _t($sKey);
- return $s !== $sKey ? $s : (string)$sTrigger;
- }
- protected function _aiAgentProfileInfo($iProfileId)
- {
- $iProfileId = (int)$iProfileId;
- $oProfile = $iProfileId ? BxDolProfile::getInstance($iProfileId) : false;
- if (!$oProfile)
- return ['id' => $iProfileId, 'display_name' => $iProfileId ? '#' . $iProfileId : '', 'url' => false, 'url_avatar' => '', 'module' => ''];
- // same shape as the ai_agent block's agent_profile, so the App's Profile molecule can render it
- return BxDolProfile::getData($oProfile);
- }
- /**
- * Agent-written NEO mockup block (Studio: system / get_mockup_block / TemplServices).
- * The tree is written by the `mockup_upsert` tool into sys_pages_blocks_data for this block;
- * BxBasePage::_getBlockService passes the block id as the only param.
- * @param int $iBlockId sys_pages_blocks.id
- * @return array API block of type `mockup`
- */
- public function serviceGetMockupBlock($iBlockId = 0)
- {
- $aTree = BxDolAIToolMockup::getTree((int)$iBlockId);
- if (!$aTree) {
- $aTree = [
- 'type' => 'view',
- 'className' => 'gap-4 w-full',
- 'children' => [
- [
- 'type' => 'text',
- 'className' => 'text-muted-foreground',
- 'text' => 'No mockup yet. Ask the mockup agent to generate one for this page.',
- ],
- ],
- ];
- }
- return [bx_api_get_block('mockup', $aTree)];
- }
- }
- /** @} */
|