ILIAS  trunk Revision v11.0_alpha-1843-g9e1fad99175
All Data Structures Namespaces Files Functions Variables Enumerations Enumerator Modules Pages
class.ilCertificateCron.php
Go to the documentation of this file.
1 <?php
2 
19 declare(strict_types=1);
20 
26 
31 {
32  protected ?ilLanguage $lng;
33  private ?Container $dic;
34 
35  public function __construct(
36  private ?ilCertificateQueueRepository $queueRepository = null,
37  private ?ilCertificateTemplateRepository $templateRepository = null,
38  private ?ilUserCertificateRepository $userRepository = null,
39  private ?ilCertificateValueReplacement $valueReplacement = null,
40  private ?ilLogger $logger = null,
41  ?Container $dic = null,
42  ?ilLanguage $language = null,
43  private ?ilCertificateObjectHelper $objectHelper = null,
44  private ?ilSetting $settings = null,
45  private ?JobManager $cronManager = null,
46  ) {
47  if (null === $dic) {
48  global $DIC;
49  $dic = $DIC;
50  }
51  $this->dic = $dic;
52 
53  if ($dic && isset($dic['lng'])) {
54  $language = $dic->language();
55  $language->loadLanguageModule('certificate');
56  }
57 
58  $this->lng = $language;
59  }
60 
61  public function getTitle(): string
62  {
63  return $this->lng->txt('cert_cron_task_title');
64  }
65 
66  public function getDescription(): string
67  {
68  return $this->lng->txt('cert_cron_task_desc');
69  }
70 
71  public function init(): void
72  {
73  if (null === $this->dic) {
74  global $DIC;
75  $this->dic = $DIC;
76  }
77 
78  $database = $this->dic->database();
79 
80  if (null === $this->logger) {
81  $this->logger = $this->dic->logger()->cert();
82  }
83 
84  if (null === $this->cronManager) {
85  $this->cronManager = $this->dic->cron()->manager();
86  }
87 
88  if (null === $this->queueRepository) {
89  $this->queueRepository = new ilCertificateQueueRepository($database, $this->logger);
90  }
91 
92  if (null === $this->templateRepository) {
93  $this->templateRepository = new ilCertificateTemplateDatabaseRepository($database, $this->logger);
94  }
95 
96  if (null === $this->userRepository) {
97  $this->userRepository = new ilUserCertificateRepository($database, $this->logger);
98  }
99 
100  if (null === $this->valueReplacement) {
101  $this->valueReplacement = new ilCertificateValueReplacement();
102  }
103 
104  if (null === $this->objectHelper) {
105  $this->objectHelper = new ilCertificateObjectHelper();
106  }
107 
108  if (null === $this->settings) {
109  $this->settings = new ilSetting('certificate');
110  }
111  }
112 
113  public function run(): JobResult
114  {
115  $this->init();
116 
117  $result = new JobResult();
118  $result->setStatus(JobResult::STATUS_NO_ACTION);
119 
120  $currentMode = $this->settings->get('persistent_certificate_mode', 'persistent_certificate_mode_cron');
121  if ($currentMode !== 'persistent_certificate_mode_cron') {
122  $this->logger->warning(sprintf(
123  'Will not start cron job, because the mode is not set as cron job. Current Mode in settings: "%s"',
124  $currentMode
125  ));
126 
127  return $result;
128  }
129 
130  $this->logger->debug('START - Begin with cron job to create user certificates from templates');
131 
132  $entries = $this->queueRepository->getAllEntriesFromQueue();
133 
134  $status = JobResult::STATUS_OK;
135 
136  $entryCounter = 0;
137  $succeededGenerations = [];
138  foreach ($entries as $entry) {
139  try {
140  $succeededGenerations = $this->processEntry(
141  $entryCounter,
142  $entry,
143  $succeededGenerations
144  );
145 
146  ++$entryCounter;
147  } catch (ilInvalidCertificateException $exception) {
148  $this->logger->warning($exception->getMessage());
149  $this->logger->warning('The user MAY not be able to achieve the certificate based on the adapters settings');
150  $this->logger->warning('Due the error, the entry will now be removed from the queue.');
151 
152  $this->queueRepository->removeFromQueue($entry->getId());
153 
154  continue;
155  } catch (ilException $exception) {
156  $this->logger->warning($exception->getMessage());
157  $this->logger->warning('Due the error, the entry will now be removed from the queue.');
158 
159  $this->queueRepository->removeFromQueue($entry->getId());
160 
161  continue;
162  }
163  }
164 
165  $result->setStatus($status);
166  if ($succeededGenerations !== []) {
167  $message = sprintf(
168  'Generated %s certificate(s) in run. Result: %s',
169  count($succeededGenerations),
170  implode(' | ', $succeededGenerations)
171  );
172  $this->logger->info($message);
173  $result->setMessage(ilStr::subStr($message, 0, 400));
174  } else {
175  $result->setMessage('0 certificates generated in current run.');
176  }
177 
178  return $result;
179  }
180 
181  public function getId(): string
182  {
183  return 'certificate';
184  }
185 
186  public function hasAutoActivation(): bool
187  {
188  return true;
189  }
190 
191  public function hasFlexibleSchedule(): bool
192  {
193  return true;
194  }
195 
197  {
198  return JobScheduleType::IN_MINUTES;
199  }
200 
201  public function getDefaultScheduleValue(): ?int
202  {
203  return 1;
204  }
205 
212  public function processEntry(int $entryCounter, ilCertificateQueueEntry $entry, array $succeededGenerations): array
213  {
214  if ($entryCounter > 0 && $entryCounter % 10 === 0) {
215  $this->cronManager->ping($this->getId());
216  }
217 
218  $this->logger->debug('Entry found will start of processing the entry');
219 
221  $class = $entry->getAdapterClass();
222  $this->logger->debug('Adapter class to be executed "' . $class . '"');
223 
224  $placeholderValueObject = new $class();
225  if (!$placeholderValueObject instanceof ilCertificatePlaceholderValues) {
227  'The given class ' . $class . ' must be an instance of ilCertificateCronAdapter and must ' .
228  'have an accessible namespace. The composer class map should be reloaded.'
229  );
230  }
231 
232  $objId = $entry->getObjId();
233  $userId = $entry->getUserId();
234  $templateId = $entry->getTemplateId();
235 
236  $this->logger->debug(sprintf(
237  'Fetch certificate template for user id: "%s" and object id: "%s" and template id: "%s"',
238  $userId,
239  $objId,
240  $templateId
241  ));
242 
243  $template = $this->templateRepository->fetchTemplate($templateId);
244 
245  $object = $this->objectHelper->getInstanceByObjId($objId, false);
246  if (!$object instanceof ilObject) {
247  throw new ilCertificateIssuingObjectNotFound(sprintf(
248  'The given object id: "%s" could not be referred to an actual object',
249  $objId
250  ));
251  }
252 
253  $type = $object->getType();
254 
255  $userObject = $this->objectHelper->getInstanceByObjId($userId, false);
256  if (!$userObject instanceof ilObjUser) {
257  throw new ilCertificateOwnerNotFound('The given user id"' . $userId . '" could not be referred to an actual user');
258  }
259 
260  $this->logger->debug(sprintf(
261  'Object type: "%s"',
262  $type
263  ));
264 
265  $cert_id = $this->userRepository->requestIdentity();
266  $certificateContent = $template->getCertificateContent();
267 
268  $placeholderValues = $placeholderValueObject->getPlaceholderValues($userId, $objId);
269  $placeholderValues['CERTIFICATE_ID'] = $cert_id->asString();
270 
271  $this->logger->debug(sprintf(
272  'Values for placeholders: "%s"',
273  json_encode($placeholderValues, JSON_THROW_ON_ERROR)
274  ));
275 
276  $certificateContent = $this->valueReplacement->replace(
277  $placeholderValues,
278  $certificateContent,
279  );
280 
281  $userCertificate = new ilUserCertificate(
282  $template->getId(),
283  $objId,
284  $type,
285  $userId,
286  $userObject->getFullname(),
287  $entry->getStartedTimestamp(),
288  $certificateContent,
289  json_encode($placeholderValues, JSON_THROW_ON_ERROR),
290  null,
291  $template->getVersion(),
293  true,
294  $cert_id,
295  $template->getBackgroundImagePath(),
296  $template->getTileImagePath(),
297  $template->getBackgroundImageIdentification(),
298  $template->getTileImageIdentification(),
299  null,
300  );
301 
302  $persistedUserCertificate = $this->userRepository->save($userCertificate);
303 
304  $succeededGenerations[] = implode('/', [
305  'obj_id: ' . $objId,
306  'usr_id: ' . $userId
307  ]);
308 
309  if ($entry->getId() !== null) {
310  $this->queueRepository->removeFromQueue($entry->getId());
311  }
312 
313  $this->dic->event()->raise(
314  'components/ILIAS/Certificate',
315  'certificateIssued',
316  ['certificate' => $persistedUserCertificate]
317  );
318 
319  return $succeededGenerations;
320  }
321 }
$objId
Definition: xapitoken.php:57
static subStr(string $a_str, int $a_start, ?int $a_length=null)
Definition: class.ilStr.php:24
Customizing of pimple-DIC for ILIAS.
Definition: Container.php:35
while($session_entry=$r->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) return null
const ILIAS_VERSION_NUMERIC
global $DIC
Definition: shib_login.php:22
language()
Get interface to the i18n service.
Definition: Container.php:95
processEntry(string $class_name, int $obj_id, int $usr_id, \ilCertificateTemplate $template)
$message
Definition: xapiexit.php:31
__construct(private ?ilCertificateQueueRepository $queueRepository=null, private ?ilCertificateTemplateRepository $templateRepository=null, private ?ilUserCertificateRepository $userRepository=null, private ?ilCertificateValueReplacement $valueReplacement=null, private ?ilLogger $logger=null, ?Container $dic=null, ?ilLanguage $language=null, private ?ilCertificateObjectHelper $objectHelper=null, private ?ilSetting $settings=null, private ?JobManager $cronManager=null,)