certificate.lib.php 16 KB

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