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