certificate.lib.php 30 KB

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