certificate.lib.php 32 KB

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