certificate.lib.php 16 KB

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