ILIAS  release_9 Revision v9.13-25-g2c18ec4c24f
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  return $result;
124  }
125 
126  $this->logger->debug('START - Begin with cron job to create user certificates from templates');
127 
128  $entries = $this->queueRepository->getAllEntriesFromQueue();
129 
130  $status = ilCronJobResult::STATUS_OK;
131 
132  $entryCounter = 0;
133  $succeededGenerations = [];
134  foreach ($entries as $entry) {
135  try {
136  $succeededGenerations = $this->processEntry(
137  $entryCounter,
138  $entry,
139  $succeededGenerations
140  );
141 
142  ++$entryCounter;
143  } catch (ilInvalidCertificateException $exception) {
144  $this->logger->warning($exception->getMessage());
145  $this->logger->warning('The user MAY not be able to achieve the certificate based on the adapters settings');
146  $this->logger->warning('Due the error, the entry will now be removed from the queue.');
147 
148  $this->queueRepository->removeFromQueue($entry->getId());
149 
150  continue;
151  } catch (ilException $exception) {
152  $this->logger->warning($exception->getMessage());
153  $this->logger->warning('Due the error, the entry will now be removed from the queue.');
154 
155  $this->queueRepository->removeFromQueue($entry->getId());
156  continue;
157  }
158  }
159 
160  $result->setStatus($status);
161  if ($succeededGenerations !== []) {
162  $message = sprintf(
163  'Generated %s certificate(s) in run. Result: %s',
164  count($succeededGenerations),
165  implode(' | ', $succeededGenerations)
166  );
167  $this->logger->info($message);
168  $result->setMessage(ilStr::subStr($message, 0, 400));
169  } else {
170  $result->setMessage('0 certificates generated in current run.');
171  }
172 
173  return $result;
174  }
175 
176  public function getId(): string
177  {
178  return 'certificate';
179  }
180 
181  public function hasAutoActivation(): bool
182  {
183  return true;
184  }
185 
186  public function hasFlexibleSchedule(): bool
187  {
188  return true;
189  }
190 
192  {
193  return CronJobScheduleType::SCHEDULE_TYPE_IN_MINUTES;
194  }
195 
196  public function getDefaultScheduleValue(): ?int
197  {
198  return 1;
199  }
200 
207  public function processEntry(int $entryCounter, ilCertificateQueueEntry $entry, array $succeededGenerations): array
208  {
209  if ($entryCounter > 0 && $entryCounter % 10 === 0) {
210  $this->cronManager->ping($this->getId());
211  }
212 
213  $this->logger->debug('Entry found will start of processing the entry');
214 
216  $class = $entry->getAdapterClass();
217  $this->logger->debug('Adapter class to be executed "' . $class . '"');
218 
219  $placeholderValueObject = new $class();
220  if (!$placeholderValueObject instanceof ilCertificatePlaceholderValues) {
222  'The given class ' . $class . ' must be an instance of ilCertificateCronAdapter and must ' .
223  'have an accessible namespace. The composer class map should be reloaded.'
224  );
225  }
226 
227  $objId = $entry->getObjId();
228  $userId = $entry->getUserId();
229  $templateId = $entry->getTemplateId();
230 
231  $this->logger->debug(sprintf(
232  'Fetch certificate template for user id: "%s" and object id: "%s" and template id: "%s"',
233  $userId,
234  $objId,
235  $templateId
236  ));
237 
238  $template = $this->templateRepository->fetchTemplate($templateId);
239 
240  $object = $this->objectHelper->getInstanceByObjId($objId, false);
241  if (!$object instanceof ilObject) {
242  throw new ilCertificateIssuingObjectNotFound(sprintf(
243  'The given object id: "%s" could not be referred to an actual object',
244  $objId
245  ));
246  }
247 
248  $type = $object->getType();
249 
250  $userObject = $this->objectHelper->getInstanceByObjId($userId, false);
251  if (!($userObject instanceof ilObjUser)) {
252  throw new ilCertificateOwnerNotFound('The given user id"' . $userId . '" could not be referred to an actual user');
253  }
254 
255  $this->logger->debug(sprintf(
256  'Object type: "%s"',
257  $type
258  ));
259 
260  $certificateContent = $template->getCertificateContent();
261 
262  $placeholderValues = $placeholderValueObject->getPlaceholderValues($userId, $objId);
263 
264  $this->logger->debug(sprintf(
265  'Values for placeholders: "%s"',
266  json_encode($placeholderValues, JSON_THROW_ON_ERROR)
267  ));
268 
269  $certificateContent = $this->valueReplacement->replace(
270  $placeholderValues,
271  $certificateContent
272  );
273 
274  $thumbnailImagePath = $template->getThumbnailImagePath();
275  $userCertificate = new ilUserCertificate(
276  $template->getId(),
277  $objId,
278  $type,
279  $userId,
280  $userObject->getFullname(),
281  $entry->getStartedTimestamp(),
282  $certificateContent,
283  json_encode($placeholderValues, JSON_THROW_ON_ERROR),
284  null,
285  $template->getVersion(),
287  true,
288  $template->getBackgroundImagePath(),
289  $thumbnailImagePath
290  );
291 
292  $persistedUserCertificate = $this->userRepository->save($userCertificate);
293 
294  $succeededGenerations[] = implode('/', [
295  'obj_id: ' . $objId,
296  'usr_id: ' . $userId
297  ]);
298 
299  if ($entry->getId() !== null) {
300  $this->queueRepository->removeFromQueue($entry->getId());
301  }
302 
303  $this->dic->event()->raise(
304  'Services/Certificate',
305  'certificateIssued',
306  ['certificate' => $persistedUserCertificate]
307  );
308 
309  return $succeededGenerations;
310  }
311 }
array $settings
Setting values (LTI parameters, custom parameters and local parameters).
Definition: System.php:200
const ILIAS_VERSION_NUMERIC
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
$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
global $DIC
Definition: feed.php:28
final const STATUS_NO_ACTION
__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)
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:32