certificate.lib.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Endroid\QrCode\QrCode;
  4. /**
  5. * Certificate Class
  6. * Generate certificates based in the gradebook tool.
  7. *
  8. * @package chamilo.library.certificates
  9. */
  10. class Certificate extends Model
  11. {
  12. public $table;
  13. public $columns = [
  14. 'id',
  15. 'cat_id',
  16. 'score_certificate',
  17. 'created_at',
  18. 'path_certificate',
  19. ];
  20. /**
  21. * Certification data.
  22. */
  23. public $certificate_data = [];
  24. /**
  25. * Student's certification path.
  26. */
  27. public $certification_user_path = null;
  28. public $certification_web_user_path = null;
  29. public $html_file = null;
  30. public $qr_file = null;
  31. public $user_id;
  32. /** If true every time we enter to the certificate URL
  33. * we would generate a new certificate (good thing because we can edit the
  34. * certificate and all users will have the latest certificate bad because we.
  35. * load the certificate every time */
  36. public $force_certificate_generation = true;
  37. /**
  38. * Constructor.
  39. *
  40. * @param int $certificate_id ID of the certificate
  41. * @param int $userId
  42. * @param bool $sendNotification send message to student
  43. * @param bool $updateCertificateData
  44. *
  45. * If no ID given, take user_id and try to generate one
  46. */
  47. public function __construct(
  48. $certificate_id = 0,
  49. $userId = 0,
  50. $sendNotification = false,
  51. $updateCertificateData = true
  52. ) {
  53. $this->table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  54. $this->user_id = !empty($userId) ? $userId : api_get_user_id();
  55. if (!empty($certificate_id)) {
  56. $certificate = $this->get($certificate_id);
  57. if (!empty($certificate) && is_array($certificate)) {
  58. $this->certificate_data = $certificate;
  59. $this->user_id = $this->certificate_data['user_id'];
  60. }
  61. }
  62. if ($this->user_id) {
  63. // Need to be called before any operation
  64. $this->check_certificate_path();
  65. // To force certification generation
  66. if ($this->force_certificate_generation) {
  67. $this->generate([], $sendNotification);
  68. }
  69. if (isset($this->certificate_data) && $this->certificate_data) {
  70. if (empty($this->certificate_data['path_certificate'])) {
  71. $this->generate([], $sendNotification);
  72. }
  73. }
  74. }
  75. // Setting the qr and html variables
  76. if (isset($certificate_id) &&
  77. !empty($this->certification_user_path) &&
  78. isset($this->certificate_data['path_certificate'])
  79. ) {
  80. $pathinfo = pathinfo($this->certificate_data['path_certificate']);
  81. $this->html_file = $this->certification_user_path.basename($this->certificate_data['path_certificate']);
  82. $this->qr_file = $this->certification_user_path.$pathinfo['filename'].'_qr.png';
  83. } else {
  84. $this->check_certificate_path();
  85. if (api_get_configuration_value('allow_general_certificate')) {
  86. // General certificate
  87. $name = md5($this->user_id).'.html';
  88. $my_path_certificate = $this->certification_user_path.$name;
  89. $path_certificate = '/'.$name;
  90. // Getting QR filename
  91. $file_info = pathinfo($path_certificate);
  92. $content = $this->generateCustomCertificate();
  93. $my_new_content_html = str_replace(
  94. '((certificate_barcode))',
  95. Display::img(
  96. $this->certification_web_user_path.$file_info['filename'].'_qr.png',
  97. 'QR'
  98. ),
  99. $content
  100. );
  101. $my_new_content_html = mb_convert_encoding(
  102. $my_new_content_html,
  103. 'UTF-8',
  104. api_get_system_encoding()
  105. );
  106. $this->html_file = $my_path_certificate;
  107. $result = @file_put_contents($my_path_certificate, $my_new_content_html);
  108. if ($result) {
  109. // Updating the path
  110. self::updateUserCertificateInfo(
  111. 0,
  112. $this->user_id,
  113. $path_certificate,
  114. $updateCertificateData
  115. );
  116. $this->certificate_data['path_certificate'] = $path_certificate;
  117. }
  118. }
  119. }
  120. }
  121. /**
  122. * Checks if the certificate user path directory is created.
  123. */
  124. public function check_certificate_path()
  125. {
  126. $this->certification_user_path = null;
  127. // Setting certification path
  128. $path_info = UserManager::getUserPathById($this->user_id, 'system');
  129. $web_path_info = UserManager::getUserPathById($this->user_id, 'web');
  130. if (!empty($path_info) && isset($path_info)) {
  131. $this->certification_user_path = $path_info.'certificate/';
  132. $this->certification_web_user_path = $web_path_info.'certificate/';
  133. $mode = api_get_permissions_for_new_directories();
  134. if (!is_dir($path_info)) {
  135. mkdir($path_info, $mode, true);
  136. }
  137. if (!is_dir($this->certification_user_path)) {
  138. mkdir($this->certification_user_path, $mode);
  139. }
  140. }
  141. }
  142. /**
  143. * Deletes the current certificate object. This is generally triggered by
  144. * the teacher from the gradebook tool to re-generate the certificate because
  145. * the original version wa flawed.
  146. *
  147. * @param bool $force_delete
  148. *
  149. * @return bool
  150. */
  151. public function delete($force_delete = false)
  152. {
  153. $delete_db = false;
  154. if (!empty($this->certificate_data)) {
  155. if (!is_null($this->html_file) || $this->html_file != '' || strlen($this->html_file)) {
  156. // Deleting HTML file
  157. if (is_file($this->html_file)) {
  158. @unlink($this->html_file);
  159. if (is_file($this->html_file) === false) {
  160. $delete_db = true;
  161. } else {
  162. $delete_db = false;
  163. }
  164. }
  165. // Deleting QR code PNG image file
  166. if (is_file($this->qr_file)) {
  167. @unlink($this->qr_file);
  168. }
  169. if ($delete_db || $force_delete) {
  170. return parent::delete($this->certificate_data['id']);
  171. }
  172. } else {
  173. return parent::delete($this->certificate_data['id']);
  174. }
  175. }
  176. return false;
  177. }
  178. /**
  179. * Generates an HTML Certificate and fills the path_certificate field in the DB.
  180. *
  181. * @param array $params
  182. * @param bool $sendNotification
  183. *
  184. * @return bool|int
  185. */
  186. public function generate($params = [], $sendNotification = false)
  187. {
  188. // The user directory should be set
  189. if (empty($this->certification_user_path) &&
  190. $this->force_certificate_generation === false
  191. ) {
  192. return false;
  193. }
  194. $params['hide_print_button'] = isset($params['hide_print_button']) ? true : false;
  195. $categoryId = 0;
  196. $my_category = [];
  197. if (isset($this->certificate_data) && isset($this->certificate_data['cat_id'])) {
  198. $categoryId = $this->certificate_data['cat_id'];
  199. $my_category = Category::load($categoryId);
  200. }
  201. if (isset($my_category[0]) && !empty($categoryId) &&
  202. $my_category[0]->is_certificate_available($this->user_id)
  203. ) {
  204. /** @var Category $category */
  205. $category = $my_category[0];
  206. $courseInfo = api_get_course_info($category->get_course_code());
  207. $courseId = $courseInfo['real_id'];
  208. $sessionId = $category->get_session_id();
  209. $skill = new Skill();
  210. $skill->addSkillToUser(
  211. $this->user_id,
  212. $category,
  213. $courseId,
  214. $sessionId
  215. );
  216. if (is_dir($this->certification_user_path)) {
  217. if (!empty($this->certificate_data)) {
  218. $new_content_html = GradebookUtils::get_user_certificate_content(
  219. $this->user_id,
  220. $category->get_course_code(),
  221. $category->get_session_id(),
  222. false,
  223. $params['hide_print_button']
  224. );
  225. if ($category->get_id() == $categoryId) {
  226. $name = $this->certificate_data['path_certificate'];
  227. $myPathCertificate = $this->certification_user_path.basename($name);
  228. if (file_exists($myPathCertificate) &&
  229. !empty($name) &&
  230. !is_dir($myPathCertificate) &&
  231. $this->force_certificate_generation == false
  232. ) {
  233. // Seems that the file was already generated
  234. return true;
  235. } else {
  236. // Creating new name
  237. $name = md5($this->user_id.$this->certificate_data['cat_id']).'.html';
  238. $myPathCertificate = $this->certification_user_path.$name;
  239. $path_certificate = '/'.$name;
  240. // Getting QR filename
  241. $file_info = pathinfo($path_certificate);
  242. $qr_code_filename = $this->certification_user_path.$file_info['filename'].'_qr.png';
  243. $newContent = str_replace(
  244. '((certificate_barcode))',
  245. Display::img(
  246. $this->certification_web_user_path.$file_info['filename'].'_qr.png',
  247. 'QR'
  248. ),
  249. $new_content_html['content']
  250. );
  251. $newContent = api_convert_encoding(
  252. $newContent,
  253. 'UTF-8',
  254. api_get_system_encoding()
  255. );
  256. $result = @file_put_contents($myPathCertificate, $newContent);
  257. if ($result) {
  258. // Updating the path
  259. $this->updateUserCertificateInfo(
  260. $this->certificate_data['cat_id'],
  261. $this->user_id,
  262. $path_certificate
  263. );
  264. $this->certificate_data['path_certificate'] = $path_certificate;
  265. if ($this->isHtmlFileGenerated()) {
  266. if (!empty($file_info)) {
  267. $text = $this->parseCertificateVariables(
  268. $new_content_html['variables']
  269. );
  270. $this->generateQRImage(
  271. $text,
  272. $qr_code_filename
  273. );
  274. if ($sendNotification) {
  275. $subject = get_lang('Certificate notification');
  276. $message = nl2br(get_lang('((user_first_name)),'));
  277. $score = $this->certificate_data['score_certificate'];
  278. self::sendNotification(
  279. $subject,
  280. $message,
  281. api_get_user_info($this->user_id),
  282. $courseInfo,
  283. [
  284. 'score_certificate' => $score,
  285. ]
  286. );
  287. }
  288. }
  289. }
  290. }
  291. return $result;
  292. }
  293. }
  294. }
  295. }
  296. } else {
  297. $this->check_certificate_path();
  298. // General certificate
  299. $name = md5($this->user_id).'.html';
  300. $my_path_certificate = $this->certification_user_path.$name;
  301. $path_certificate = '/'.$name;
  302. // Getting QR filename
  303. $file_info = pathinfo($path_certificate);
  304. $content = $this->generateCustomCertificate();
  305. $my_new_content_html = str_replace(
  306. '((certificate_barcode))',
  307. Display::img(
  308. $this->certification_web_user_path.$file_info['filename'].'_qr.png',
  309. 'QR'
  310. ),
  311. $content
  312. );
  313. $my_new_content_html = mb_convert_encoding(
  314. $my_new_content_html,
  315. 'UTF-8',
  316. api_get_system_encoding()
  317. );
  318. $result = @file_put_contents($my_path_certificate, $my_new_content_html);
  319. if ($result) {
  320. // Updating the path
  321. self::updateUserCertificateInfo(
  322. 0,
  323. $this->user_id,
  324. $path_certificate
  325. );
  326. $this->certificate_data['path_certificate'] = $path_certificate;
  327. }
  328. return $result;
  329. }
  330. return false;
  331. }
  332. /**
  333. * @return array
  334. */
  335. public static function notificationTags()
  336. {
  337. $tags = [
  338. '((course_title))',
  339. '((user_first_name))',
  340. '((user_last_name))',
  341. '((author_first_name))',
  342. '((author_last_name))',
  343. '((score))',
  344. '((portal_name))',
  345. '((certificate_link))',
  346. ];
  347. return $tags;
  348. }
  349. /**
  350. * @param string $subject
  351. * @param string $message
  352. * @param array $userInfo
  353. * @param array $courseInfo
  354. * @param array $certificateInfo
  355. *
  356. * @return bool
  357. */
  358. public static function sendNotification(
  359. $subject,
  360. $message,
  361. $userInfo,
  362. $courseInfo,
  363. $certificateInfo
  364. ) {
  365. if (empty($userInfo) || empty($courseInfo)) {
  366. return false;
  367. }
  368. $currentUserInfo = api_get_user_info();
  369. $url = api_get_path(WEB_PATH).
  370. 'certificates/index.php?id='.$certificateInfo['id'].'&user_id='.$certificateInfo['user_id'];
  371. $link = Display::url($url, $url);
  372. $replace = [
  373. $courseInfo['title'],
  374. $userInfo['firstname'],
  375. $userInfo['lastname'],
  376. $currentUserInfo['firstname'],
  377. $currentUserInfo['lastname'],
  378. $certificateInfo['score_certificate'],
  379. api_get_setting('Institution'),
  380. $link,
  381. ];
  382. $message = str_replace(self::notificationTags(), $replace, $message);
  383. MessageManager::send_message(
  384. $userInfo['id'],
  385. $subject,
  386. $message,
  387. [],
  388. [],
  389. 0,
  390. 0,
  391. 0,
  392. 0,
  393. $currentUserInfo['id']
  394. );
  395. $plugin = new AppPlugin();
  396. $smsPlugin = $plugin->getSMSPluginLibrary();
  397. if ($smsPlugin) {
  398. $additionalParameters = [
  399. 'smsType' => SmsPlugin::CERTIFICATE_NOTIFICATION,
  400. 'userId' => $userInfo['id'],
  401. 'direct_message' => $message,
  402. ];
  403. $smsPlugin->send($additionalParameters);
  404. }
  405. }
  406. /**
  407. * Update user info about certificate.
  408. *
  409. * @param int $categoryId category id
  410. * @param int $user_id user id
  411. * @param string $path_certificate the path name of the certificate
  412. * @param bool $updateCertificateData
  413. */
  414. public function updateUserCertificateInfo(
  415. $categoryId,
  416. $user_id,
  417. $path_certificate,
  418. $updateCertificateData = true
  419. ) {
  420. $categoryId = (int) $categoryId;
  421. $user_id = (int) $user_id;
  422. if ($updateCertificateData &&
  423. !UserManager::is_user_certified($categoryId, $user_id)
  424. ) {
  425. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  426. $now = api_get_utc_datetime();
  427. $sql = 'UPDATE '.$table.' SET
  428. path_certificate="'.Database::escape_string($path_certificate).'",
  429. created_at = "'.$now.'"
  430. WHERE cat_id = "'.$categoryId.'" AND user_id="'.$user_id.'" ';
  431. Database::query($sql);
  432. }
  433. }
  434. /**
  435. * Check if the file was generated.
  436. *
  437. * @return bool
  438. */
  439. public function isHtmlFileGenerated()
  440. {
  441. if (empty($this->certification_user_path)) {
  442. return false;
  443. }
  444. if (!empty($this->certificate_data) &&
  445. isset($this->certificate_data['path_certificate']) &&
  446. !empty($this->certificate_data['path_certificate'])
  447. ) {
  448. return true;
  449. }
  450. return false;
  451. }
  452. /**
  453. * Generates a QR code for the certificate. The QR code embeds the text given.
  454. *
  455. * @param string $text Text to be added in the QR code
  456. * @param string $path file path of the image
  457. *
  458. * @return bool
  459. */
  460. public function generateQRImage($text, $path)
  461. {
  462. // Make sure HTML certificate is generated
  463. if (!empty($text) && !empty($path)) {
  464. $qrCode = new QrCode($text);
  465. $qrCode->setWriterByName('png');
  466. $qrCode->writeFile($path);
  467. //L low, M - Medium, L large error correction
  468. //return QrCode::png($text, $path, 'M', 2, 2);
  469. return file_exists($path);
  470. }
  471. return false;
  472. }
  473. /**
  474. * Transforms certificate tags into text values. This function is very static
  475. * (it doesn't allow for much flexibility in terms of what tags are printed).
  476. *
  477. * @param array $array Contains two array entries: first are the headers,
  478. * second is an array of contents
  479. *
  480. * @return string The translated string
  481. */
  482. public function parseCertificateVariables($array)
  483. {
  484. $headers = $array[0];
  485. $content = $array[1];
  486. $final_content = [];
  487. if (!empty($content)) {
  488. foreach ($content as $key => $value) {
  489. $my_header = str_replace(['((', '))'], '', $headers[$key]);
  490. $final_content[$my_header] = $value;
  491. }
  492. }
  493. /* Certificate tags
  494. *
  495. 0 => string '((user_firstname))' (length=18)
  496. 1 => string '((user_lastname))' (length=17)
  497. 2 => string '((gradebook_institution))' (length=25)
  498. 3 => string '((gradebook_sitename))' (length=22)
  499. 4 => string '((teacher_firstname))' (length=21)
  500. 5 => string '((teacher_lastname))' (length=20)
  501. 6 => string '((official_code))' (length=17)
  502. 7 => string '((date_certificate))' (length=20)
  503. 8 => string '((course_code))' (length=15)
  504. 9 => string '((course_title))' (length=16)
  505. 10 => string '((gradebook_grade))' (length=19)
  506. 11 => string '((certificate_link))' (length=20)
  507. 12 => string '((certificate_link_html))' (length=25)
  508. 13 => string '((certificate_barcode))' (length=23)
  509. */
  510. $break_space = " \n\r ";
  511. $text =
  512. $final_content['gradebook_institution'].' - '.
  513. $final_content['gradebook_sitename'].' - '.
  514. get_lang('Certification').$break_space.
  515. get_lang('Learner').': '.$final_content['user_firstname'].' '.$final_content['user_lastname'].$break_space.
  516. get_lang('Trainer').': '.$final_content['teacher_firstname'].' '.$final_content['teacher_lastname'].$break_space.
  517. get_lang('Date').': '.$final_content['date_certificate'].$break_space.
  518. get_lang('Score').': '.$final_content['gradebook_grade'].$break_space.
  519. 'URL'.': '.$final_content['certificate_link'];
  520. return $text;
  521. }
  522. /**
  523. * Check if the certificate is visible for the current user
  524. * If the global setting allow_public_certificates is set to 'false', no certificate can be printed.
  525. * If the global allow_public_certificates is set to 'true' and the course setting allow_public_certificates
  526. * is set to 0, no certificate *in this course* can be printed (for anonymous users).
  527. * Connected users can always print them.
  528. *
  529. * @return bool
  530. */
  531. public function isVisible()
  532. {
  533. if (!api_is_anonymous()) {
  534. return true;
  535. }
  536. if (api_get_setting('allow_public_certificates') != 'true') {
  537. // The "non-public" setting is set, so do not print
  538. return false;
  539. }
  540. if (!isset($this->certificate_data, $this->certificate_data['cat_id'])) {
  541. return false;
  542. }
  543. $gradeBook = new Gradebook();
  544. $gradeBookInfo = $gradeBook->get($this->certificate_data['cat_id']);
  545. if (empty($gradeBookInfo['course_code'])) {
  546. return false;
  547. }
  548. $setting = api_get_course_setting(
  549. 'allow_public_certificates',
  550. api_get_course_info($gradeBookInfo['course_code'])
  551. );
  552. if ($setting == 0) {
  553. // Printing not allowed
  554. return false;
  555. }
  556. return true;
  557. }
  558. /**
  559. * Check if the certificate is available.
  560. *
  561. * @return bool
  562. */
  563. public function isAvailable()
  564. {
  565. if (empty($this->certificate_data['path_certificate'])) {
  566. return false;
  567. }
  568. $userCertificate = $this->certification_user_path.basename($this->certificate_data['path_certificate']);
  569. if (!file_exists($userCertificate)) {
  570. return false;
  571. }
  572. return true;
  573. }
  574. /**
  575. * Shows the student's certificate (HTML file).
  576. */
  577. public function show()
  578. {
  579. $user_certificate = $this->certification_user_path.basename($this->certificate_data['path_certificate']);
  580. if (file_exists($user_certificate)) {
  581. // Needed in order to browsers don't add custom CSS
  582. $certificateContent = '<!DOCTYPE html>';
  583. $certificateContent .= (string) file_get_contents($user_certificate);
  584. // Remove media=screen to be available when printing a document
  585. $certificateContent = str_replace(
  586. ' media="screen"',
  587. '',
  588. $certificateContent
  589. );
  590. if ($this->user_id == api_get_user_id() &&
  591. !empty($this->certificate_data) &&
  592. isset($this->certificate_data['id'])
  593. ) {
  594. $certificateId = $this->certificate_data['id'];
  595. $extraFieldValue = new ExtraFieldValue('user_certificate');
  596. $value = $extraFieldValue->get_values_by_handler_and_field_variable(
  597. $certificateId,
  598. 'downloaded_at'
  599. );
  600. if (empty($value)) {
  601. $params = [
  602. 'item_id' => $this->certificate_data['id'],
  603. 'extra_downloaded_at' => api_get_utc_datetime(),
  604. ];
  605. $extraFieldValue->saveFieldValues($params);
  606. }
  607. }
  608. header('Content-Type: text/html; charset='.api_get_system_encoding());
  609. echo $certificateContent;
  610. return;
  611. }
  612. api_not_allowed(true);
  613. }
  614. /**
  615. * @return string
  616. */
  617. public function generateCustomCertificate()
  618. {
  619. $myCertificate = GradebookUtils::get_certificate_by_user_id(
  620. 0,
  621. $this->user_id
  622. );
  623. if (empty($myCertificate)) {
  624. GradebookUtils::registerUserInfoAboutCertificate(
  625. 0,
  626. $this->user_id,
  627. 100,
  628. api_get_utc_datetime()
  629. );
  630. }
  631. $userInfo = api_get_user_info($this->user_id);
  632. $extraFieldValue = new ExtraFieldValue('user');
  633. $value = $extraFieldValue->get_values_by_handler_and_field_variable($this->user_id, 'legal_accept');
  634. $termsValidationDate = '';
  635. if (isset($value) && !empty($value['value'])) {
  636. list($id, $id2, $termsValidationDate) = explode(':', $value['value']);
  637. }
  638. $sessions = SessionManager::get_sessions_by_user($this->user_id, false, true);
  639. $totalTimeInLearningPaths = 0;
  640. $sessionsApproved = [];
  641. $coursesApproved = [];
  642. if ($sessions) {
  643. foreach ($sessions as $session) {
  644. $allCoursesApproved = [];
  645. foreach ($session['courses'] as $course) {
  646. $courseInfo = api_get_course_info_by_id($course['real_id']);
  647. $courseCode = $courseInfo['code'];
  648. $gradebookCategories = Category::load(
  649. null,
  650. null,
  651. $courseCode,
  652. null,
  653. false,
  654. $session['session_id']
  655. );
  656. if (isset($gradebookCategories[0])) {
  657. /** @var Category $category */
  658. $category = $gradebookCategories[0];
  659. $result = Category::userFinishedCourse(
  660. $this->user_id,
  661. $category,
  662. true
  663. );
  664. if ($result) {
  665. $coursesApproved[$course['real_id']] = $courseInfo['title'];
  666. // Find time spent in LP
  667. $totalTimeInLearningPaths += Tracking::get_time_spent_in_lp(
  668. $this->user_id,
  669. $courseCode,
  670. [],
  671. $session['session_id']
  672. );
  673. $allCoursesApproved[] = true;
  674. }
  675. }
  676. }
  677. if (count($allCoursesApproved) == count($session['courses'])) {
  678. $sessionsApproved[] = $session;
  679. }
  680. }
  681. }
  682. $skill = new Skill();
  683. // Ofaj
  684. $skills = $skill->getStudentSkills($this->user_id, 2);
  685. $timeInSeconds = Tracking::get_time_spent_on_the_platform(
  686. $this->user_id,
  687. 'ever'
  688. );
  689. $time = api_time_to_hms($timeInSeconds);
  690. $tplContent = new Template(null, false, false, false, false, false);
  691. // variables for the default template
  692. $tplContent->assign('complete_name', $userInfo['complete_name']);
  693. $tplContent->assign('time_in_platform', $time);
  694. $tplContent->assign('certificate_generated_date', api_get_local_time($myCertificate['created_at']));
  695. if (!empty($termsValidationDate)) {
  696. $termsValidationDate = api_get_local_time($termsValidationDate);
  697. }
  698. $tplContent->assign('terms_validation_date', $termsValidationDate);
  699. // Ofaj
  700. $tplContent->assign('time_in_platform_in_hours', round($timeInSeconds / 3600, 1));
  701. $tplContent->assign(
  702. 'certificate_generated_date_no_time',
  703. api_get_local_time(
  704. $myCertificate['created_at'],
  705. null,
  706. null,
  707. false,
  708. false
  709. )
  710. );
  711. $tplContent->assign(
  712. 'terms_validation_date_no_time',
  713. api_get_local_time(
  714. $termsValidationDate,
  715. null,
  716. null,
  717. false,
  718. false
  719. )
  720. );
  721. $tplContent->assign('skills', $skills);
  722. $tplContent->assign('sessions', $sessionsApproved);
  723. $tplContent->assign('courses', $coursesApproved);
  724. $tplContent->assign('time_spent_in_lps', api_time_to_hms($totalTimeInLearningPaths));
  725. $tplContent->assign('time_spent_in_lps_in_hours', round($totalTimeInLearningPaths / 3600, 1));
  726. $layoutContent = $tplContent->get_template('gradebook/custom_certificate.tpl');
  727. $content = $tplContent->fetch($layoutContent);
  728. return $content;
  729. }
  730. /**
  731. * Ofaj.
  732. */
  733. public function generatePdfFromCustomCertificate()
  734. {
  735. $orientation = api_get_configuration_value('certificate_pdf_orientation');
  736. $params['orientation'] = 'landscape';
  737. if (!empty($orientation)) {
  738. $params['orientation'] = $orientation;
  739. }
  740. $params['left'] = 0;
  741. $params['right'] = 0;
  742. $params['top'] = 0;
  743. $params['bottom'] = 0;
  744. $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
  745. $pdf = new PDF($page_format, $params['orientation'], $params);
  746. $pdf->html_to_pdf(
  747. $this->html_file,
  748. get_lang('Certificates'),
  749. null,
  750. false,
  751. false
  752. );
  753. }
  754. /**
  755. * @param int $userId
  756. *
  757. * @return array
  758. */
  759. public static function getCertificateByUser($userId)
  760. {
  761. $userId = (int) $userId;
  762. if (empty($userId)) {
  763. return [];
  764. }
  765. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  766. $sql = "SELECT * FROM $table
  767. WHERE user_id= $userId";
  768. $rs = Database::query($sql);
  769. return Database::store_result($rs, 'ASSOC');
  770. }
  771. /**
  772. * @param int $userId
  773. */
  774. public static function generateUserSkills($userId)
  775. {
  776. $controller = new IndexManager(get_lang('My courses'));
  777. $courseAndSessions = $controller->returnCoursesAndSessions($userId, true, null, true, false);
  778. if (isset($courseAndSessions['courses']) && !empty($courseAndSessions['courses'])) {
  779. foreach ($courseAndSessions['courses'] as $course) {
  780. $cats = Category::load(
  781. null,
  782. null,
  783. $course['code'],
  784. null,
  785. null,
  786. null,
  787. false
  788. );
  789. if (isset($cats[0]) && !empty($cats[0])) {
  790. Category::generateUserCertificate(
  791. $cats[0]->get_id(),
  792. $userId
  793. );
  794. }
  795. }
  796. }
  797. if (isset($courseAndSessions['sessions']) && !empty($courseAndSessions['sessions'])) {
  798. foreach ($courseAndSessions['sessions'] as $sessionCategory) {
  799. if (isset($sessionCategory['sessions'])) {
  800. foreach ($sessionCategory['sessions'] as $sessionData) {
  801. if (!empty($sessionData['courses'])) {
  802. $sessionId = $sessionData['session_id'];
  803. foreach ($sessionData['courses'] as $courseData) {
  804. $cats = Category:: load(
  805. null,
  806. null,
  807. $courseData['course_code'],
  808. null,
  809. null,
  810. $sessionId,
  811. false
  812. );
  813. if (isset($cats[0]) && !empty($cats[0])) {
  814. Category::generateUserCertificate(
  815. $cats[0]->get_id(),
  816. $userId
  817. );
  818. }
  819. }
  820. }
  821. }
  822. }
  823. }
  824. }
  825. }
  826. }