certificate.lib.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Certificate Class
  5. * Generate certificates based in the gradebook tool.
  6. * @package chamilo.library.certificates
  7. */
  8. class Certificate extends Model
  9. {
  10. public $table;
  11. public $columns = array(
  12. 'id',
  13. 'cat_id',
  14. 'score_certificate',
  15. 'created_at',
  16. 'path_certificate'
  17. );
  18. /**
  19. * Certification data
  20. */
  21. public $certificate_data = array();
  22. /**
  23. * Student's certification path
  24. */
  25. public $certification_user_path = null;
  26. public $certification_web_user_path = null;
  27. public $html_file = null;
  28. public $qr_file = null;
  29. public $user_id;
  30. /* If true every time we enter to the certificate URL
  31. we would generate a new certificate (good thing because we can edit the
  32. certificate and all users will have the latest certificate bad because we
  33. load the certificate everytime*/
  34. public $force_certificate_generation = true;
  35. /**
  36. * Constructor
  37. * @param int $certificate_id ID of the certificate.
  38. * @param int $userId
  39. *
  40. * If no ID given, take user_id and try to generate one
  41. */
  42. public function __construct($certificate_id = 0, $userId = 0)
  43. {
  44. $this->table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  45. $this->user_id = !empty($userId) ? $userId : api_get_user_id();
  46. if (!empty($certificate_id)) {
  47. $certificate = $this->get($certificate_id);
  48. if (!empty($certificate) && is_array($certificate)) {
  49. $this->certificate_data = $certificate;
  50. $this->user_id = $this->certificate_data['user_id'];
  51. }
  52. }
  53. if ($this->user_id) {
  54. // Need to be called before any operation
  55. $this->check_certificate_path();
  56. // To force certification generation
  57. if ($this->force_certificate_generation) {
  58. $this->generate();
  59. }
  60. if (isset($this->certificate_data) && $this->certificate_data) {
  61. if (empty($this->certificate_data['path_certificate'])) {
  62. $this->generate();
  63. }
  64. }
  65. }
  66. //Setting the qr and html variables
  67. if (
  68. isset($certificate_id) &&
  69. !empty($this->certification_user_path) &&
  70. isset($this->certificate_data['path_certificate'])
  71. ) {
  72. $pathinfo = pathinfo($this->certificate_data['path_certificate']);
  73. $this->html_file = $this->certification_user_path.basename($this->certificate_data['path_certificate']);
  74. $this->qr_file = $this->certification_user_path.$pathinfo['filename'].'_qr.png';
  75. }
  76. }
  77. /**
  78. * Checks if the certificate user path directory is created
  79. */
  80. public function check_certificate_path()
  81. {
  82. $this->certification_user_path = null;
  83. //Setting certification path
  84. $path_info = UserManager::getUserPathById($this->user_id, 'system');
  85. $web_path_info = UserManager::getUserPathById($this->user_id, 'web');
  86. if (!empty($path_info) && isset($path_info)) {
  87. $this->certification_user_path = $path_info.'certificate/';
  88. $this->certification_web_user_path = $web_path_info.'certificate/';
  89. if (!is_dir($path_info)) {
  90. mkdir($path_info, 0777, true);
  91. }
  92. if (!is_dir($this->certification_user_path)) {
  93. mkdir($this->certification_user_path, 0777);
  94. }
  95. }
  96. }
  97. /**
  98. * Deletes the current certificate object. This is generally triggered by
  99. * the teacher from the gradebook tool to re-generate the certificate because
  100. * the original version wa flawed.
  101. * @param bool $force_delete
  102. * @return bool
  103. */
  104. public function delete($force_delete = false)
  105. {
  106. $delete_db = false;
  107. if (!empty($this->certificate_data)) {
  108. if (!is_null($this->html_file) || $this->html_file != '' || strlen($this->html_file)) {
  109. //Deleting HTML file
  110. if (is_file($this->html_file)) {
  111. @unlink($this->html_file);
  112. if (is_file($this->html_file) === false) {
  113. $delete_db = true;
  114. } else {
  115. $delete_db = false;
  116. }
  117. }
  118. //Deleting QR code PNG image file
  119. if (is_file($this->qr_file)) {
  120. @unlink($this->qr_file);
  121. }
  122. if ($delete_db || $force_delete) {
  123. return parent::delete($this->certificate_data['id']);
  124. }
  125. } else {
  126. return parent::delete($this->certificate_data['id']);
  127. }
  128. }
  129. return false;
  130. }
  131. /**
  132. * Generates an HTML Certificate and fills the path_certificate field in the DB
  133. *
  134. * @param array $params
  135. * @return bool|int
  136. */
  137. public function generate($params = array())
  138. {
  139. // The user directory should be set
  140. if (empty($this->certification_user_path) &&
  141. $this->force_certificate_generation == false
  142. ) {
  143. return false;
  144. }
  145. $params['hide_print_button'] = isset($params['hide_print_button']) ? true : false;
  146. if (isset($this->certificate_data) && isset($this->certificate_data['cat_id'])) {
  147. $my_category = Category :: load($this->certificate_data['cat_id']);
  148. }
  149. if (isset($my_category[0]) &&
  150. $my_category[0]->is_certificate_available($this->user_id)
  151. ) {
  152. $courseId = api_get_course_int_id();
  153. $sessionId = api_get_session_id();
  154. $skill = new Skill();
  155. $skill->add_skill_to_user(
  156. $this->user_id,
  157. $this->certificate_data['cat_id'],
  158. $courseId,
  159. $sessionId
  160. );
  161. if (is_dir($this->certification_user_path)) {
  162. if (!empty($this->certificate_data)) {
  163. $new_content_html = GradebookUtils::get_user_certificate_content(
  164. $this->user_id,
  165. $my_category[0]->get_course_code(),
  166. $my_category[0]->get_session_id(),
  167. false,
  168. $params['hide_print_button']
  169. );
  170. if ($my_category[0]->get_id() == strval(intval($this->certificate_data['cat_id']))) {
  171. $name = $this->certificate_data['path_certificate'];
  172. $my_path_certificate = $this->certification_user_path.basename($name);
  173. if (file_exists($my_path_certificate) &&
  174. !empty($name) &&
  175. !is_dir($my_path_certificate) &&
  176. $this->force_certificate_generation == false
  177. ) {
  178. //Seems that the file was already generated
  179. return true;
  180. } else {
  181. // Creating new name
  182. $name = md5($this->user_id.$this->certificate_data['cat_id']).'.html';
  183. $my_path_certificate = $this->certification_user_path.$name;
  184. $path_certificate ='/'.$name;
  185. //Getting QR filename
  186. $file_info = pathinfo($path_certificate);
  187. $qr_code_filename = $this->certification_user_path.$file_info['filename'].'_qr.png';
  188. $my_new_content_html = str_replace(
  189. '((certificate_barcode))',
  190. Display::img($this->certification_web_user_path.$file_info['filename'].'_qr.png', 'QR'),
  191. $new_content_html['content']
  192. );
  193. $my_new_content_html = mb_convert_encoding(
  194. $my_new_content_html,
  195. 'UTF-8',
  196. api_get_system_encoding()
  197. );
  198. $result = @file_put_contents($my_path_certificate, $my_new_content_html);
  199. if ($result) {
  200. //Updating the path
  201. self::update_user_info_about_certificate(
  202. $this->certificate_data['cat_id'],
  203. $this->user_id,
  204. $path_certificate
  205. );
  206. $this->certificate_data['path_certificate'] = $path_certificate;
  207. if ($this->html_file_is_generated()) {
  208. if (!empty($file_info)) {
  209. $text = $this->parse_certificate_variables($new_content_html['variables']);
  210. $this->generate_qr($text, $qr_code_filename);
  211. }
  212. }
  213. }
  214. return $result;
  215. }
  216. }
  217. }
  218. }
  219. }
  220. return false;
  221. }
  222. /**
  223. * update user info about certificate
  224. * @param int $cat_id category id
  225. * @param int $user_id user id
  226. * @param string $path_certificate the path name of the certificate
  227. * @return void
  228. */
  229. public function update_user_info_about_certificate(
  230. $cat_id,
  231. $user_id,
  232. $path_certificate
  233. ) {
  234. $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
  235. if (!UserManager::is_user_certified($cat_id, $user_id)) {
  236. $sql = 'UPDATE '.$table_certificate.' SET
  237. path_certificate="'.Database::escape_string($path_certificate).'"
  238. WHERE cat_id="'.intval($cat_id).'" AND user_id="'.intval($user_id).'" ';
  239. Database::query($sql);
  240. }
  241. }
  242. /**
  243. *
  244. * Check if the file was generated
  245. *
  246. * @return boolean
  247. */
  248. public function html_file_is_generated()
  249. {
  250. if (empty($this->certification_user_path)) {
  251. return false;
  252. }
  253. if (!empty($this->certificate_data) &&
  254. isset($this->certificate_data['path_certificate']) &&
  255. !empty($this->certificate_data['path_certificate'])
  256. ) {
  257. return true;
  258. }
  259. return false;
  260. }
  261. /**
  262. * Generates a QR code for the certificate. The QR code embeds the text given
  263. * @param string $text Text to be added in the QR code
  264. * @param string $path file path of the image
  265. * */
  266. public function generate_qr($text, $path)
  267. {
  268. //Make sure HTML certificate is generated
  269. if (!empty($text) && !empty($path)) {
  270. //L low, M - Medium, L large error correction
  271. return PHPQRCode\QRcode::png($text, $path, 'M', 2, 2);
  272. }
  273. return false;
  274. }
  275. /**
  276. * Transforms certificate tags into text values. This function is very static
  277. * (it doesn't allow for much flexibility in terms of what tags are printed).
  278. * @param array $array Contains two array entris: first are the headers,
  279. * second is an array of contents
  280. * @return string The translated string
  281. */
  282. public function parse_certificate_variables($array)
  283. {
  284. $headers = $array[0];
  285. $content = $array[1];
  286. $final_content = array();
  287. if (!empty($content)) {
  288. foreach ($content as $key => $value) {
  289. $my_header = str_replace(array('((', '))') , '', $headers[$key]);
  290. $final_content[$my_header] = $value;
  291. }
  292. }
  293. /* Certificate tags
  294. *
  295. 0 => string '((user_firstname))' (length=18)
  296. 1 => string '((user_lastname))' (length=17)
  297. 2 => string '((gradebook_institution))' (length=25)
  298. 3 => string '((gradebook_sitename))' (length=22)
  299. 4 => string '((teacher_firstname))' (length=21)
  300. 5 => string '((teacher_lastname))' (length=20)
  301. 6 => string '((official_code))' (length=17)
  302. 7 => string '((date_certificate))' (length=20)
  303. 8 => string '((course_code))' (length=15)
  304. 9 => string '((course_title))' (length=16)
  305. 10 => string '((gradebook_grade))' (length=19)
  306. 11 => string '((certificate_link))' (length=20)
  307. 12 => string '((certificate_link_html))' (length=25)
  308. 13 => string '((certificate_barcode))' (length=23)
  309. */
  310. $break_space = " \n\r ";
  311. $text =
  312. $final_content['gradebook_institution'].' - '.
  313. $final_content['gradebook_sitename'].' - '.
  314. get_lang('Certification').$break_space.
  315. get_lang('Student'). ': '.$final_content['user_firstname'].' '.$final_content['user_lastname'].$break_space.
  316. get_lang('Teacher'). ': '.$final_content['teacher_firstname'].' '.$final_content['teacher_lastname'].$break_space.
  317. get_lang('Date'). ': '.$final_content['date_certificate'].$break_space.
  318. get_lang('Score'). ': '.$final_content['gradebook_grade'].$break_space.
  319. 'URL'. ': '.$final_content['certificate_link'];
  320. return $text;
  321. }
  322. /**
  323. * Shows the student's certificate (HTML file). If the global setting
  324. * allow_public_certificates is set to 'false', no certificate can be printed.
  325. * If the global allow_public_certificates is set to 'true' and the course
  326. * setting allow_public_certificates is set to 0, no certificate *in this
  327. * course* can be printed (for anonymous users). Connected users can always
  328. * print them.
  329. */
  330. public function show()
  331. {
  332. // Special rules for anonymous users
  333. $failed = false;
  334. if (api_is_anonymous()) {
  335. if (api_get_setting('allow_public_certificates') != 'true') {
  336. // The "non-public" setting is set, so do not print
  337. $failed = true;
  338. } else {
  339. // Check the course-level setting to make sure the certificate
  340. // can be printed publicly
  341. if (isset($this->certificate_data) &&
  342. isset($this->certificate_data['cat_id'])
  343. ) {
  344. $gradebook = new Gradebook();
  345. $gradebook_info = $gradebook->get($this->certificate_data['cat_id']);
  346. if (!empty($gradebook_info['course_code'])) {
  347. $allow_public_certificates = api_get_course_setting('allow_public_certificates', $gradebook_info['course_code']);
  348. if ($allow_public_certificates == 0) {
  349. // Printing not allowed
  350. $failed = true;
  351. }
  352. } else {
  353. // No course ID defined (should never get here)
  354. Display :: display_reduced_header();
  355. Display :: display_warning_message(get_lang('NoCertificateAvailable'));
  356. exit;
  357. }
  358. }
  359. }
  360. }
  361. if ($failed) {
  362. Display :: display_reduced_header();
  363. Display :: display_warning_message(get_lang('CertificateExistsButNotPublic'));
  364. exit;
  365. }
  366. //Read file or preview file
  367. if (!empty($this->certificate_data['path_certificate'])) {
  368. $user_certificate = $this->certification_user_path.basename($this->certificate_data['path_certificate']);
  369. if (file_exists($user_certificate)) {
  370. header('Content-Type: text/html; charset='. api_get_system_encoding());
  371. echo @file_get_contents($user_certificate);
  372. }
  373. } else {
  374. Display :: display_reduced_header();
  375. Display :: display_warning_message(get_lang('NoCertificateAvailable'));
  376. }
  377. exit;
  378. }
  379. }