certificate.lib.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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. /** @var Category $category */
  207. $category = $my_category[0];
  208. $courseInfo = api_get_course_info($category->get_course_code());
  209. $courseId = $courseInfo['real_id'];
  210. $sessionId = $category->get_session_id();
  211. $skill = new Skill();
  212. $skill->addSkillToUser(
  213. $this->user_id,
  214. $category,
  215. $courseId,
  216. $sessionId
  217. );
  218. if (is_dir($this->certification_user_path)) {
  219. if (!empty($this->certificate_data)) {
  220. $new_content_html = GradebookUtils::get_user_certificate_content(
  221. $this->user_id,
  222. $category->get_course_code(),
  223. $category->get_session_id(),
  224. false,
  225. $params['hide_print_button']
  226. );
  227. if ($category->get_id() == $categoryId) {
  228. $name = $this->certificate_data['path_certificate'];
  229. $myPathCertificate = $this->certification_user_path.basename($name);
  230. if (file_exists($myPathCertificate) &&
  231. !empty($name) &&
  232. !is_dir($myPathCertificate) &&
  233. $this->force_certificate_generation == false
  234. ) {
  235. //Seems that the file was already generated
  236. return true;
  237. } else {
  238. // Creating new name
  239. $name = md5($this->user_id.$this->certificate_data['cat_id']).'.html';
  240. $myPathCertificate = $this->certification_user_path.$name;
  241. $path_certificate = '/'.$name;
  242. // Getting QR filename
  243. $file_info = pathinfo($path_certificate);
  244. $qr_code_filename = $this->certification_user_path.$file_info['filename'].'_qr.png';
  245. $newContent = str_replace(
  246. '((certificate_barcode))',
  247. Display::img(
  248. $this->certification_web_user_path.$file_info['filename'].'_qr.png',
  249. 'QR'
  250. ),
  251. $new_content_html['content']
  252. );
  253. $newContent = api_convert_encoding(
  254. $newContent,
  255. 'UTF-8',
  256. api_get_system_encoding()
  257. );
  258. $result = @file_put_contents($myPathCertificate, $newContent);
  259. if ($result) {
  260. // Updating the path
  261. $this->updateUserCertificateInfo(
  262. $this->certificate_data['cat_id'],
  263. $this->user_id,
  264. $path_certificate
  265. );
  266. $this->certificate_data['path_certificate'] = $path_certificate;
  267. if ($this->isHtmlFileGenerated()) {
  268. if (!empty($file_info)) {
  269. $text = $this->parseCertificateVariables(
  270. $new_content_html['variables']
  271. );
  272. $this->generateQRImage(
  273. $text,
  274. $qr_code_filename
  275. );
  276. if ($sendNotification) {
  277. $subject = get_lang('NotificationCertificateSubject');
  278. $message = nl2br(get_lang('NotificationCertificateTemplate'));
  279. $score = $this->certificate_data['score_certificate'];
  280. self::sendNotification(
  281. $subject,
  282. $message,
  283. api_get_user_info($this->user_id),
  284. $courseInfo,
  285. [
  286. 'score_certificate' => $score,
  287. ]
  288. );
  289. }
  290. }
  291. }
  292. }
  293. return $result;
  294. }
  295. }
  296. }
  297. }
  298. } else {
  299. // General certificate
  300. $name = md5($this->user_id).'.html';
  301. $my_path_certificate = $this->certification_user_path.$name;
  302. $path_certificate = '/'.$name;
  303. // Getting QR filename
  304. $file_info = pathinfo($path_certificate);
  305. $content = $this->generateCustomCertificate();
  306. $my_new_content_html = str_replace(
  307. '((certificate_barcode))',
  308. Display::img(
  309. $this->certification_web_user_path.$file_info['filename'].'_qr.png',
  310. 'QR'
  311. ),
  312. $content
  313. );
  314. $my_new_content_html = mb_convert_encoding(
  315. $my_new_content_html,
  316. 'UTF-8',
  317. api_get_system_encoding()
  318. );
  319. $result = @file_put_contents($my_path_certificate, $my_new_content_html);
  320. if ($result) {
  321. // Updating the path
  322. self::updateUserCertificateInfo(
  323. 0,
  324. $this->user_id,
  325. $path_certificate
  326. );
  327. $this->certificate_data['path_certificate'] = $path_certificate;
  328. if ($this->isHtmlFileGenerated()) {
  329. if (!empty($file_info)) {
  330. //$text = $this->parse_certificate_variables($new_content_html['variables']);
  331. //$this->generate_qr($text, $qr_code_filename);
  332. }
  333. }
  334. }
  335. return $result;
  336. }
  337. return false;
  338. }
  339. /**
  340. * @return array
  341. */
  342. public static function notificationTags()
  343. {
  344. $tags = [
  345. '((course_title))',
  346. '((user_first_name))',
  347. '((user_last_name))',
  348. '((author_first_name))',
  349. '((author_last_name))',
  350. '((score))',
  351. '((portal_name))',
  352. '((certificate_link))',
  353. ];
  354. return $tags;
  355. }
  356. /**
  357. * @param string $subject
  358. * @param string $message
  359. * @param array $userInfo
  360. * @param array $courseInfo
  361. * @param array $certificateInfo
  362. *
  363. * @return bool
  364. */
  365. public static function sendNotification(
  366. $subject,
  367. $message,
  368. $userInfo,
  369. $courseInfo,
  370. $certificateInfo
  371. ) {
  372. if (empty($userInfo) || empty($courseInfo)) {
  373. return false;
  374. }
  375. $currentUserInfo = api_get_user_info();
  376. $url = api_get_path(WEB_PATH).
  377. 'certificates/index.php?id='.$certificateInfo['id'].'&user_id='.$certificateInfo['user_id'];
  378. $link = Display::url($url, $url);
  379. $replace = [
  380. $courseInfo['title'],
  381. $userInfo['firstname'],
  382. $userInfo['lastname'],
  383. $currentUserInfo['firstname'],
  384. $currentUserInfo['lastname'],
  385. $certificateInfo['score_certificate'],
  386. api_get_setting('Institution'),
  387. $link,
  388. ];
  389. $message = str_replace(self::notificationTags(), $replace, $message);
  390. MessageManager::send_message(
  391. $userInfo['id'],
  392. $subject,
  393. $message,
  394. [],
  395. [],
  396. 0,
  397. 0,
  398. 0,
  399. 0,
  400. $currentUserInfo['id']
  401. );
  402. $plugin = new AppPlugin();
  403. $smsPlugin = $plugin->getSMSPluginLibrary();
  404. if ($smsPlugin) {
  405. $additionalParameters = [
  406. 'smsType' => SmsPlugin::CERTIFICATE_NOTIFICATION,
  407. 'userId' => $userInfo['id'],
  408. 'direct_message' => $message,
  409. ];
  410. $smsPlugin->send($additionalParameters);
  411. }
  412. }
  413. /**
  414. * Update user info about certificate.
  415. *
  416. * @param int $categoryId category id
  417. * @param int $user_id user id
  418. * @param string $path_certificate the path name of the certificate
  419. * @param bool $updateCertificateData
  420. */
  421. public function updateUserCertificateInfo(
  422. $categoryId,
  423. $user_id,
  424. $path_certificate,
  425. $updateCertificateData = true
  426. ) {
  427. $categoryId = (int) $categoryId;
  428. $user_id = (int) $user_id;
  429. if ($updateCertificateData &&
  430. !UserManager::is_user_certified($categoryId, $user_id)
  431. ) {
  432. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  433. $now = api_get_utc_datetime();
  434. $sql = 'UPDATE '.$table.' SET
  435. path_certificate="'.Database::escape_string($path_certificate).'",
  436. created_at = "'.$now.'"
  437. WHERE cat_id = "'.$categoryId.'" AND user_id="'.$user_id.'" ';
  438. Database::query($sql);
  439. }
  440. }
  441. /**
  442. * Check if the file was generated.
  443. *
  444. * @return bool
  445. */
  446. public function isHtmlFileGenerated()
  447. {
  448. if (empty($this->certification_user_path)) {
  449. return false;
  450. }
  451. if (!empty($this->certificate_data) &&
  452. isset($this->certificate_data['path_certificate']) &&
  453. !empty($this->certificate_data['path_certificate'])
  454. ) {
  455. return true;
  456. }
  457. return false;
  458. }
  459. /**
  460. * Generates a QR code for the certificate. The QR code embeds the text given.
  461. *
  462. * @param string $text Text to be added in the QR code
  463. * @param string $path file path of the image
  464. *
  465. * @return bool
  466. */
  467. public function generateQRImage($text, $path)
  468. {
  469. // Make sure HTML certificate is generated
  470. if (!empty($text) && !empty($path)) {
  471. //L low, M - Medium, L large error correction
  472. return PHPQRCode\QRcode::png($text, $path, 'M', 2, 2);
  473. }
  474. return false;
  475. }
  476. /**
  477. * Transforms certificate tags into text values. This function is very static
  478. * (it doesn't allow for much flexibility in terms of what tags are printed).
  479. *
  480. * @param array $array Contains two array entries: first are the headers,
  481. * second is an array of contents
  482. *
  483. * @return string The translated string
  484. */
  485. public function parseCertificateVariables($array)
  486. {
  487. $headers = $array[0];
  488. $content = $array[1];
  489. $final_content = [];
  490. if (!empty($content)) {
  491. foreach ($content as $key => $value) {
  492. $my_header = str_replace(['((', '))'], '', $headers[$key]);
  493. $final_content[$my_header] = $value;
  494. }
  495. }
  496. /* Certificate tags
  497. *
  498. 0 => string '((user_firstname))' (length=18)
  499. 1 => string '((user_lastname))' (length=17)
  500. 2 => string '((gradebook_institution))' (length=25)
  501. 3 => string '((gradebook_sitename))' (length=22)
  502. 4 => string '((teacher_firstname))' (length=21)
  503. 5 => string '((teacher_lastname))' (length=20)
  504. 6 => string '((official_code))' (length=17)
  505. 7 => string '((date_certificate))' (length=20)
  506. 8 => string '((course_code))' (length=15)
  507. 9 => string '((course_title))' (length=16)
  508. 10 => string '((gradebook_grade))' (length=19)
  509. 11 => string '((certificate_link))' (length=20)
  510. 12 => string '((certificate_link_html))' (length=25)
  511. 13 => string '((certificate_barcode))' (length=23)
  512. */
  513. $break_space = " \n\r ";
  514. $text =
  515. $final_content['gradebook_institution'].' - '.
  516. $final_content['gradebook_sitename'].' - '.
  517. get_lang('Certification').$break_space.
  518. get_lang('Student').': '.$final_content['user_firstname'].' '.$final_content['user_lastname'].$break_space.
  519. get_lang('Teacher').': '.$final_content['teacher_firstname'].' '.$final_content['teacher_lastname'].$break_space.
  520. get_lang('Date').': '.$final_content['date_certificate'].$break_space.
  521. get_lang('Score').': '.$final_content['gradebook_grade'].$break_space.
  522. 'URL'.': '.$final_content['certificate_link'];
  523. return $text;
  524. }
  525. /**
  526. * Check if the certificate is visible for the current user
  527. * If the global setting allow_public_certificates is set to 'false', no certificate can be printed.
  528. * If the global allow_public_certificates is set to 'true' and the course setting allow_public_certificates
  529. * is set to 0, no certificate *in this course* can be printed (for anonymous users).
  530. * Connected users can always print them.
  531. *
  532. * @return bool
  533. */
  534. public function isVisible()
  535. {
  536. if (!api_is_anonymous()) {
  537. return true;
  538. }
  539. if (api_get_setting('allow_public_certificates') != 'true') {
  540. // The "non-public" setting is set, so do not print
  541. return false;
  542. }
  543. if (!isset($this->certificate_data, $this->certificate_data['cat_id'])) {
  544. return false;
  545. }
  546. $gradeBook = new Gradebook();
  547. $gradeBookInfo = $gradeBook->get($this->certificate_data['cat_id']);
  548. if (empty($gradeBookInfo['course_code'])) {
  549. return false;
  550. }
  551. if (api_get_course_setting('allow_public_certificates', $gradeBookInfo['course_code']) == 0) {
  552. // Printing not allowed
  553. return false;
  554. }
  555. return true;
  556. }
  557. /**
  558. * Check if the certificate is available.
  559. *
  560. * @return bool
  561. */
  562. public function isAvailable()
  563. {
  564. if (empty($this->certificate_data['path_certificate'])) {
  565. return false;
  566. }
  567. $user_certificate = $this->certification_user_path.basename($this->certificate_data['path_certificate']);
  568. if (!file_exists($user_certificate)) {
  569. return false;
  570. }
  571. return true;
  572. }
  573. /**
  574. * Shows the student's certificate (HTML file).
  575. */
  576. public function show()
  577. {
  578. header('Content-Type: text/html; charset='.api_get_system_encoding());
  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() && !empty($this->certificate_data)) {
  591. $certificateId = $this->certificate_data['id'];
  592. $extraFieldValue = new ExtraFieldValue('user_certificate');
  593. $value = $extraFieldValue->get_values_by_handler_and_field_variable(
  594. $certificateId,
  595. 'downloaded_at'
  596. );
  597. if (empty($value)) {
  598. $params = [
  599. 'item_id' => $this->certificate_data['id'],
  600. 'extra_downloaded_at' => api_get_utc_datetime(),
  601. ];
  602. $extraFieldValue->saveFieldValues($params);
  603. }
  604. }
  605. echo $certificateContent;
  606. return;
  607. }
  608. api_not_allowed(true);
  609. }
  610. /**
  611. * @return string
  612. */
  613. public function generateCustomCertificate()
  614. {
  615. $myCertificate = GradebookUtils::get_certificate_by_user_id(
  616. 0,
  617. $this->user_id
  618. );
  619. if (empty($myCertificate)) {
  620. GradebookUtils::registerUserInfoAboutCertificate(
  621. 0,
  622. $this->user_id,
  623. 100,
  624. api_get_utc_datetime()
  625. );
  626. }
  627. $userInfo = api_get_user_info($this->user_id);
  628. $extraFieldValue = new ExtraFieldValue('user');
  629. $value = $extraFieldValue->get_values_by_handler_and_field_variable($this->user_id, 'legal_accept');
  630. $termsValidationDate = '';
  631. if (isset($value) && !empty($value['value'])) {
  632. list($id, $id2, $termsValidationDate) = explode(':', $value['value']);
  633. }
  634. $sessions = SessionManager::get_sessions_by_user($this->user_id, false, true);
  635. $totalTimeInLearningPaths = 0;
  636. $sessionsApproved = [];
  637. $coursesApproved = [];
  638. if ($sessions) {
  639. foreach ($sessions as $session) {
  640. $allCoursesApproved = [];
  641. foreach ($session['courses'] as $course) {
  642. $courseInfo = api_get_course_info_by_id($course['real_id']);
  643. $courseCode = $courseInfo['code'];
  644. $gradebookCategories = Category::load(
  645. null,
  646. null,
  647. $courseCode,
  648. null,
  649. false,
  650. $session['session_id']
  651. );
  652. if (isset($gradebookCategories[0])) {
  653. /** @var Category $category */
  654. $category = $gradebookCategories[0];
  655. $result = Category::userFinishedCourse(
  656. $this->user_id,
  657. $category,
  658. true
  659. );
  660. if ($result) {
  661. $coursesApproved[$course['real_id']] = $courseInfo['title'];
  662. // Find time spent in LP
  663. $totalTimeInLearningPaths += Tracking::get_time_spent_in_lp(
  664. $this->user_id,
  665. $courseCode,
  666. [],
  667. $session['session_id']
  668. );
  669. $allCoursesApproved[] = true;
  670. }
  671. }
  672. }
  673. if (count($allCoursesApproved) == count($session['courses'])) {
  674. $sessionsApproved[] = $session;
  675. }
  676. }
  677. }
  678. $skill = new Skill();
  679. // Ofaj
  680. $skills = $skill->getStudentSkills($this->user_id, 2);
  681. $timeInSeconds = Tracking::get_time_spent_on_the_platform(
  682. $this->user_id,
  683. 'ever'
  684. );
  685. $time = api_time_to_hms($timeInSeconds);
  686. $tplContent = new Template(null, false, false, false, false, false);
  687. // variables for the default template
  688. $tplContent->assign('complete_name', $userInfo['complete_name']);
  689. $tplContent->assign('time_in_platform', $time);
  690. $tplContent->assign('certificate_generated_date', api_get_local_time($myCertificate['created_at']));
  691. if (!empty($termsValidationDate)) {
  692. $termsValidationDate = api_get_local_time($termsValidationDate);
  693. }
  694. $tplContent->assign('terms_validation_date', $termsValidationDate);
  695. // Ofaj
  696. $tplContent->assign('time_in_platform_in_hours', round($timeInSeconds / 3600, 1));
  697. $tplContent->assign(
  698. 'certificate_generated_date_no_time',
  699. api_get_local_time(
  700. $myCertificate['created_at'],
  701. null,
  702. null,
  703. false,
  704. false
  705. )
  706. );
  707. $tplContent->assign(
  708. 'terms_validation_date_no_time',
  709. api_get_local_time(
  710. $termsValidationDate,
  711. null,
  712. null,
  713. false,
  714. false
  715. )
  716. );
  717. $tplContent->assign('skills', $skills);
  718. $tplContent->assign('sessions', $sessionsApproved);
  719. $tplContent->assign('courses', $coursesApproved);
  720. $tplContent->assign('time_spent_in_lps', api_time_to_hms($totalTimeInLearningPaths));
  721. $tplContent->assign('time_spent_in_lps_in_hours', round($totalTimeInLearningPaths / 3600, 1));
  722. $layoutContent = $tplContent->get_template('gradebook/custom_certificate.tpl');
  723. $content = $tplContent->fetch($layoutContent);
  724. return $content;
  725. }
  726. /**
  727. * Ofaj.
  728. */
  729. public function generatePdfFromCustomCertificate()
  730. {
  731. $orientation = api_get_configuration_value('certificate_pdf_orientation');
  732. $params['orientation'] = 'landscape';
  733. if (!empty($orientation)) {
  734. $params['orientation'] = $orientation;
  735. }
  736. $params['left'] = 0;
  737. $params['right'] = 0;
  738. $params['top'] = 0;
  739. $params['bottom'] = 0;
  740. $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
  741. $pdf = new PDF($page_format, $params['orientation'], $params);
  742. $pdf->html_to_pdf(
  743. $this->html_file,
  744. get_lang('Certificates'),
  745. null,
  746. false,
  747. false
  748. );
  749. }
  750. /**
  751. * @param int $userId
  752. *
  753. * @return array
  754. */
  755. public static function getCertificateByUser($userId)
  756. {
  757. $userId = (int) $userId;
  758. if (empty($userId)) {
  759. return [];
  760. }
  761. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  762. $sql = "SELECT * FROM $table
  763. WHERE user_id= $userId";
  764. $rs = Database::query($sql);
  765. return Database::store_result($rs, 'ASSOC');
  766. }
  767. /**
  768. * @param int $userId
  769. */
  770. public static function generateUserSkills($userId)
  771. {
  772. $controller = new IndexManager(get_lang('MyCourses'));
  773. $courseAndSessions = $controller->returnCoursesAndSessions($userId, true, null, true, false);
  774. if (isset($courseAndSessions['courses']) && !empty($courseAndSessions['courses'])) {
  775. foreach ($courseAndSessions['courses'] as $course) {
  776. $cats = Category::load(
  777. null,
  778. null,
  779. $course['code'],
  780. null,
  781. null,
  782. null,
  783. false
  784. );
  785. if (isset($cats[0]) && !empty($cats[0])) {
  786. Category::generateUserCertificate(
  787. $cats[0]->get_id(),
  788. $userId
  789. );
  790. }
  791. }
  792. }
  793. if (isset($courseAndSessions['sessions']) && !empty($courseAndSessions['sessions'])) {
  794. foreach ($courseAndSessions['sessions'] as $sessionCategory) {
  795. if (isset($sessionCategory['sessions'])) {
  796. foreach ($sessionCategory['sessions'] as $sessionData) {
  797. if (!empty($sessionData['courses'])) {
  798. $sessionId = $sessionData['session_id'];
  799. foreach ($sessionData['courses'] as $courseData) {
  800. $cats = Category:: load(
  801. null,
  802. null,
  803. $courseData['course_code'],
  804. null,
  805. null,
  806. $sessionId,
  807. false
  808. );
  809. if (isset($cats[0]) && !empty($cats[0])) {
  810. Category::generateUserCertificate(
  811. $cats[0]->get_id(),
  812. $userId
  813. );
  814. }
  815. }
  816. }
  817. }
  818. }
  819. }
  820. }
  821. }
  822. }