certificate.lib.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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. $setting = api_get_course_setting(
  544. 'allow_public_certificates',
  545. api_get_course_info($gradeBookInfo['course_code'])
  546. );
  547. if ($setting == 0) {
  548. // Printing not allowed
  549. return false;
  550. }
  551. return true;
  552. }
  553. /**
  554. * Check if the certificate is available.
  555. *
  556. * @return bool
  557. */
  558. public function isAvailable()
  559. {
  560. if (empty($this->certificate_data['path_certificate'])) {
  561. return false;
  562. }
  563. $userCertificate = $this->certification_user_path.basename($this->certificate_data['path_certificate']);
  564. if (!file_exists($userCertificate)) {
  565. return false;
  566. }
  567. return true;
  568. }
  569. /**
  570. * Shows the student's certificate (HTML file).
  571. */
  572. public function show()
  573. {
  574. $user_certificate = $this->certification_user_path.basename($this->certificate_data['path_certificate']);
  575. if (file_exists($user_certificate)) {
  576. // Needed in order to browsers don't add custom CSS
  577. $certificateContent = '<!DOCTYPE html>';
  578. $certificateContent .= (string) file_get_contents($user_certificate);
  579. // Remove media=screen to be available when printing a document
  580. $certificateContent = str_replace(
  581. ' media="screen"',
  582. '',
  583. $certificateContent
  584. );
  585. if ($this->user_id == api_get_user_id() &&
  586. !empty($this->certificate_data) &&
  587. isset($this->certificate_data['id'])
  588. ) {
  589. $certificateId = $this->certificate_data['id'];
  590. $extraFieldValue = new ExtraFieldValue('user_certificate');
  591. $value = $extraFieldValue->get_values_by_handler_and_field_variable(
  592. $certificateId,
  593. 'downloaded_at'
  594. );
  595. if (empty($value)) {
  596. $params = [
  597. 'item_id' => $this->certificate_data['id'],
  598. 'extra_downloaded_at' => api_get_utc_datetime(),
  599. ];
  600. $extraFieldValue->saveFieldValues($params);
  601. }
  602. }
  603. header('Content-Type: text/html; charset='.api_get_system_encoding());
  604. echo $certificateContent;
  605. return;
  606. }
  607. api_not_allowed(true);
  608. }
  609. /**
  610. * @return string
  611. */
  612. public function generateCustomCertificate()
  613. {
  614. $myCertificate = GradebookUtils::get_certificate_by_user_id(
  615. 0,
  616. $this->user_id
  617. );
  618. if (empty($myCertificate)) {
  619. GradebookUtils::registerUserInfoAboutCertificate(
  620. 0,
  621. $this->user_id,
  622. 100,
  623. api_get_utc_datetime()
  624. );
  625. }
  626. $userInfo = api_get_user_info($this->user_id);
  627. $extraFieldValue = new ExtraFieldValue('user');
  628. $value = $extraFieldValue->get_values_by_handler_and_field_variable($this->user_id, 'legal_accept');
  629. $termsValidationDate = '';
  630. if (isset($value) && !empty($value['value'])) {
  631. list($id, $id2, $termsValidationDate) = explode(':', $value['value']);
  632. }
  633. $sessions = SessionManager::get_sessions_by_user($this->user_id, false, true);
  634. $totalTimeInLearningPaths = 0;
  635. $sessionsApproved = [];
  636. $coursesApproved = [];
  637. if ($sessions) {
  638. foreach ($sessions as $session) {
  639. $allCoursesApproved = [];
  640. foreach ($session['courses'] as $course) {
  641. $courseInfo = api_get_course_info_by_id($course['real_id']);
  642. $courseCode = $courseInfo['code'];
  643. $gradebookCategories = Category::load(
  644. null,
  645. null,
  646. $courseCode,
  647. null,
  648. false,
  649. $session['session_id']
  650. );
  651. if (isset($gradebookCategories[0])) {
  652. /** @var Category $category */
  653. $category = $gradebookCategories[0];
  654. $result = Category::userFinishedCourse(
  655. $this->user_id,
  656. $category,
  657. true
  658. );
  659. if ($result) {
  660. $coursesApproved[$course['real_id']] = $courseInfo['title'];
  661. // Find time spent in LP
  662. $totalTimeInLearningPaths += Tracking::get_time_spent_in_lp(
  663. $this->user_id,
  664. $courseCode,
  665. [],
  666. $session['session_id']
  667. );
  668. $allCoursesApproved[] = true;
  669. }
  670. }
  671. }
  672. if (count($allCoursesApproved) == count($session['courses'])) {
  673. $sessionsApproved[] = $session;
  674. }
  675. }
  676. }
  677. $skill = new Skill();
  678. // Ofaj
  679. $skills = $skill->getStudentSkills($this->user_id, 2);
  680. $timeInSeconds = Tracking::get_time_spent_on_the_platform(
  681. $this->user_id,
  682. 'ever'
  683. );
  684. $time = api_time_to_hms($timeInSeconds);
  685. $tplContent = new Template(null, false, false, false, false, false);
  686. // variables for the default template
  687. $tplContent->assign('complete_name', $userInfo['complete_name']);
  688. $tplContent->assign('time_in_platform', $time);
  689. $tplContent->assign('certificate_generated_date', api_get_local_time($myCertificate['created_at']));
  690. if (!empty($termsValidationDate)) {
  691. $termsValidationDate = api_get_local_time($termsValidationDate);
  692. }
  693. $tplContent->assign('terms_validation_date', $termsValidationDate);
  694. // Ofaj
  695. $tplContent->assign('time_in_platform_in_hours', round($timeInSeconds / 3600, 1));
  696. $tplContent->assign(
  697. 'certificate_generated_date_no_time',
  698. api_get_local_time(
  699. $myCertificate['created_at'],
  700. null,
  701. null,
  702. false,
  703. false
  704. )
  705. );
  706. $tplContent->assign(
  707. 'terms_validation_date_no_time',
  708. api_get_local_time(
  709. $termsValidationDate,
  710. null,
  711. null,
  712. false,
  713. false
  714. )
  715. );
  716. $tplContent->assign('skills', $skills);
  717. $tplContent->assign('sessions', $sessionsApproved);
  718. $tplContent->assign('courses', $coursesApproved);
  719. $tplContent->assign('time_spent_in_lps', api_time_to_hms($totalTimeInLearningPaths));
  720. $tplContent->assign('time_spent_in_lps_in_hours', round($totalTimeInLearningPaths / 3600, 1));
  721. $layoutContent = $tplContent->get_template('gradebook/custom_certificate.tpl');
  722. $content = $tplContent->fetch($layoutContent);
  723. return $content;
  724. }
  725. /**
  726. * Ofaj.
  727. */
  728. public function generatePdfFromCustomCertificate()
  729. {
  730. $orientation = api_get_configuration_value('certificate_pdf_orientation');
  731. $params['orientation'] = 'landscape';
  732. if (!empty($orientation)) {
  733. $params['orientation'] = $orientation;
  734. }
  735. $params['left'] = 0;
  736. $params['right'] = 0;
  737. $params['top'] = 0;
  738. $params['bottom'] = 0;
  739. $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
  740. $pdf = new PDF($page_format, $params['orientation'], $params);
  741. $pdf->html_to_pdf(
  742. $this->html_file,
  743. get_lang('Certificates'),
  744. null,
  745. false,
  746. false
  747. );
  748. }
  749. /**
  750. * @param int $userId
  751. *
  752. * @return array
  753. */
  754. public static function getCertificateByUser($userId)
  755. {
  756. $userId = (int) $userId;
  757. if (empty($userId)) {
  758. return [];
  759. }
  760. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  761. $sql = "SELECT * FROM $table
  762. WHERE user_id= $userId";
  763. $rs = Database::query($sql);
  764. return Database::store_result($rs, 'ASSOC');
  765. }
  766. /**
  767. * @param int $userId
  768. */
  769. public static function generateUserSkills($userId)
  770. {
  771. $controller = new IndexManager(get_lang('MyCourses'));
  772. $courseAndSessions = $controller->returnCoursesAndSessions($userId, true, null, true, false);
  773. if (isset($courseAndSessions['courses']) && !empty($courseAndSessions['courses'])) {
  774. foreach ($courseAndSessions['courses'] as $course) {
  775. $cats = Category::load(
  776. null,
  777. null,
  778. $course['code'],
  779. null,
  780. null,
  781. null,
  782. false
  783. );
  784. if (isset($cats[0]) && !empty($cats[0])) {
  785. Category::generateUserCertificate(
  786. $cats[0]->get_id(),
  787. $userId
  788. );
  789. }
  790. }
  791. }
  792. if (isset($courseAndSessions['sessions']) && !empty($courseAndSessions['sessions'])) {
  793. foreach ($courseAndSessions['sessions'] as $sessionCategory) {
  794. if (isset($sessionCategory['sessions'])) {
  795. foreach ($sessionCategory['sessions'] as $sessionData) {
  796. if (!empty($sessionData['courses'])) {
  797. $sessionId = $sessionData['session_id'];
  798. foreach ($sessionData['courses'] as $courseData) {
  799. $cats = Category:: load(
  800. null,
  801. null,
  802. $courseData['course_code'],
  803. null,
  804. null,
  805. $sessionId,
  806. false
  807. );
  808. if (isset($cats[0]) && !empty($cats[0])) {
  809. Category::generateUserCertificate(
  810. $cats[0]->get_id(),
  811. $userId
  812. );
  813. }
  814. }
  815. }
  816. }
  817. }
  818. }
  819. }
  820. }
  821. }