1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
document.php
См. документацию.
1<?php
2
9
14{
15 const PARAM_TAGRET_USER = 'TargetUser';
16 const PARAM_MODIFIED_DOCUMENT_FIELDS = 'ModifiedDocumentField';
17 const PARAM_USE_FORCED_TRACKING = 'UseForcedTracking';
18 const PARAM_IGNORE_SIMULTANEOUS_PROCESSES_LIMIT = 'IgnoreSimultaneousProcessesLimit';
19 const PARAM_DOCUMENT_EVENT_TYPE = 'DocumentEventType';
20 const PARAM_DOCUMENT_TYPE = '__DocumentType';
21 const PARAM_PRE_GENERATED_WORKFLOW_ID = 'PreGeneratedWorkflowId';
22 const PARAM_USED_DOCUMENT_FIELDS = 'UsedDocumentField';
23
24 public static function migrateDocumentType($oldType, $newType)
25 {
26 $templateIds = array();
27 $db = CBPWorkflowTemplateLoader::GetList(array(), array("DOCUMENT_TYPE" => $oldType), false, false, array("ID"));
28 while ($ar = $db->Fetch())
29 $templateIds[] = $ar["ID"];
30
31 foreach ($templateIds as $id)
32 CBPWorkflowTemplateLoader::Update($id, array("DOCUMENT_TYPE" => $newType));
33
34 if (count($templateIds) > 0)
35 {
36 CBPHistoryService::MigrateDocumentType($oldType, $newType, $templateIds);
37 CBPStateService::MigrateDocumentType($oldType, $newType, $templateIds);
39 }
40 }
41
108 public static function getDocumentStates($documentType, $documentId = null)
109 {
110 $arDocumentStates = array();
111
112 if ($documentId != null)
113 $arDocumentStates = CBPStateService::GetDocumentStates($documentId);
114
115 $arTemplateStates = CBPWorkflowTemplateLoader::GetDocumentTypeStates(
116 $documentType,
118 );
119
120 return ($arDocumentStates + $arTemplateStates);
121 }
122
123 public static function getActiveStates(array $documentId, $limit = 0)
124 {
125 $documentId = CBPHelper::ParseDocumentId($documentId);
127
128 if (!$workflowIds)
129 {
130 return [];
131 }
132
133 if ($limit > 0 && count($workflowIds) > $limit)
134 {
135 $workflowIds = array_slice($workflowIds, 0, $limit);
136 }
137
138 return CBPStateService::GetDocumentStates($documentId, $workflowIds);
139 }
140
148 public static function getDocumentState($documentId, $workflowId)
149 {
150 $arDocumentState = CBPStateService::GetDocumentStates($documentId, $workflowId);
151 return $arDocumentState;
152 }
153
154 public static function mergeDocuments($firstDocumentId, $secondDocumentId)
155 {
156 CBPStateService::MergeStates($firstDocumentId, $secondDocumentId);
157 Bizproc\Workflow\Entity\WorkflowInstanceTable::mergeByDocument($firstDocumentId, $secondDocumentId);
158 CBPHistoryService::MergeHistory($firstDocumentId, $secondDocumentId);
159 }
160
171 public static function getAllowableEvents($userId, $arGroups, $arState, $appendExtendedGroups = false)
172 {
173 if (!is_array($arState))
174 {
175 throw new CBPArgumentTypeException('arState');
176 }
177 if (!is_array($arGroups))
178 {
179 throw new CBPArgumentTypeException('arGroups');
180 }
181
182 $arGroups = CBPHelper::convertToExtendedGroups($arGroups);
183 if ($appendExtendedGroups)
184 {
185 $arGroups = array_merge($arGroups, CBPHelper::getUserExtendedGroups($userId));
186 }
187 if (!in_array('group_u' . $userId, $arGroups, true))
188 {
189 $arGroups[] = 'group_u' . $userId;
190 }
191
192 $allowableEvents = [];
193 if (is_array($arState['STATE_PARAMETERS']) && $arState['STATE_PARAMETERS'])
194 {
195 foreach ($arState['STATE_PARAMETERS'] as $parameter)
196 {
197 $parameter['PERMISSION'] = CBPHelper::convertToExtendedGroups($parameter['PERMISSION']);
198 if (!$parameter['PERMISSION'] || array_intersect($arGroups, $parameter['PERMISSION']))
199 {
200 $allowableEvents[] = [
201 'NAME' => $parameter['NAME'],
202 'TITLE' => !empty($parameter['TITLE']) ? $parameter['TITLE'] : $parameter['NAME'],
203 ];
204 }
205 }
206 }
207
208 return $allowableEvents;
209 }
210
211 public static function addDocumentToHistory($parameterDocumentId, $name, $userId)
212 {
213 [$moduleId, $entity, $documentType] = CBPHelper::ParseDocumentId($parameterDocumentId);
214
215 if ($moduleId <> '')
216 CModule::IncludeModule($moduleId);
217
218 if (!class_exists($entity))
219 return false;
220
221 $runtime = CBPRuntime::GetRuntime();
222 $runtime->StartRuntime();
223
224 $historyService = $runtime->GetService("HistoryService");
225 $documentService = $runtime->GetService("DocumentService");
226
227 $userId = intval($userId);
228
229 $historyIndex = $historyService->AddHistory(
230 array(
231 "DOCUMENT_ID" => $parameterDocumentId,
232 "NAME" => "New",
233 "DOCUMENT" => null,
234 "USER_ID" => $userId,
235 )
236 );
237
238 $arDocument = $documentService->GetDocumentForHistory($parameterDocumentId, $historyIndex);
239 if (!is_array($arDocument))
240 return false;
241
242 $historyService->UpdateHistory(
243 $historyIndex,
244 array(
245 "NAME" => $name,
246 "DOCUMENT" => $arDocument,
247 )
248 );
249
250 return $historyIndex;
251 }
252
266 public static function getAllowableOperations($userId, $arGroups, $arStates, $appendExtendedGroups = false)
267 {
268 if (!is_array($arStates))
269 throw new CBPArgumentTypeException("arStates");
270 if (!is_array($arGroups))
271 throw new CBPArgumentTypeException("arGroups");
272
273 $arGroups = CBPHelper::convertToExtendedGroups($arGroups);
274 if ($appendExtendedGroups)
275 {
276 $arGroups = array_merge($arGroups, CBPHelper::getUserExtendedGroups($userId));
277 }
278 if (!in_array("group_u".$userId, $arGroups))
279 $arGroups[] = "group_u".$userId;
280
281 $result = null;
282
283 foreach ($arStates as $arState)
284 {
285 if (is_array($arState["STATE_PERMISSIONS"]) && count($arState["STATE_PERMISSIONS"]) > 0)
286 {
287 if ($result == null)
288 $result = array();
289
290 foreach ($arState["STATE_PERMISSIONS"] as $operation => $arOperationGroups)
291 {
292 $arOperationGroups = CBPHelper::convertToExtendedGroups($arOperationGroups);
293
294 if (count(array_intersect($arGroups, $arOperationGroups)) > 0)
295 $result[] = mb_strtolower($operation);
296 }
297 }
298 }
299
300 return $result;
301 }
302
316 public static function canOperate($operation, $userId, $arGroups, $arStates)
317 {
318 $operation = trim($operation);
319 if ($operation == '')
320 throw new CBPArgumentNullException("operation");
321
322 $operations = self::GetAllowableOperations($userId, $arGroups, $arStates);
323 if ($operations === null)
324 return true;
325
326 return in_array($operation, $operations);
327 }
328
339 public static function startWorkflow($workflowTemplateId, $documentId, $parameters, &$errors, $parentWorkflow = null)
340 {
341 $errors = [];
342 $parameters = static::prepareWorkflowParameters($workflowTemplateId, $parameters);
343
344 try
345 {
346 $wi = CBPRuntime::GetRuntime()->createWorkflow($workflowTemplateId, $documentId, $parameters, $parentWorkflow);
347 $wi->start();
348
349 return $wi->GetInstanceId();
350 }
351 catch (Exception $e)
352 {
353 $errors[] = [
354 "code" => $e->getCode(),
355 "message" => $e->getMessage(),
356 "file" => $e->getFile() . " [" . $e->getLine() . "]",
357 ];
358 }
359
360 return null;
361 }
362
363 public static function startDebugWorkflow($workflowTemplateId, $documentId, $parameters, &$errors): ?string
364 {
365 $errors = [];
366 $runtime = CBPRuntime::GetRuntime(true);
367
368 $parameters = static::prepareWorkflowParameters($workflowTemplateId, $parameters);
369
370 try
371 {
372 $workflow = $runtime->createDebugWorkflow($workflowTemplateId, $documentId, $parameters);
373 $workflow->Start();
374
375 return $workflow->getInstanceId();
376 }
377 catch (Exception $e)
378 {
379 $errors[] = array(
380 "code" => $e->getCode(),
381 "message" => $e->getMessage(),
382 "file" => $e->getFile()." [".$e->getLine()."]"
383 );
384 }
385
386 return null;
387 }
388
389 private static function prepareWorkflowParameters($workflowTemplateId, $parameters): array
390 {
391 static $usagesCache = [];
392
393 if (!is_array($parameters))
394 {
395 $parameters = [$parameters];
396 }
397
398 if (!array_key_exists(static::PARAM_TAGRET_USER, $parameters))
399 {
400 $currentUserId = Main\Engine\CurrentUser::get()->getId();
401 $parameters[static::PARAM_TAGRET_USER] = isset($currentUserId) ? "user_{$currentUserId}" : null;
402 }
403
404 if (!isset($parameters[static::PARAM_MODIFIED_DOCUMENT_FIELDS]))
405 {
406 $parameters[static::PARAM_MODIFIED_DOCUMENT_FIELDS] = false;
407 }
408
409 if (!isset($parameters[static::PARAM_DOCUMENT_EVENT_TYPE]))
410 {
411 $parameters[static::PARAM_DOCUMENT_EVENT_TYPE] = CBPDocumentEventType::None;
412 }
413
414 if (!isset($parameters[static::PARAM_PRE_GENERATED_WORKFLOW_ID]))
415 {
416 $parameters[static::PARAM_PRE_GENERATED_WORKFLOW_ID] = CBPRuntime::generateWorkflowId();
417 }
418
419 if (!isset($usagesCache[$workflowTemplateId]))
420 {
421 $tpl = WorkflowTemplateTable::getById($workflowTemplateId)->fetchObject();
422 if ($tpl)
423 {
424 try
425 {
426 $usages = $tpl->collectUsages();
427 $usagesCache[$workflowTemplateId] = $usages->getValuesBySourceType(
428 SourceType::DocumentField
429 );
430 }
431 catch (\Throwable $e)
432 {
433 $usagesCache[$workflowTemplateId] = [];
434 }
435 }
436 }
437
438 $parameters[static::PARAM_USED_DOCUMENT_FIELDS] = $usagesCache[$workflowTemplateId] ?? [];
439
440 return $parameters;
441 }
442
452 public static function autoStartWorkflows($documentType, $autoExecute, $documentId, $arParameters, &$arErrors)
453 {
454 static $usagesCache = [];
455 $arErrors = array();
456
457 $runtime = CBPRuntime::GetRuntime();
458
459 if (!is_array($arParameters))
460 $arParameters = array($arParameters);
461
462 if (!isset($arParameters[static::PARAM_TAGRET_USER]))
463 $arParameters[static::PARAM_TAGRET_USER] = is_object($GLOBALS["USER"]) ? "user_".intval($GLOBALS["USER"]->GetID()) : null;
464
465 if (!isset($arParameters[static::PARAM_MODIFIED_DOCUMENT_FIELDS]))
466 $arParameters[static::PARAM_MODIFIED_DOCUMENT_FIELDS] = false;
467
468 $arParameters[static::PARAM_DOCUMENT_EVENT_TYPE] = $autoExecute;
469
470 $templates = CBPWorkflowTemplateLoader::SearchTemplatesByDocumentType($documentType, $autoExecute);
471 foreach ($templates as $template)
472 {
473 try
474 {
475 if (!isset($usagesCache[$template['ID']]))
476 {
477 $tpl = WorkflowTemplateTable::getById($template['ID'])->fetchObject();
478 if ($tpl)
479 {
480 $usages = $tpl->collectUsages();
481 $usagesCache[$template['ID']] = $usages->getValuesBySourceType(
482 SourceType::DocumentField
483 );
484 }
485 }
486
487 $arParameters[static::PARAM_USED_DOCUMENT_FIELDS] = $usagesCache[$template['ID']] ?? [];
488
489 $wi = $runtime->CreateWorkflow($template['ID'], $documentId, $arParameters);
490 $wi->Start();
491 }
492 catch (Exception $e)
493 {
494 $arErrors[] = array(
495 "code" => $e->getCode(),
496 "message" => $e->getMessage(),
497 "file" => $e->getFile()." [".$e->getLine()."]"
498 );
499 }
500 }
501 }
502
511 public static function sendExternalEvent($workflowId, $workflowEvent, $arParameters, &$arErrors)
512 {
513 $arErrors = array();
514
515 try
516 {
517 CBPRuntime::SendExternalEvent($workflowId, $workflowEvent, $arParameters);
518 }
519 catch(Exception $e)
520 {
521 $arErrors[] = array(
522 "code" => $e->getCode(),
523 "message" => $e->getMessage(),
524 "file" => $e->getFile()." [".$e->getLine()."]"
525 );
526 }
527 }
528
537 public static function terminateWorkflow($workflowId, $documentId, &$arErrors, $stateTitle = '')
538 {
539 $arErrors = array();
540
541 $runtime = CBPRuntime::GetRuntime();
542
543 try
544 {
545 $workflow = $runtime->GetWorkflow($workflowId, true);
546 if ($documentId)
547 {
548 $d = $workflow->GetDocumentId();
549 if ($d[0] != $documentId[0] || $d[1] != $documentId[1] || mb_strtolower($d[2]) !== mb_strtolower($documentId[2]))
550 throw new CBPArgumentOutOfRangeException(GetMessage("BPCGDOC_INVALID_WF_MSGVER_1"));
551 }
552 $workflow->Terminate(null, $stateTitle);
553 }
554 catch(Exception $e)
555 {
556 $arErrors[] = array(
557 "code" => $e->getCode(),
558 "message" => $e->getMessage(),
559 "file" => $e->getFile()." [".$e->getLine()."]"
560 );
561 return false;
562 }
563 return true;
564 }
565
566 public static function killWorkflow($workflowId, $terminate = true, $documentId = null)
567 {
568 $errors = array();
569 if ($terminate)
570 static::TerminateWorkflow($workflowId, $documentId, $errors);
571
572 if (!$errors)
573 {
575 CBPTaskService::DeleteByWorkflow($workflowId);
576 CBPStateService::DeleteWorkflow($workflowId);
579
580 if (!Bizproc\Debugger\Session\Manager::isDebugWorkflow($workflowId))
581 {
582 CBPTrackingService::DeleteByWorkflow($workflowId);
583 }
584
585 $event = new Event('bizproc', 'onAfterWorkflowKill', ['ID' => $workflowId]);
587 }
588
589 return $errors;
590 }
591
597 public static function onDocumentDelete($documentId, &$errors)
598 {
599 $errors = [];
600
602 foreach ($instanceIds as $instanceId)
603 {
604 static::TerminateWorkflow($instanceId, $documentId, $errors);
605 }
606
608 if ($debugSession && $debugSession->isFixedDocument($documentId))
609 {
610 Bizproc\Debugger\Listener::getInstance()->onDocumentDeleted();
611 }
612
613 \CBPHistoryService::DeleteByDocument($documentId);
614
616
617 // Deferred deletion
619
620 //touch runtime
621 CBPRuntime::getRuntime()->onDocumentDelete($documentId);
622 }
623
624 public static function postTaskForm($arTask, $userId, $arRequest, &$arErrors, $userName = "")
625 {
626 $activity = $arTask['ACTIVITY'] ?? '';
627
628 if (is_string($activity) && is_array($arTask) && Bizproc\Task\Manager::hasTask($activity))
629 {
630 $task = Bizproc\Task\Manager::getTask($activity, $arTask, (int)$userId);
631 $result = $task?->postTaskForm(is_array($arRequest) ? $arRequest : []);
632 if (!$result || !$result->isSuccess())
633 {
634 $arErrors = [];
635 foreach ($result->getErrors() as $error)
636 {
637 $arErrors[] = [
638 'code' => $error->getCode(),
639 'message' => $error->getMessage(),
640 'file' => null,
641 'customData' => $error->getCustomData(),
642 ];
643 }
644
645 return false;
646 }
647
648 return true;
649 }
650
651 $originalUserId = CBPTaskService::getOriginalTaskUserId($arTask['ID'], $userId);
652
653 return CBPActivity::CallStaticMethod(
654 $activity,
655 'PostTaskForm',
656 [$arTask, $originalUserId, $arRequest, &$arErrors, $userName, $userId]
657 );
658 }
659
660 public static function showTaskForm($arTask, $userId, $userName = "", $arRequest = null)
661 {
662 return CBPActivity::CallStaticMethod(
663 $arTask["ACTIVITY"],
664 "ShowTaskForm",
665 array(
666 $arTask,
667 $userId,
668 $userName,
669 $arRequest
670 )
671 );
672 }
673
681 public static function setTasksUserStatus($userId, $status, $ids = array(), &$errors = array())
682 {
683 $filter = array(
684 'USER_ID' => $userId,
685 'STATUS' => CBPTaskStatus::Running,
686 'USER_STATUS' => CBPTaskUserStatus::Waiting,
687 );
688 if ($ids)
689 {
690 $ids = array_filter(array_map('intval', (array)$ids));
691 if ($ids)
692 $filter['ID'] = $ids;
693 }
694
696 $filter,
697 false,
698 false,
699 array('ID', 'NAME', 'WORKFLOW_ID', 'ACTIVITY', 'ACTIVITY_NAME', 'IS_INLINE'));
700 while ($task = $iterator->fetch())
701 {
702 if ($task['IS_INLINE'] == 'Y')
703 {
704 $taskErrors = array();
705 self::PostTaskForm($task, $userId, array('INLINE_USER_STATUS' => $status), $taskErrors);
706 if (!empty($taskErrors))
707 foreach ($taskErrors as $error)
708 $errors[] = GetMessage('BPCGDOC_ERROR_ACTION_MSGVER_1', array('#NAME#' => $task['NAME'], '#ERROR#' => $error['message']));
709 }
710 else
711 $errors[] = GetMessage('BPCGDOC_ERROR_TASK_IS_NOT_INLINE_MSGVER_1', array('#NAME#' => $task['NAME']));
712
713 }
714 return true;
715 }
716
725 public static function delegateTasks($fromUserId, $toUserId, $ids = array(), &$errors = array(), $allowedDelegationType = null)
726 {
727 $filter = [
728 'USER_ID' => $fromUserId,
729 'STATUS' => CBPTaskStatus::Running,
730 'USER_STATUS' => CBPTaskUserStatus::Waiting,
731 ];
732
733 if ($ids)
734 {
735 $ids = array_filter(array_map('intval', (array)$ids));
736 if ($ids)
737 {
738 $filter['ID'] = $ids;
739 }
740 }
741
742 $isSinglePostfix = count($ids) === 1 ? '_SINGLE_MSGVER_1' : '_MSGVER_1';
743
745 array('ID'=>'ASC'),
746 $filter,
747 false,
748 false,
749 array('ID', 'NAME', 'WORKFLOW_ID', 'ACTIVITY_NAME', 'DELEGATION_TYPE')
750 );
751 $found = false;
752 $trackingService = null;
753 $sendImNotify = (CModule::IncludeModule("im"));
754 $workflowIdsToSync = [];
755
756 while ($task = $iterator->fetch())
757 {
758 if ((int)$task['DELEGATION_TYPE'] === CBPTaskDelegationType::ExactlyNone)
759 {
760 $errors[] = Main\Localization\Loc::getMessage('BPCGDOC_ERROR_DELEGATE_2_SINGLE_MSGVER_1');
761
762 continue;
763 }
764
765 if ($allowedDelegationType && !in_array((int)$task['DELEGATION_TYPE'], $allowedDelegationType, true))
766 {
768 'BPCGDOC_ERROR_DELEGATE_' . $task['DELEGATION_TYPE'] . $isSinglePostfix,
769 ['#NAME#' => $task['NAME']],
770 );
771 }
772 elseif (!CBPTaskService::delegateTask($task['ID'], $fromUserId, $toUserId))
773 {
774 $errors[] = GetMessage('BPCGDOC_ERROR_DELEGATE' . $isSinglePostfix, ['#NAME#' => $task['NAME']]);
775 }
776 else
777 {
778 if (!$found)
779 {
780 $runtime = CBPRuntime::GetRuntime();
781 $runtime->StartRuntime();
783 $trackingService = $runtime->GetService('TrackingService');
784 }
785 $found = true;
786
787 $trackingService->Write(
788 $task['WORKFLOW_ID'],
790 $task['ACTIVITY_NAME'],
793 GetMessage('BPCGDOC_DELEGATE_LOG_TITLE'),
794 GetMessage('BPCGDOC_DELEGATE_LOG_MSGVER_1', array(
795 '#NAME#' => $task['NAME'],
796 '#FROM#' => '{=user:user_'.$fromUserId.'}',
797 '#TO#' => '{=user:user_'.$toUserId.'}'
798 ))
799 );
800 $workflowIdsToSync[$task['WORKFLOW_ID']] = true;
801
802 if ($sendImNotify)
803 {
805 "MESSAGE_TYPE" => IM_MESSAGE_SYSTEM,
806 'FROM_USER_ID' => $fromUserId,
807 'TO_USER_ID' => $toUserId,
808 "NOTIFY_TYPE" => IM_NOTIFY_FROM,
809 "NOTIFY_MODULE" => "bizproc",
810 "NOTIFY_EVENT" => "delegate_task",
811 "NOTIFY_TAG" => "BIZPROC|TASK|".$task['ID'],
812 'MESSAGE' => GetMessage('BPCGDOC_DELEGATE_NOTIFY_TEXT_MSGVER_1', array(
813 '#TASK_URL#' => '/company/personal/bizproc/'.(int)$task['ID'].'/',
814 '#TASK_NAME#' => $task['NAME']
815 ))
816 ));
817 }
818 }
819 }
820
821 if ($workflowIdsToSync)
822 {
823 foreach (array_keys($workflowIdsToSync) as $workflowId)
824 {
825 Bizproc\Workflow\Entity\WorkflowUserTable::syncOnTaskUpdated($workflowId);
826 }
827 }
828
829 return $found;
830 }
831
832 public static function getTaskControls($arTask, $userId = 0)
833 {
834 $activity = $arTask['ACTIVITY'] ?? '';
835
836 if (is_string($activity) && is_array($arTask) && Bizproc\Task\Manager::hasTask($activity))
837 {
838 return Bizproc\Task\Manager::getTask($activity, $arTask, (int)$userId)?->getTaskControls();
839 }
840
841 return CBPActivity::CallStaticMethod($activity, 'getTaskControls', [$arTask, $userId]);
842 }
843
853 public static function startWorkflowParametersValidate($templateId, $arWorkflowParameters, $documentType, &$arErrors)
854 {
855 $arErrors = array();
856
857 $templateId = intval($templateId);
858 if ($templateId <= 0)
859 {
860 $arErrors[] = array(
861 "code" => "",
862 "message" => GetMessage("BPCGDOC_EMPTY_WD_ID_MSGVER_1"),
863 );
864 return array();
865 }
866
867 if (!isset($arWorkflowParameters) || !is_array($arWorkflowParameters))
868 $arWorkflowParameters = array();
869
870 $arWorkflowParametersValues = array();
871
872 $arRequest = $_REQUEST;
873 foreach ($_FILES as $k => $v)
874 {
875 if (array_key_exists("name", $v))
876 {
877 if (is_array($v["name"]))
878 {
879 $ks = array_keys($v["name"]);
880 for ($i = 0, $cnt = count($ks); $i < $cnt; $i++)
881 {
882 $ar = array();
883 foreach ($v as $k1 => $v1)
884 $ar[$k1] = $v1[$ks[$i]];
885
886 $arRequest[$k][] = $ar;
887 }
888 }
889 else
890 {
891 $arRequest[$k] = $v;
892 }
893 }
894 }
895
896 if (count($arWorkflowParameters) > 0)
897 {
898 $arErrorsTmp = array();
899 $ar = array();
900
901 foreach ($arWorkflowParameters as $parameterKey => $arParameter)
902 {
903 $key = "bizproc" . $templateId . "_" . $parameterKey;
904 $ar[$parameterKey] = $arRequest[$key] ?? null;
905 }
906
907 $arWorkflowParametersValues = CBPWorkflowTemplateLoader::CheckWorkflowParameters(
908 $arWorkflowParameters,
909 $ar,
910 $documentType,
911 $arErrors
912 );
913 }
914
915 return $arWorkflowParametersValues;
916 }
917
927 public static function startWorkflowParametersShow($templateId, $arWorkflowParameters, $formName, $bVarsFromForm, $documentType = null)
928 {
929 $templateId = intval($templateId);
930 if ($templateId <= 0)
931 return;
932
933 if (!isset($arWorkflowParameters) || !is_array($arWorkflowParameters))
934 $arWorkflowParameters = array();
935
936 if ($formName == '')
937 $formName = "start_workflow_form1";
938
939 if ($documentType == null)
940 {
941 $dbResult = CBPWorkflowTemplateLoader::GetList(array(), array("ID" => $templateId), false, false, array("ID", "MODULE_ID", "ENTITY", "DOCUMENT_TYPE"));
942 if ($arResult = $dbResult->Fetch())
943 $documentType = $arResult["DOCUMENT_TYPE"];
944 }
945
946 $arParametersValues = array();
947 $keys = array_keys($arWorkflowParameters);
948 foreach ($keys as $key)
949 {
950 $v = ($bVarsFromForm ? $_REQUEST["bizproc".$templateId."_".$key] : $arWorkflowParameters[$key]["Default"]);
951 if (!is_array($v))
952 {
953 $arParametersValues[$key] = $v;
954 }
955 else
956 {
957 $keys1 = array_keys($v);
958 foreach ($keys1 as $key1)
959 $arParametersValues[$key][$key1] = $v[$key1];
960 }
961 }
962
963 $runtime = CBPRuntime::GetRuntime();
964 $runtime->StartRuntime();
965 $documentService = $runtime->GetService("DocumentService");
966
967 foreach ($arWorkflowParameters as $parameterKey => $arParameter)
968 {
969 $parameterKeyExt = "bizproc".$templateId."_".$parameterKey;
970 ?><tr>
971 <td align="right" width="40%" valign="top" class="field-name"><?= $arParameter["Required"] ? "<span class=\"required\">*</span> " : ""?><?= htmlspecialcharsbx($arParameter["Name"]) ?>:<?if ($arParameter["Description"] <> '') echo "<br /><small>".htmlspecialcharsbx($arParameter["Description"])."</small><br />";?></td>
972 <td width="60%" valign="top"><?
973 echo $documentService->GetFieldInputControl(
974 $documentType,
975 $arParameter,
976 ['Form' => $formName, 'Field' => $parameterKeyExt],
977 $arParametersValues[$parameterKey] ?? null,
978 false,
979 true
980 );
981 ?></td></tr><?
982 }
983 }
984
985 public static function addShowParameterInit($module, $type, $document_type, $entity = "", $document_id = '')
986 {
987 $GLOBALS["BP_AddShowParameterInit_".$module."_".$entity."_".$document_type] = 1;
988 CUtil::InitJSCore(array("window", "ajax"));
989
990 $dts = \CBPDocument::signDocumentType([$module, $entity, $document_type]);
991?>
992<script src="/bitrix/js/bizproc/bizproc.js"></script>
993<script>
994 function BPAShowSelector(id, type, mode, arCurValues)
995 {
996 <?if($type=="only_users"):?>
997 var def_mode = "only_users";
998 <?else:?>
999 var def_mode = "";
1000 <?endif?>
1001
1002 if (!mode)
1003 mode = def_mode;
1004 var module = '<?=CUtil::JSEscape($module)?>';
1005 var entity = '<?=CUtil::JSEscape($entity)?>';
1006 var documentType = '<?=CUtil::JSEscape($document_type)?>';
1007 var documentId = '<?=CUtil::JSEscape($document_id)?>';
1008
1009 var loadAccessLib = (typeof BX.Access === 'undefined');
1010
1011 var contentUrl = '/bitrix/tools/bizproc/compatible_selector.php?mode=public&bxpublic=Y&lang=<?=LANGUAGE_ID?>'
1012 +'&dts=<?=CUtil::JSEscape($dts)?>'
1013 +(loadAccessLib? '&load_access_lib=Y':'');
1014
1015 if (mode == "only_users")
1016 {
1017 BX.WindowManager.setStartZIndex(1150);
1018 (new BX.CDialog({
1019 'content_url': contentUrl,
1020 'content_post': {
1021 'document_type': documentType,
1022 'document_id': documentId,
1023 'fieldName': id,
1024 'fieldType': type,
1025 'only_users': 'Y',
1026 'sessid': '<?= bitrix_sessid() ?>'
1027 },
1028 'height': 400,
1029 'width': 485
1030 })).Show();
1031 }
1032 else
1033 {
1034 if (typeof arWorkflowConstants === 'undefined')
1035 arWorkflowConstants = {};
1036
1037 var workflowTemplateNameCur = workflowTemplateName;
1038 var workflowTemplateDescriptionCur = workflowTemplateDescription;
1039 var workflowTemplateAutostartCur = workflowTemplateAutostart;
1040 var arWorkflowParametersCur = arWorkflowParameters;
1041 var arWorkflowVariablesCur = arWorkflowVariables;
1042 var arWorkflowConstantsCur = arWorkflowConstants;
1043 var arWorkflowTemplateCur = Array(rootActivity.Serialize());
1044
1045 if (arCurValues)
1046 {
1047 if (arCurValues['workflowTemplateName'])
1048 workflowTemplateNameCur = arCurValues['workflowTemplateName'];
1049 if (arCurValues['workflowTemplateDescription'])
1050 workflowTemplateDescriptionCur = arCurValues['workflowTemplateDescription'];
1051 if (arCurValues['workflowTemplateAutostart'])
1052 workflowTemplateAutostartCur = arCurValues['workflowTemplateAutostart'];
1053 if (arCurValues['arWorkflowParameters'])
1054 arWorkflowParametersCur = arCurValues['arWorkflowParameters'];
1055 if (arCurValues['arWorkflowVariables'])
1056 arWorkflowVariablesCur = arCurValues['arWorkflowVariables'];
1057 if (arCurValues['arWorkflowConstants'])
1058 arWorkflowConstantsCur = arCurValues['arWorkflowConstants'];
1059 if (arCurValues['arWorkflowTemplate'])
1060 arWorkflowTemplateCur = arCurValues['arWorkflowTemplate'];
1061 }
1062
1063 var p = {
1064 'document_type': documentType,
1065 'document_id': documentId,
1066 'fieldName': id,
1067 'fieldType': type,
1068 'selectorMode': mode,
1069 'workflowTemplateName': workflowTemplateNameCur,
1070 'workflowTemplateDescription': workflowTemplateDescriptionCur,
1071 'workflowTemplateAutostart': workflowTemplateAutostartCur,
1072 'sessid': '<?= bitrix_sessid() ?>'
1073 };
1074
1075 JSToPHPHidd(p, arWorkflowParametersCur, 'arWorkflowParameters');
1076 JSToPHPHidd(p, arWorkflowVariablesCur, 'arWorkflowVariables');
1077 JSToPHPHidd(p, arWorkflowConstantsCur, 'arWorkflowConstants');
1078 JSToPHPHidd(p, arWorkflowTemplateCur, 'arWorkflowTemplate');
1079
1080 (new BX.CDialog({
1081 'content_url': contentUrl,
1082 'content_post': p,
1083 'height': 425,
1084 'width': 485
1085 })).Show();
1086 }
1087 }
1088</script>
1089<?
1090 }
1091
1092 public static function showParameterField($type, $name, $values, $arParams = Array())
1093 {
1094 $id = !empty($arParams['id']) ? $arParams['id'] : md5(uniqid('', true));
1095
1096 $cols = !empty($arParams['size']) ? intval($arParams['size']) : 70;
1097 $defaultRows = $type == "user" ? 3 : 1;
1098 $rows = max((isset($arParams['rows']) && $arParams['rows']>0?intval($arParams['rows']):$defaultRows), min(5, ceil(mb_strlen((string)$values) / $cols)));
1099
1100 if($type == "user")
1101 {
1102 $s = '<table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td valign="top">';
1103 $s .= '<textarea onkeydown="i' . 'f(event.keyCode==45)BPAShowSelector(\''.Cutil::JSEscape(htmlspecialcharsbx($id)).'\', \''.Cutil::JSEscape($type).'\');" ';
1104 $s .= 'rows="'.$rows.'" ';
1105 $s .= 'cols="'.$cols.'" ';
1106 $s .= 'name="'.htmlspecialcharsbx($name).'" ';
1107 $s .= 'id="'.htmlspecialcharsbx($id).'" ';
1108 $s .= 'style="width: 100%"';
1109 $s .= '>'.htmlspecialcharsbx($values).'</textarea>';
1110 $s .= '</td><td valign="top" style="padding-left:4px" width="30">';
1111 $s .= CBPHelper::renderControlSelectorButton($id, $type, array('title' => GetMessage("BIZPROC_AS_SEL_FIELD_BUTTON").' (Insert)'));
1112 $s .= '</td></tr></table>';
1113 }
1114 elseif($type == "bool")
1115 {
1116 $s = '<table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td valign="top" width="30">';
1117 $s .= '<select name="'.htmlspecialcharsbx($name).'"><option value=""></option><option value="Y"'.($values=='Y'?' selected':'').'>'.GetMessage('MAIN_YES').'</option><option value="N"'.($values=='N'?' selected':'').'>'.GetMessage('MAIN_NO').'</option>';
1118 $s .= '</td><td style="padding-left:4px"><textarea ';
1119 $s .= 'rows="'.$rows.'" ';
1120 $s .= 'cols="'.$cols.'" ';
1121 $s .= 'name="'.htmlspecialcharsbx($name).'_X" ';
1122 $s .= 'id="'.htmlspecialcharsbx($id).'" ';
1123 $s .= 'style="width: 100%"';
1124 $s .= '>'.($values=="Y" || $values=="N"?"":htmlspecialcharsbx($values));
1125 $s .= '</textarea></td>';
1126 $s .= '<td valign="top" style="padding-left:4px" width="30">';
1127 $s .= CBPHelper::renderControlSelectorButton($id, $type);
1128 $s .= '</td></tr></table>';
1129 }
1130 elseif ($type == 'datetime')
1131 {
1132 $s = '<table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td valign="top"><textarea ';
1133 $s .= 'rows="'.$rows.'" ';
1134 $s .= 'cols="'.$cols.'" ';
1135 $s .= 'name="'.htmlspecialcharsbx($name).'" ';
1136 $s .= 'id="'.htmlspecialcharsbx($id).'" ';
1137 $s .= 'style="width: 100%"';
1138 $s .= '>'.htmlspecialcharsbx($values);
1139 $s .= '</textarea></td><td valign="top" style="padding-left:4px" width="20">'.CAdminCalendar::Calendar(htmlspecialcharsbx($name), "", "", true).'</td>';
1140 $s .= '<td valign="top" style="padding-left:4px" width="30">';
1141 $s .= CBPHelper::renderControlSelectorButton($id, $type);
1142 $s .= '</td></tr></table>';
1143 }
1144 else
1145 {
1146 $s = '<table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td valign="top"><textarea ';
1147 $s .= 'rows="'.$rows.'" ';
1148 $s .= 'cols="'.$cols.'" ';
1149 if (!empty($arParams['maxlength']))
1150 {
1151 $s .= 'maxlength="'.intval($arParams['maxlength']).'" ';
1152 }
1153 $s .= 'name="'.htmlspecialcharsbx($name).'" ';
1154 $s .= 'id="'.htmlspecialcharsbx($id).'" ';
1155 $s .= 'style="width: 100%"';
1156 $s .= '>'.htmlspecialcharsbx($values);
1157 $s .= '</textarea></td>';
1158 $s .= '<td valign="top" style="padding-left:4px" width="30">';
1159 $s .= CBPHelper::renderControlSelectorButton($id, $type);
1160 $s .= '</td></tr></table>';
1161 }
1162
1163 return $s;
1164 }
1165
1166 public static function _ReplaceTaskURL($str, $documentType)
1167 {
1168 $chttp = new CHTTP();
1169 $baseHref = $chttp->URN2URI('');
1170
1171 return str_replace(
1172 Array('#HTTP_HOST#', '#TASK_URL#', '#BASE_HREF#'),
1173 Array($_SERVER['HTTP_HOST'], ($documentType[0]=="iblock"?"/bitrix/admin/bizproc_task.php?workflow_id={=Workflow:id}":"/company/personal/bizproc/{=Workflow:id}/"), $baseHref),
1174 $str
1175 );
1176 }
1177
1178 public static function addDefaultWorkflowTemplates($documentType, $additionalModuleId = null)
1179 {
1180 if (!empty($additionalModuleId))
1181 {
1182 $additionalModuleId = preg_replace("/[^a-z0-9_.]/i", "", $additionalModuleId);
1183 $arModule = array($additionalModuleId, $documentType[0], 'bizproc');
1184 }
1185 else
1186 {
1187 $arModule = array($documentType[0], 'bizproc');
1188 }
1189
1190 $bIn = false;
1191 foreach ($arModule as $sModule)
1192 {
1193 if (file_exists($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/'.$sModule.'/templates'))
1194 {
1195 if($handle = opendir($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/'.$sModule.'/templates'))
1196 {
1197 $bIn = true;
1198 while(false !== ($file = readdir($handle)))
1199 {
1200 if(!is_file($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/'.$sModule.'/templates/'.$file))
1201 continue;
1202 $arFields = false;
1203 include($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/'.$sModule.'/templates/'.$file);
1204 if(is_array($arFields))
1205 {
1206 /*
1207 * If DOCUMENT_TYPE not defined, use current documentType
1208 * Overwise check if DOCUMENT_TYPE equals to current documentType
1209 */
1210 if (!array_key_exists("DOCUMENT_TYPE", $arFields))
1211 $arFields["DOCUMENT_TYPE"] = $documentType;
1212 elseif($arFields["DOCUMENT_TYPE"] != $documentType)
1213 continue;
1214
1215 $arFields["SYSTEM_CODE"] = $file;
1216 if(is_object($GLOBALS['USER']))
1217 $arFields["USER_ID"] = $GLOBALS['USER']->GetID();
1218 $arFields["MODIFIER_USER"] = new CBPWorkflowTemplateUser(CBPWorkflowTemplateUser::CurrentUser);
1219 try
1220 {
1221 CBPWorkflowTemplateLoader::Add($arFields);
1222 }
1223 catch (Exception $e)
1224 {
1225 }
1226 }
1227 }
1228 closedir($handle);
1229 }
1230 }
1231 if ($bIn)
1232 break;
1233 }
1234 }
1235
1257 public static function getWorkflowTemplatesForDocumentType($documentType, $showSystemTemplates = true)
1258 {
1259 $arResult = [];
1260 $filter = [
1261 "DOCUMENT_TYPE" => $documentType,
1262 "ACTIVE" => "Y",
1263 '<AUTO_EXECUTE' => CBPDocumentEventType::Automation
1264 ];
1265
1266 if (!$showSystemTemplates)
1267 {
1268 $filter['IS_SYSTEM'] = 'N';
1269 }
1270
1271 $dbWorkflowTemplate = CBPWorkflowTemplateLoader::GetList(
1272 ['SORT'=>'ASC','NAME'=>'ASC'],
1273 $filter,
1274 false,
1275 false,
1276 array("ID", "NAME", "DESCRIPTION", "MODIFIED", "USER_ID", "AUTO_EXECUTE", "USER_NAME", "USER_LAST_NAME", "USER_LOGIN", "USER_SECOND_NAME", 'PARAMETERS')
1277 );
1278 while ($arWorkflowTemplate = $dbWorkflowTemplate->GetNext())
1279 {
1280 $arWorkflowTemplate["USER"] = "(".$arWorkflowTemplate["USER_LOGIN"].")".(($arWorkflowTemplate["USER_NAME"] <> '' || $arWorkflowTemplate["USER_LAST_NAME"] <> '') ? " " : "").CUser::FormatName(COption::GetOptionString("bizproc", "name_template", CSite::GetNameFormat(false), SITE_ID), array("NAME" => $arWorkflowTemplate["USER_NAME"], "LAST_NAME" => $arWorkflowTemplate["USER_LAST_NAME"], "SECOND_NAME" => $arWorkflowTemplate["USER_SECOND_NAME"]), false, false);
1281
1282 $arWorkflowTemplate["AUTO_EXECUTE_TEXT"] = "";
1283
1284 if ($arWorkflowTemplate["AUTO_EXECUTE"] == CBPDocumentEventType::None)
1285 $arWorkflowTemplate["AUTO_EXECUTE_TEXT"] .= GetMessage("BPCGDOC_AUTO_EXECUTE_NONE");
1286
1287 if (($arWorkflowTemplate["AUTO_EXECUTE"] & CBPDocumentEventType::Create) != 0)
1288 {
1289 if ($arWorkflowTemplate["AUTO_EXECUTE_TEXT"] <> '')
1290 $arWorkflowTemplate["AUTO_EXECUTE_TEXT"] .= ", ";
1291 $arWorkflowTemplate["AUTO_EXECUTE_TEXT"] .= GetMessage("BPCGDOC_AUTO_EXECUTE_CREATE");
1292 }
1293
1294 if (($arWorkflowTemplate["AUTO_EXECUTE"] & CBPDocumentEventType::Edit) != 0)
1295 {
1296 if ($arWorkflowTemplate["AUTO_EXECUTE_TEXT"] <> '')
1297 $arWorkflowTemplate["AUTO_EXECUTE_TEXT"] .= ", ";
1298 $arWorkflowTemplate["AUTO_EXECUTE_TEXT"] .= GetMessage("BPCGDOC_AUTO_EXECUTE_EDIT");
1299 }
1300
1301 if (($arWorkflowTemplate["AUTO_EXECUTE"] & CBPDocumentEventType::Delete) != 0)
1302 {
1303 if ($arWorkflowTemplate["AUTO_EXECUTE_TEXT"] <> '')
1304 $arWorkflowTemplate["AUTO_EXECUTE_TEXT"] .= ", ";
1305 $arWorkflowTemplate["AUTO_EXECUTE_TEXT"] .= GetMessage("BPCGDOC_AUTO_EXECUTE_DELETE");
1306 }
1307
1308 $arWorkflowTemplate['HAS_PARAMETERS'] = count($arWorkflowTemplate['PARAMETERS']) > 0;
1309
1310 $arResult[] = $arWorkflowTemplate;
1311 }
1312
1313 return $arResult;
1314 }
1315
1316 public static function getNumberOfWorkflowTemplatesForDocumentType($documentType)
1317 {
1318 $n = CBPWorkflowTemplateLoader::GetList(
1319 array(),
1320 array("DOCUMENT_TYPE" => $documentType, "ACTIVE"=>"Y"),
1321 array()
1322 );
1323 return $n;
1324 }
1325
1333 public static function deleteWorkflowTemplate($id, $documentType, &$arErrors)
1334 {
1335 $arErrors = array();
1336
1337 $dbTemplates = CBPWorkflowTemplateLoader::GetList(
1338 array(),
1339 array("ID" => $id, "DOCUMENT_TYPE" => $documentType),
1340 false,
1341 false,
1342 array("ID")
1343 );
1344 $arTemplate = $dbTemplates->Fetch();
1345 if (!$arTemplate)
1346 {
1347 $arErrors[] = array(
1348 "code" => 0,
1349 "message" => str_replace("#ID#", $id, GetMessage("BPCGDOC_INVALID_WF_ID_MSGVER_1")),
1350 "file" => ""
1351 );
1352 return;
1353 }
1354
1355 try
1356 {
1357 CBPWorkflowTemplateLoader::Delete($id);
1358 }
1359 catch (Exception $e)
1360 {
1361 $arErrors[] = array(
1362 "code" => $e->getCode(),
1363 "message" => $e->getMessage(),
1364 "file" => $e->getFile()." [".$e->getLine()."]"
1365 );
1366 }
1367 }
1368
1377 public static function updateWorkflowTemplate($id, $documentType, $arFields, &$arErrors)
1378 {
1379 $arErrors = array();
1380
1381 $dbTemplates = CBPWorkflowTemplateLoader::GetList(
1382 array(),
1383 array("ID" => $id, "DOCUMENT_TYPE" => $documentType),
1384 false,
1385 false,
1386 array("ID")
1387 );
1388 $arTemplate = $dbTemplates->Fetch();
1389 if (!$arTemplate)
1390 {
1391 $arErrors[] = array(
1392 "code" => 0,
1393 "message" => str_replace("#ID#", $id, GetMessage("BPCGDOC_INVALID_WF_ID_MSGVER_1")),
1394 "file" => ""
1395 );
1396 return;
1397 }
1398
1399 try
1400 {
1401 CBPWorkflowTemplateLoader::Update($id, $arFields);
1402 }
1403 catch (Exception $e)
1404 {
1405 $arErrors[] = array(
1406 "code" => $e->getCode(),
1407 "message" => $e->getMessage(),
1408 "file" => $e->getFile()." [".$e->getLine()."]"
1409 );
1410 }
1411 }
1412
1422 public static function canUserOperateDocument($operation, $userId, $parameterDocumentId, $arParameters = array())
1423 {
1424 [$moduleId, $entity, $documentId] = CBPHelper::ParseDocumentId($parameterDocumentId);
1425
1426 if ($moduleId <> '')
1427 CModule::IncludeModule($moduleId);
1428
1429 if (class_exists($entity))
1430 return call_user_func_array(array($entity, "CanUserOperateDocument"), array($operation, $userId, $documentId, $arParameters));
1431
1432 return false;
1433 }
1434
1444 public static function canUserOperateDocumentType($operation, $userId, $parameterDocumentType, $arParameters = array())
1445 {
1446 [$moduleId, $entity, $documentType] = CBPHelper::ParseDocumentId($parameterDocumentType);
1447
1448 if ($moduleId <> '')
1449 CModule::IncludeModule($moduleId);
1450
1451 if (class_exists($entity))
1452 return call_user_func_array(array($entity, "CanUserOperateDocumentType"), array($operation, $userId, $documentType, $arParameters));
1453
1454 return false;
1455 }
1456
1463 public static function getDocumentAdminPage($parameterDocumentId)
1464 {
1465 [$moduleId, $entity, $documentId] = CBPHelper::ParseDocumentId($parameterDocumentId);
1466
1467 if ($moduleId <> '')
1468 CModule::IncludeModule($moduleId);
1469
1470 if (class_exists($entity))
1471 return call_user_func_array(array($entity, "GetDocumentAdminPage"), array($documentId));
1472
1473 return "";
1474 }
1475
1481 public static function getDocumentName($parameterDocumentId)
1482 {
1483 [$moduleId, $entity, $documentId] = CBPHelper::ParseDocumentId($parameterDocumentId);
1484
1485 if ($moduleId <> '')
1486 CModule::IncludeModule($moduleId);
1487
1488 if (class_exists($entity) && method_exists($entity, 'getDocumentName'))
1489 return call_user_func_array(array($entity, "getDocumentName"), array($documentId));
1490
1491 return "";
1492 }
1493
1510 public static function getUserTasksForWorkflow($userId, $workflowId)
1511 {
1512 $userId = intval($userId);
1513 if ($userId <= 0)
1514 return array();
1515
1516 $workflowId = trim($workflowId);
1517 if ($workflowId == '')
1518 return array();
1519
1520 $arResult = array();
1521
1522 $dbTask = CBPTaskService::GetList(
1523 array(),
1524 array("WORKFLOW_ID" => $workflowId, "USER_ID" => $userId, 'STATUS' => CBPTaskStatus::Running),
1525 false,
1526 false,
1527 array("ID", "WORKFLOW_ID", "NAME", "DESCRIPTION")
1528 );
1529 while ($arTask = $dbTask->GetNext())
1530 $arResult[] = $arTask;
1531
1532 return $arResult;
1533 }
1534
1535 public static function prepareFileForHistory($documentId, $fileId, $historyIndex)
1536 {
1537 return CBPHistoryService::PrepareFileForHistory($documentId, $fileId, $historyIndex);
1538 }
1539
1540 public static function isAdmin()
1541 {
1542 global $APPLICATION;
1543 return ($APPLICATION->GetGroupRight("bizproc") >= "W");
1544 }
1545
1546 public static function getDocumentFromHistory($historyId, &$arErrors)
1547 {
1548 $arErrors = array();
1549
1550 try
1551 {
1552 $historyId = intval($historyId);
1553 if ($historyId <= 0)
1554 throw new CBPArgumentNullException("historyId");
1555
1556 return CBPHistoryService::GetById($historyId);
1557 }
1558 catch (Exception $e)
1559 {
1560 $arErrors[] = array(
1561 "code" => $e->getCode(),
1562 "message" => $e->getMessage(),
1563 "file" => $e->getFile()." [".$e->getLine()."]"
1564 );
1565 }
1566 return null;
1567 }
1568
1569 public static function getAllowableUserGroups($parameterDocumentType)
1570 {
1571 [$moduleId, $entity, $documentType] = CBPHelper::ParseDocumentId($parameterDocumentType);
1572
1573 if ($moduleId <> '')
1574 CModule::IncludeModule($moduleId);
1575
1576 if (class_exists($entity))
1577 {
1578 $result = call_user_func_array(array($entity, "GetAllowableUserGroups"), array($documentType));
1579 $result1 = array();
1580 foreach ($result as $key => $value)
1581 $result1[mb_strtolower($key)] = $value;
1582 return $result1;
1583 }
1584
1585 return array();
1586 }
1587
1588 public static function onAfterTMDayStart($data)
1589 {
1590 if (!CModule::IncludeModule("im"))
1591 return;
1592
1593 $userId = (int) $data['USER_ID'];
1594
1595 $iterator = Bizproc\Workflow\Entity\WorkflowInstanceTable::getList(
1596 [
1597 'select' => [new \Bitrix\Main\Entity\ExpressionField('CNT', 'COUNT(\'x\')')],
1598 'filter' => [
1599 '=STARTED_BY' => $userId,
1600 '<OWNED_UNTIL' => Main\Type\DateTime::createFromTimestamp(
1601 time() - Bizproc\Workflow\Entity\WorkflowInstanceTable::LOCKED_TIME_INTERVAL
1602 ),
1603 ],
1604 ]
1605 );
1606 $row = $iterator->fetch();
1607 if (!empty($row['CNT']))
1608 {
1609 $path = IsModuleInstalled('bitrix24') ? '/bizproc/bizproc/?type=is_locked'
1610 : Main\Config\Option::get("bizproc", "locked_wi_path", '/services/bp/instances.php?type=is_locked');
1611
1612 CIMNotify::Add([
1613 'FROM_USER_ID' => 0,
1614 'TO_USER_ID' => $userId,
1615 'NOTIFY_TYPE' => IM_NOTIFY_SYSTEM,
1616 'NOTIFY_MODULE' => 'bizproc',
1617 'NOTIFY_EVENT' => 'wi_locked',
1618 'TITLE' => Main\Localization\Loc::getMessage('BPCGDOC_WI_LOCKED_NOTICE_TITLE_MSGVER_1'),
1619 'MESSAGE' => Main\Localization\Loc::getMessage(
1620 'BPCGDOC_WI_LOCKED_NOTICE_MESSAGE',
1621 ['#PATH#' => $path, '#CNT#' => $row['CNT']]
1622 ),
1623 ]);
1624 }
1625 }
1626
1633 public static function sendB24LimitsNotifyToAdmins()
1634 {
1635 return '';
1636 }
1637
1643 public static function getDocumentFieldsAliasesMap($fields)
1644 {
1645 if (empty($fields) || !is_array($fields))
1646 {
1647 return [];
1648 }
1649
1650 $aliases = [];
1651 foreach ($fields as $key => $property)
1652 {
1653 if (isset($property['Alias']))
1654 {
1655 $aliases[$property['Alias']] = $key;
1656 }
1657 }
1658 return $aliases;
1659 }
1660
1667 public static function isExpression($value)
1668 {
1669 //go to internal alias
1670 return CBPActivity::isExpression($value);
1671 }
1672
1673 public static function parseExpression($expression)
1674 {
1675 $matches = null;
1676 if (is_string($expression) && preg_match(CBPActivity::ValuePattern, $expression, $matches))
1677 {
1678 $result = array(
1679 'object' => $matches['object'],
1680 'field' => $matches['field'],
1681 'modifiers' => array()
1682 );
1683 if (!empty($matches['mod1']))
1684 $result['modifiers'][] = $matches['mod1'];
1685 if (!empty($matches['mod2']))
1686 $result['modifiers'][] = $matches['mod2'];
1687
1688 return $result;
1689 }
1690 return false;
1691 }
1692
1693 public static function signParameters(array $parameters)
1694 {
1695 return self::signArray($parameters, 'bizproc_wf_params');
1696 }
1697
1702 public static function unSignParameters($unsignedData)
1703 {
1704 return self::unSignArray($unsignedData, 'bizproc_wf_params');
1705 }
1706
1707 public static function signDocumentType(array $documentType)
1708 {
1709 return self::signArray($documentType, 'bizproc_document_type');
1710 }
1711
1716 public static function unSignDocumentType($unsignedData): ?array
1717 {
1718 $dt = self::unSignArray($unsignedData, 'bizproc_document_type');
1719 return $dt ?: null;
1720 }
1721
1722 private static function signArray(array $source, $salt)
1723 {
1724 $signer = new Main\Security\Sign\Signer;
1725 $jsonData = Main\Web\Json::encode($source);
1726
1727 return $signer->sign($jsonData, $salt);
1728 }
1729
1730 private static function unSignArray(string $unsignedSource, $salt)
1731 {
1732 $signer = new Main\Security\Sign\Signer;
1733
1734 try
1735 {
1736 $unsigned = $signer->unsign($unsignedSource, $salt);
1737 $result = Main\Web\Json::decode($unsigned);
1738 }
1739 catch (\Exception $e)
1740 {
1741 $result = [];
1742 }
1743
1744 return $result;
1745 }
1746
1747 public static function getTemplatesForStart($userId, $documentType, $documentId = null, array $parameters = array())
1748 {
1749 if (!isset($parameters['UserGroups']))
1750 {
1751 $currentUser = \Bitrix\Main\Engine\CurrentUser::get();
1752 $currentUserId = $currentUser->getId();
1753
1754 $parameters['UserGroups'] = (
1755 $currentUserId !== null && ((int)$currentUserId === (int)$userId)
1756 ? $currentUser->getUserGroups()
1757 : CUser::GetUserGroup($userId)
1758 );
1759 }
1760 if (!isset($parameters['DocumentStates']))
1761 {
1762 $parameters['DocumentStates'] = static::GetDocumentStates($documentType, $documentId);
1763 }
1764 $op = CBPCanUserOperateOperation::StartWorkflow;
1765
1766 $templates = array();
1767 $dbWorkflowTemplate = CBPWorkflowTemplateLoader::GetList(
1768 array('SORT' => 'ASC', 'NAME' => 'ASC'),
1769 array(
1770 "DOCUMENT_TYPE" => $documentType,
1771 "ACTIVE" => "Y",
1772 "IS_SYSTEM" => "N",
1773 '<AUTO_EXECUTE' => CBPDocumentEventType::Automation
1774 ),
1775 false,
1776 false,
1777 array("ID", "NAME", "DESCRIPTION", "PARAMETERS")
1778 );
1779 while ($arWorkflowTemplate = $dbWorkflowTemplate->fetch())
1780 {
1781 $parameters['WorkflowTemplateId'] = $arWorkflowTemplate['ID'];
1782 if ($documentId)
1783 {
1784 if (!CBPDocument::CanUserOperateDocument($op, $userId, $documentId, $parameters))
1785 {
1786 continue;
1787 }
1788 }
1789 elseif (!CBPDocument::CanUserOperateDocumentType($op, $userId, $documentType, $parameters))
1790 {
1791 continue;
1792 }
1793
1794 $templates[] = array(
1795 'id' => $arWorkflowTemplate['ID'],
1796 'name' => $arWorkflowTemplate['NAME'],
1797 'description' => $arWorkflowTemplate['DESCRIPTION'],
1798 'hasParameters' => count($arWorkflowTemplate['PARAMETERS']) > 0,
1799 'isConstantsTuned' => CBPWorkflowTemplateLoader::isConstantsTuned($arWorkflowTemplate["ID"])
1800 );
1801 }
1802
1803 return $templates;
1804 }
1805
1806 public static function getUserGroups(array $parameterDocumentType, array $parameterDocumentId, int $userId)
1807 {
1808 [$moduleId, $entity, $documentType] = CBPHelper::ParseDocumentId($parameterDocumentType);
1809
1810 if ($moduleId)
1811 {
1812 \Bitrix\Main\Loader::includeModule($moduleId);
1813 }
1814
1815 if (class_exists($entity) && method_exists($entity, 'GetUserGroups'))
1816 {
1817 return call_user_func([$entity, 'GetUserGroups'], $parameterDocumentType, $parameterDocumentId, $userId);
1818 }
1819
1820 return null;
1821 }
1822}
$arParams
Определения access_dialog.php:21
$type
Определения options.php:106
$arResult
Определения generate_coupon.php:16
if(!is_object($USER)||! $USER->IsAuthorized()) $userId
Определения check_mail.php:18
static getInstance()
Определения Listener.php:154
static getActiveSession()
Определения Manager.php:38
static deleteByWorkflowId(string $workflowId)
Определения ResultTable.php:79
static getTask(string $associatedActivity, array $task, int $userId)
Определения Manager.php:14
static getIdsByDocument(array $documentId)
Определения workflowinstance.php:114
static mergeByDocument($paramFirstDocumentId, $paramSecondDocumentId)
Определения workflowinstance.php:159
static migrateDocumentType($paramOldType, $paramNewType, $workflowTemplateIds)
Определения workflowinstance.php:190
static deleteByWorkflowId(string $workflowId)
Определения workflowmetadatatable.php:52
static maskAsZombie(array $documentId)
Определения workflowstate.php:157
static onDocumentDelete(array $docId)
Определения workflowusertable.php:323
Определения event.php:5
static getInstance()
Определения eventmanager.php:31
static delete($primary)
Определения datamanager.php:1644
const None
Определения constants.php:44
const Executing
Определения constants.php:8
const Edit
Определения constants.php:154
const Create
Определения constants.php:153
const None
Определения constants.php:152
Определения document.php:14
static mergeDocuments($firstDocumentId, $secondDocumentId)
Определения document.php:154
static addShowParameterInit($module, $type, $document_type, $entity="", $document_id='')
Определения document.php:985
static getAllowableOperations($userId, $arGroups, $arStates, $appendExtendedGroups=false)
Определения document.php:266
const PARAM_DOCUMENT_EVENT_TYPE
Определения document.php:19
static onDocumentDelete($documentId, &$errors)
Определения document.php:597
const PARAM_DOCUMENT_TYPE
Определения document.php:20
static terminateWorkflow($workflowId, $documentId, &$arErrors, $stateTitle='')
Определения document.php:537
static canOperate($operation, $userId, $arGroups, $arStates)
Определения document.php:316
static getTaskControls($arTask, $userId=0)
Определения document.php:832
static getDocumentState($documentId, $workflowId)
Определения document.php:148
const PARAM_TAGRET_USER
Определения document.php:15
static setTasksUserStatus($userId, $status, $ids=array(), &$errors=array())
Определения document.php:681
const PARAM_PRE_GENERATED_WORKFLOW_ID
Определения document.php:21
static getDocumentStates($documentType, $documentId=null)
Определения document.php:108
static startWorkflowParametersValidate($templateId, $arWorkflowParameters, $documentType, &$arErrors)
Определения document.php:853
static getAllowableEvents($userId, $arGroups, $arState, $appendExtendedGroups=false)
Определения document.php:171
const PARAM_USED_DOCUMENT_FIELDS
Определения document.php:22
const PARAM_USE_FORCED_TRACKING
Определения document.php:17
static showTaskForm($arTask, $userId, $userName="", $arRequest=null)
Определения document.php:660
static startDebugWorkflow($workflowTemplateId, $documentId, $parameters, &$errors)
Определения document.php:363
static autoStartWorkflows($documentType, $autoExecute, $documentId, $arParameters, &$arErrors)
Определения document.php:452
static getDocumentName($parameterDocumentId)
Определения document.php:1481
static killWorkflow($workflowId, $terminate=true, $documentId=null)
Определения document.php:566
const PARAM_MODIFIED_DOCUMENT_FIELDS
Определения document.php:16
static addDocumentToHistory($parameterDocumentId, $name, $userId)
Определения document.php:211
static sendExternalEvent($workflowId, $workflowEvent, $arParameters, &$arErrors)
Определения document.php:511
static startWorkflowParametersShow($templateId, $arWorkflowParameters, $formName, $bVarsFromForm, $documentType=null)
Определения document.php:927
static migrateDocumentType($oldType, $newType)
Определения document.php:24
static startWorkflow($workflowTemplateId, $documentId, $parameters, &$errors, $parentWorkflow=null)
Определения document.php:339
static showParameterField($type, $name, $values, $arParams=Array())
Определения document.php:1092
static getActiveStates(array $documentId, $limit=0)
Определения document.php:123
static postTaskForm($arTask, $userId, $arRequest, &$arErrors, $userName="")
Определения document.php:624
const PARAM_IGNORE_SIMULTANEOUS_PROCESSES_LIMIT
Определения document.php:18
static generateWorkflowId()
Определения runtime.php:401
const ExactlyNone
Определения constants.php:326
static GetList($arOrder=array("ID"=> "DESC"), $arFilter=array(), $arGroupBy=false, $arNavStartParams=false, $arSelectFields=array())
Определения taskservice.php:138
static delegateTask($taskId, $fromUserId, $toUserId)
Определения taskservice.php:239
static getOriginalTaskUserId($taskId, $realUserId)
Определения taskservice.php:287
const Running
Определения constants.php:258
const Waiting
Определения constants.php:273
const Custom
Определения trackingservice.php:702
static Add($arFields)
Определения im_notify.php:28
static IncludeModule($module_name)
Определения module.php:151
$templateId
Определения component_props2.php:51
$bVarsFromForm
Определения file_edit.php:44
$template
Определения file_edit.php:49
bx popup label bx width30 PAGE_NEW_MENU_NAME text width
Определения file_new.php:677
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
bx_acc_lim_group_list limitGroupList[] multiple<?=$group[ 'ID']?> ID selected margin top
Определения file_new.php:657
hidden mSiteList<?=htmlspecialcharsbx(serialize( $siteList))?><?=htmlspecialcharsbx( $siteList[ $j]["ID"])?> _Propery<? if(((COption::GetOptionString( $module_id, "different_set", "N")=="Y") &&( $j !=0))||(COption::GetOptionString( $module_id, "different_set", "N")=="N")) echo "display: none;"?> top adm detail content cell l top adm detail content cell r heading center center ID left
Определения options.php:768
$arGroups
Определения options.php:1766
$_REQUEST["admin_mnu_menu_id"]
Определения get_menu.php:8
$result
Определения get_property_values.php:14
$entity
$moduleId
$activity
Определения options.php:214
$errors
Определения iblock_catalog_edit.php:74
$filter
Определения iblock_catalog_list.php:54
const IM_MESSAGE_SYSTEM
Определения include.php:21
const IM_NOTIFY_FROM
Определения include.php:37
endif
Определения csv_new_setup.php:990
$status
Определения session.php:10
htmlspecialcharsbx($string, $flags=ENT_COMPAT, $doubleEncode=true)
Определения tools.php:2701
GetMessage($name, $aReplace=null)
Определения tools.php:3397
$name
Определения menu_edit.php:35
Определения BaseTask.php:3
$GLOBALS['____1690880296']
Определения license.php:1
$event
Определения prolog_after.php:141
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
$ar
Определения options.php:199
if(empty($signedUserToken)) $key
Определения quickway.php:257
$i
Определения factura.php:643
else $userName
Определения order_form.php:75
</p ></td >< td valign=top style='border-top:none;border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;padding:0cm 2.0pt 0cm 2.0pt;height:9.0pt'>< p class=Normal align=center style='margin:0cm;margin-bottom:.0001pt;text-align:center;line-height:normal'>< a name=ТекстовоеПоле54 ></a ><?=($taxRate > count( $arTaxList) > 0) ? $taxRate."%"
Определения waybill.php:936
text align
Определения template.php:556
$rows
Определения options.php:264
$error
Определения subscription_card_product.php:20
$k
Определения template_pdf.php:567
$dbResult
Определения updtr957.php:3
$iterator
Определения yandex_run.php:610