add_course.lib.inc.php 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CourseBundle\Entity\CTool;
  4. use Chamilo\CoreBundle\Entity\Course;
  5. use Chamilo\CoreBundle\Entity\AccessUrlRelCourse;
  6. /**
  7. * Class AddCourse
  8. */
  9. class AddCourse
  10. {
  11. /**
  12. * Defines the four needed keys to create a course based on several parameters.
  13. * @param string The code you want for this course
  14. * @param string Prefix added for ALL keys
  15. * @param string Prefix added for databases only
  16. * @param string Prefix added for paths only
  17. * @param bool Add unique prefix
  18. * @param bool Use code-independent keys
  19. * @return array An array with the needed keys ['currentCourseCode'], ['currentCourseId'], ['currentCourseDbName'], ['currentCourseRepository']
  20. * @todo Eliminate the global variables.
  21. * @assert (null) === false
  22. */
  23. public static function define_course_keys(
  24. $wanted_code,
  25. $prefix_for_all = '',
  26. $prefix_for_base_name = '',
  27. $prefix_for_path = '',
  28. $add_unique_prefix = false,
  29. $use_code_indepedent_keys = true
  30. ) {
  31. $course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
  32. $wanted_code = CourseManager::generate_course_code($wanted_code);
  33. $keys_course_code = $wanted_code;
  34. if (!$use_code_indepedent_keys) {
  35. $wanted_code = '';
  36. }
  37. if ($add_unique_prefix) {
  38. $unique_prefix = substr(md5(uniqid(rand())), 0, 10);
  39. } else {
  40. $unique_prefix = '';
  41. }
  42. $keys = array();
  43. $final_suffix = array('CourseId' => '', 'CourseDb' => '', 'CourseDir' => '');
  44. $limit_numb_try = 100;
  45. $keys_are_unique = false;
  46. $try_new_fsc_id = $try_new_fsc_db = $try_new_fsc_dir = 0;
  47. while (!$keys_are_unique) {
  48. $keys_course_id = $prefix_for_all . $unique_prefix . $wanted_code . $final_suffix['CourseId'];
  49. $keys_course_repository = $prefix_for_path . $unique_prefix . $wanted_code . $final_suffix['CourseDir'];
  50. $keys_are_unique = true;
  51. // Check whether they are unique.
  52. $query = "SELECT 1 FROM $course_table
  53. WHERE code='".$keys_course_id."'
  54. LIMIT 0, 1";
  55. $result = Database::query($query);
  56. if (Database::num_rows($result)) {
  57. $keys_are_unique = false;
  58. $try_new_fsc_id ++;
  59. $final_suffix['CourseId'] = substr(md5(uniqid(rand())), 0, 4);
  60. }
  61. if (file_exists(api_get_path(SYS_COURSE_PATH).$keys_course_repository)) {
  62. $keys_are_unique = false;
  63. $try_new_fsc_dir ++;
  64. $final_suffix['CourseDir'] = substr(md5(uniqid(rand())), 0, 4);
  65. }
  66. if (($try_new_fsc_id + $try_new_fsc_db + $try_new_fsc_dir) > $limit_numb_try) {
  67. return $keys;
  68. }
  69. }
  70. $keys['currentCourseCode'] = $keys_course_code;
  71. $keys['currentCourseId'] = $keys_course_id;
  72. $keys['currentCourseRepository'] = $keys_course_repository;
  73. return $keys;
  74. }
  75. /**
  76. * Initializes a file repository for a newly created course.
  77. * @param string Course repository
  78. * @param string Course code
  79. * @return int 0
  80. * @assert (null,null) === false
  81. */
  82. public static function prepare_course_repository($course_repository, $course_code)
  83. {
  84. $perm = api_get_permissions_for_new_directories();
  85. $perm_file = api_get_permissions_for_new_files();
  86. $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Not authorized</title>\n </head>\n <body>\n </body>\n</html>";
  87. $cp = api_get_path(SYS_COURSE_PATH) . $course_repository;
  88. //Creating document folder
  89. mkdir($cp, $perm);
  90. mkdir($cp . '/document', $perm);
  91. $cpt = $cp . '/document/index.html';
  92. $fd = fopen($cpt, 'w');
  93. fwrite($fd, $htmlpage);
  94. fclose($fd);
  95. /*
  96. @chmod($cpt, $perm_file);
  97. @copy($cpt, $cp . '/document/index.html');
  98. mkdir($cp . '/document/images', $perm);
  99. @copy($cpt, $cp . '/document/images/index.html');
  100. mkdir($cp . '/document/images/gallery/', $perm);
  101. @copy($cpt, $cp . '/document/images/gallery/index.html');
  102. mkdir($cp . '/document/shared_folder/', $perm);
  103. @copy($cpt, $cp . '/document/shared_folder/index.html');
  104. mkdir($cp . '/document/audio', $perm);
  105. @copy($cpt, $cp . '/document/audio/index.html');
  106. mkdir($cp . '/document/flash', $perm);
  107. @copy($cpt, $cp . '/document/flash/index.html');
  108. mkdir($cp . '/document/video', $perm);
  109. @copy($cpt, $cp . '/document/video/index.html'); */
  110. //Creatind dropbox folder
  111. mkdir($cp . '/dropbox', $perm);
  112. $cpt = $cp . '/dropbox/index.html';
  113. $fd = fopen($cpt, 'w');
  114. fwrite($fd, $htmlpage);
  115. fclose($fd);
  116. @chmod($cpt, $perm_file);
  117. mkdir($cp . '/group', $perm);
  118. @copy($cpt, $cp . '/group/index.html');
  119. mkdir($cp . '/page', $perm);
  120. @copy($cpt, $cp . '/page/index.html');
  121. mkdir($cp . '/scorm', $perm);
  122. @copy($cpt, $cp . '/scorm/index.html');
  123. mkdir($cp . '/upload', $perm);
  124. @copy($cpt, $cp . '/upload/index.html');
  125. mkdir($cp . '/upload/forum', $perm);
  126. @copy($cpt, $cp . '/upload/forum/index.html');
  127. mkdir($cp . '/upload/forum/images', $perm);
  128. @copy($cpt, $cp . '/upload/forum/images/index.html');
  129. mkdir($cp . '/upload/test', $perm);
  130. @copy($cpt, $cp . '/upload/test/index.html');
  131. mkdir($cp . '/upload/blog', $perm);
  132. @copy($cpt, $cp . '/upload/blog/index.html');
  133. mkdir($cp . '/upload/learning_path', $perm);
  134. @copy($cpt, $cp . '/upload/learning_path/index.html');
  135. mkdir($cp . '/upload/learning_path/images', $perm);
  136. @copy($cpt, $cp . '/upload/learning_path/images/index.html');
  137. mkdir($cp . '/upload/calendar', $perm);
  138. @copy($cpt, $cp . '/upload/calendar/index.html');
  139. mkdir($cp . '/upload/calendar/images', $perm);
  140. @copy($cpt, $cp . '/upload/calendar/images/index.html');
  141. mkdir($cp . '/work', $perm);
  142. @copy($cpt, $cp . '/work/index.html');
  143. mkdir($cp . '/upload/announcements', $perm);
  144. @copy($cpt, $cp . '/upload/announcements/index.html');
  145. mkdir($cp . '/upload/announcements/images', $perm);
  146. @copy($cpt, $cp . '/upload/announcements/images/index.html');
  147. //Oral expression question type
  148. mkdir($cp . '/exercises', $perm);
  149. @copy($cpt, $cp . '/exercises/index.html');
  150. // Create .htaccess in the dropbox directory.
  151. $fp = fopen($cp . '/dropbox/.htaccess', 'w');
  152. fwrite(
  153. $fp,
  154. "AuthName AllowLocalAccess
  155. AuthType Basic
  156. order deny,allow
  157. deny from all
  158. php_flag zlib.output_compression off"
  159. );
  160. fclose($fp);
  161. // Build index.php of the course.
  162. /*$fd = fopen($cp . '/index.php', 'w');
  163. // str_replace() removes \r that cause squares to appear at the end of each line
  164. //@todo fix the harcoded include
  165. $string = str_replace(
  166. "\r",
  167. "",
  168. "<?" . "php
  169. \$cidReq = \"$course_code\";
  170. \$dbname = \"$course_code\";
  171. include(\"" . api_get_path(SYS_CODE_PATH) . "course_home/course_home.php\");
  172. ?>"
  173. );
  174. fwrite($fd, $string);
  175. @chmod($cp . '/index.php', $perm_file);*/
  176. return 0;
  177. }
  178. /**
  179. * Gets an array with all the course tables (deprecated?)
  180. * @return string[]
  181. * @assert (null) !== null
  182. */
  183. public static function get_course_tables()
  184. {
  185. $tables = array();
  186. $tables[] = 'item_property';
  187. $tables[] = 'tool';
  188. $tables[] = 'tool_intro';
  189. $tables[] = 'group_info';
  190. $tables[] = 'group_category';
  191. $tables[] = 'group_rel_user';
  192. $tables[] = 'group_rel_tutor';
  193. $tables[] = 'userinfo_content';
  194. $tables[] = 'userinfo_def';
  195. $tables[] = 'course_description';
  196. $tables[] = 'calendar_event';
  197. $tables[] = 'calendar_event_repeat';
  198. $tables[] = 'calendar_event_repeat_not';
  199. $tables[] = 'calendar_event_attachment';
  200. $tables[] = 'announcement';
  201. $tables[] = 'announcement_attachment';
  202. $tables[] = 'resource';
  203. $tables[] = 'student_publication';
  204. $tables[] = 'student_publication_assignment';
  205. $tables[] = 'document';
  206. $tables[] = 'forum_category';
  207. $tables[] = 'forum_forum';
  208. $tables[] = 'forum_thread';
  209. $tables[] = 'forum_post';
  210. $tables[] = 'forum_mailcue';
  211. $tables[] = 'forum_attachment';
  212. $tables[] = 'forum_notification';
  213. $tables[] = 'forum_thread_qualify';
  214. $tables[] = 'forum_thread_qualify_log';
  215. $tables[] = 'link';
  216. $tables[] = 'link_category';
  217. $tables[] = 'online_connected';
  218. $tables[] = 'online_link';
  219. $tables[] = 'chat_connected';
  220. $tables[] = 'quiz';
  221. $tables[] = 'quiz_rel_question';
  222. $tables[] = 'quiz_question';
  223. $tables[] = 'quiz_answer';
  224. $tables[] = 'quiz_question_option';
  225. $tables[] = 'quiz_question_category';
  226. $tables[] = 'quiz_question_rel_category';
  227. $tables[] = 'dropbox_post';
  228. $tables[] = 'dropbox_file';
  229. $tables[] = 'dropbox_person';
  230. $tables[] = 'dropbox_category';
  231. $tables[] = 'dropbox_feedback';
  232. $tables[] = 'lp';
  233. $tables[] = 'lp_item';
  234. $tables[] = 'lp_view';
  235. $tables[] = 'lp_item_view';
  236. $tables[] = 'lp_iv_interaction';
  237. $tables[] = 'lp_iv_objective';
  238. $tables[] = 'blog';
  239. $tables[] = 'blog_comment';
  240. $tables[] = 'blog_post';
  241. $tables[] = 'blog_rating';
  242. $tables[] = 'blog_rel_user';
  243. $tables[] = 'blog_task';
  244. $tables[] = 'blog_task_rel_user';
  245. $tables[] = 'blog_attachment';
  246. $tables[] = 'permission_group';
  247. $tables[] = 'permission_user';
  248. $tables[] = 'permission_task';
  249. $tables[] = 'role';
  250. $tables[] = 'role_group';
  251. $tables[] = 'role_permissions';
  252. $tables[] = 'role_user';
  253. $tables[] = 'survey';
  254. $tables[] = 'survey_question';
  255. $tables[] = 'survey_question_option';
  256. $tables[] = 'survey_invitation';
  257. $tables[] = 'survey_answer';
  258. $tables[] = 'survey_group';
  259. $tables[] = 'wiki';
  260. $tables[] = 'wiki_conf';
  261. $tables[] = 'wiki_discuss';
  262. $tables[] = 'wiki_mailcue';
  263. $tables[] = 'course_setting';
  264. $tables[] = 'glossary';
  265. $tables[] = 'notebook';
  266. $tables[] = 'attendance';
  267. $tables[] = 'attendance_sheet';
  268. $tables[] = 'attendance_calendar';
  269. $tables[] = 'attendance_result';
  270. $tables[] = 'attendance_sheet_log';
  271. $tables[] = 'thematic';
  272. $tables[] = 'thematic_plan';
  273. $tables[] = 'thematic_advance';
  274. return $tables;
  275. }
  276. /**
  277. * Executed only before create_course_tables()
  278. * @return void
  279. * @assert (null) === null
  280. */
  281. public static function drop_course_tables()
  282. {
  283. $list = self::get_course_tables();
  284. foreach ($list as $table) {
  285. $sql = "DROP TABLE IF EXISTS " . DB_COURSE_PREFIX . $table;
  286. Database::query($sql);
  287. }
  288. }
  289. /**
  290. * Returns a list of all files in the given course directory. The requested
  291. * directory will be checked against a "checker" directory to avoid access to
  292. * protected/unauthorized files
  293. * @param string Complete path to directory we want to list
  294. * @param array A list of files to which we want to add the files found
  295. * @param string Type of base directory from which we want to recover the files
  296. * @param string $path
  297. * @param string $media
  298. * @return array
  299. * @assert (null,null,null) === false
  300. * @assert ('abc',array(),'') === array()
  301. */
  302. public static function browse_folders($path, $files, $media)
  303. {
  304. if ($media == 'images') {
  305. $code_path = api_get_path(
  306. SYS_CODE_PATH
  307. ) . 'default_course_document/images/';
  308. }
  309. if ($media == 'audio') {
  310. $code_path = api_get_path(
  311. SYS_CODE_PATH
  312. ) . 'default_course_document/audio/';
  313. }
  314. if ($media == 'flash') {
  315. $code_path = api_get_path(
  316. SYS_CODE_PATH
  317. ) . 'default_course_document/flash/';
  318. }
  319. if ($media == 'video') {
  320. $code_path = api_get_path(
  321. SYS_CODE_PATH
  322. ) . 'default_course_document/video/';
  323. }
  324. if ($media == 'certificates') {
  325. $code_path = api_get_path(
  326. SYS_CODE_PATH
  327. ) . 'default_course_document/certificates/';
  328. }
  329. if (is_dir($path)) {
  330. $handle = opendir($path);
  331. while (false !== ($file = readdir($handle))) {
  332. if (is_dir($path . $file) && strpos($file, '.') !== 0) {
  333. $files[]['dir'] = str_replace(
  334. $code_path,
  335. '',
  336. $path . $file . '/'
  337. );
  338. $files = self::browse_folders(
  339. $path . $file . '/',
  340. $files,
  341. $media
  342. );
  343. } elseif (is_file($path . $file) && strpos($file, '.') !== 0) {
  344. $files[]['file'] = str_replace(
  345. $code_path,
  346. '',
  347. $path . $file
  348. );
  349. }
  350. }
  351. }
  352. return $files;
  353. }
  354. /**
  355. * Sorts pictures by type (used?)
  356. * @param array List of files (sthg like array(0=>array('png'=>1)))
  357. * @param string File type
  358. * @param string $type
  359. * @return array The received array without files not matching type
  360. * @assert (array(),null) === array()
  361. */
  362. public static function sort_pictures($files, $type)
  363. {
  364. $pictures = array();
  365. foreach ($files as $key => $value) {
  366. if (isset($value[$type]) && $value[$type] != '') {
  367. $pictures[][$type] = $value[$type];
  368. }
  369. }
  370. return $pictures;
  371. }
  372. /**
  373. * Fills the course database with some required content and example content.
  374. * @param int Course (int) ID
  375. * @param string Course directory name (e.g. 'ABC')
  376. * @param string Language used for content (e.g. 'spanish')
  377. * @param bool Whether to fill the course with example content
  378. * @param int $authorId
  379. * @return bool False on error, true otherwise
  380. * @version 1.2
  381. * @assert (null, '', '', null) === false
  382. * @assert (1, 'ABC', null, null) === false
  383. * @assert (1, 'TEST', 'spanish', true) === true
  384. */
  385. public static function fill_db_course(
  386. $course_id,
  387. $course_repository,
  388. $language,
  389. $fill_with_exemplary_content = null,
  390. $authorId = 0
  391. ) {
  392. if (is_null($fill_with_exemplary_content)) {
  393. $fill_with_exemplary_content = api_get_setting('course.example_material_course_creation') != 'false';
  394. }
  395. $course_id = intval($course_id);
  396. if (empty($course_id)) {
  397. return false;
  398. }
  399. $entityManager = Database::getManager();
  400. $course = $entityManager->getRepository('ChamiloCoreBundle:Course')->find($course_id);
  401. $tools = array();
  402. $settingsManager = CourseManager::getCourseSettingsManager();
  403. $settingsManager->setCourse($course);
  404. $toolList = CourseManager::getToolList();
  405. $toolList = $toolList->getTools();
  406. /** @var Chamilo\CourseBundle\Tool\BaseTool $tool */
  407. foreach ($toolList as $tool) {
  408. $visibility = self::string2binary(
  409. api_get_setting_in_list('course.active_tools_on_create', $tool->getName())
  410. );
  411. $toolObject = new CTool();
  412. $toolObject->setName($tool->getName())
  413. ->setCategory($tool->getCategory())
  414. ->setLink($tool->getLink())
  415. ->setImage($tool->getImage())
  416. ->setVisibility($visibility)
  417. ->setAdmin(0)
  418. ->setTarget($tool->getTarget())
  419. ;
  420. $tools[] = $toolObject;
  421. $settings = $settingsManager->loadSettings($tool->getName());
  422. $settingsManager->saveSettings($tool->getName(), $settings);
  423. }
  424. $course->setTools($tools);
  425. $entityManager->persist($course);
  426. $entityManager->flush($course);
  427. $courseInfo = api_get_course_info_by_id($course_id);
  428. $now = api_get_utc_datetime(time());
  429. $tbl_course_homepage = Database::get_course_table(TABLE_TOOL_LIST);
  430. $TABLEINTROS = Database::get_course_table(TABLE_TOOL_INTRO);
  431. $TABLEGROUPCATEGORIES = Database::get_course_table(
  432. TABLE_GROUP_CATEGORY
  433. );
  434. $TABLEITEMPROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY);
  435. $TABLETOOLAGENDA = Database::get_course_table(TABLE_AGENDA);
  436. $TABLETOOLANNOUNCEMENTS = Database::get_course_table(
  437. TABLE_ANNOUNCEMENT
  438. );
  439. $TABLETOOLDOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
  440. $TABLETOOLLINK = Database::get_course_table(TABLE_LINK);
  441. $TABLEQUIZ = Database::get_course_table(TABLE_QUIZ_TEST);
  442. $TABLEQUIZQUESTION = Database::get_course_table(
  443. TABLE_QUIZ_TEST_QUESTION
  444. );
  445. $TABLEQUIZQUESTIONLIST = Database::get_course_table(
  446. TABLE_QUIZ_QUESTION
  447. );
  448. $TABLEQUIZANSWERSLIST = Database::get_course_table(TABLE_QUIZ_ANSWER);
  449. $TABLESETTING = Database::get_course_table(TABLE_COURSE_SETTING);
  450. $TABLEFORUMCATEGORIES = Database::get_course_table(
  451. TABLE_FORUM_CATEGORY
  452. );
  453. $TABLEFORUMS = Database::get_course_table(TABLE_FORUM);
  454. $TABLEFORUMTHREADS = Database::get_course_table(TABLE_FORUM_THREAD);
  455. $TABLEFORUMPOSTS = Database::get_course_table(TABLE_FORUM_POST);
  456. $TABLEGRADEBOOKCERT = Database::get_main_table(
  457. TABLE_MAIN_GRADEBOOK_CERTIFICATE
  458. );
  459. $visible_for_all = 1;
  460. $visible_for_course_admin = 0;
  461. $visible_for_platform_admin = 2;
  462. /* Course tools */
  463. $alert = api_get_setting('exercise.email_alert_manager_on_new_quiz');
  464. if ($alert === 'true') {
  465. $defaultEmailExerciseAlert = 1;
  466. } else {
  467. $defaultEmailExerciseAlert = 0;
  468. }
  469. /* course_setting table (courseinfo tool) */
  470. $settings = [
  471. 'email_alert_manager_on_new_doc' => ['title' => '', 'default' => 0, 'category' => 'work'],
  472. 'email_alert_on_new_doc_dropbox' => ['default' => 0, 'category' => 'dropbox'],
  473. 'allow_user_edit_agenda' => ['default' => 0, 'category' => 'agenda'],
  474. 'allow_user_edit_announcement' => ['default' => 0, 'category' => 'announcement'],
  475. 'email_alert_manager_on_new_quiz' => ['default' => $defaultEmailExerciseAlert, 'category' => 'quiz'],
  476. 'allow_user_image_forum' => ['default' => 1, 'category' => 'forum'],
  477. 'course_theme' => ['default' => '', 'category' => 'theme'],
  478. 'allow_learning_path_theme' => ['default' => 1, 'category' => 'theme'],
  479. 'allow_open_chat_window' => ['default' => 1, 'category' => 'chat'],
  480. 'email_alert_to_teacher_on_new_user_in_course' => ['default' => 0, 'category' =>'registration'],
  481. 'allow_user_view_user_list' => ['default' =>1, 'category' =>'user'],
  482. 'display_info_advance_inside_homecourse' => ['default' => 1, 'category' =>'thematic_advance'],
  483. 'email_alert_students_on_new_homework' => ['default' => 0, 'category' =>'work'],
  484. 'enable_lp_auto_launch' => ['default' => 0, 'category' =>'learning_path'],
  485. 'pdf_export_watermark_text' => ['default' =>'', 'category' =>'learning_path'],
  486. 'allow_public_certificates' => [
  487. 'default' => api_get_setting('course.allow_public_certificates') === 'true' ? 1 : '',
  488. 'category' =>'certificates'
  489. ],
  490. 'documents_default_visibility' => ['default' =>'visible', 'category' =>'document'],
  491. 'show_course_in_user_language' => ['default' => 2],
  492. ];
  493. /*$counter = 1;
  494. foreach ($settings as $variable => $setting) {
  495. Database::query(
  496. "INSERT INTO $TABLESETTING (id, c_id, variable, value, category)
  497. VALUES ($counter, $course_id, '".$variable."', '".$setting['default']."', '".$setting['category']."')"
  498. );
  499. $counter++;
  500. }*/
  501. /* Course homepage tools for platform admin only */
  502. /* Group tool */
  503. Database::query(
  504. "INSERT INTO $TABLEGROUPCATEGORIES (c_id, id, title , description, max_student, self_reg_allowed, self_unreg_allowed, groups_per_user, display_order)
  505. VALUES ($course_id, '2', '" . self::lang2db(get_lang('DefaultGroupCategory')) . "', '', '8', '0', '0', '0', '0');"
  506. );
  507. /* Example Material */
  508. $language_interface = !empty($language_interface) ? $language_interface : api_get_setting('language.platform_language');
  509. // Example material should be in the same language as the course is.
  510. $language_interface_original = $language_interface;
  511. $now = api_get_utc_datetime();
  512. $files = [
  513. ['path' => '/shared_folder', 'title' => get_lang('UserFolders'), 'filetype' => 'folder', 'size' => 0],
  514. ['path' => '/chat_files', 'title' => get_lang('ChatFiles'), 'filetype' => 'folder', 'size' => 0],
  515. ];
  516. $counter = 1;
  517. foreach ($files as $file) {
  518. self::insertDocument($course_id, $counter, $file);
  519. $counter++;
  520. }
  521. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  522. $perm = api_get_permissions_for_new_directories();
  523. $perm_file = api_get_permissions_for_new_files();
  524. $chat_path = $sys_course_path . $course_repository . '/document/chat_files';
  525. if (!is_dir($chat_path)) {
  526. @mkdir($chat_path, api_get_permissions_for_new_directories());
  527. }
  528. /* Documents */
  529. if ($fill_with_exemplary_content) {
  530. $files = [
  531. ['path' => '/images', 'title' => get_lang('Images'), 'filetype' => 'folder', 'size' => 0],
  532. ['path' => '/images/gallery', 'title' => get_lang('DefaultCourseImages'), 'filetype' => 'folder', 'size' => 0],
  533. ['path' => '/audio', 'title' => get_lang('Audio'), 'filetype' => 'folder', 'size' => 0],
  534. ['path' => '/flash', 'title' => get_lang('Flash'), 'filetype' => 'folder', 'size' => 0],
  535. ['path' => '/video', 'title' => get_lang('Video'), 'filetype' => 'folder', 'size' => 0],
  536. ['path' => '/certificates', 'title' => get_lang('Certificates'), 'filetype' => 'folder', 'size' => 0]
  537. ];
  538. foreach ($files as $file) {
  539. self::insertDocument($course_id, $counter, $file);
  540. $counter++;
  541. }
  542. // FILL THE COURSE DOCUMENT WITH DEFAULT COURSE PICTURES
  543. $folders_to_copy_from_default_course = array(
  544. 'images',
  545. 'audio',
  546. 'flash',
  547. 'video',
  548. 'certificates',
  549. );
  550. $default_course_path = api_get_path(SYS_CODE_PATH) . 'default_course_document/';
  551. $default_document_array = array();
  552. foreach ($folders_to_copy_from_default_course as $folder) {
  553. $default_course_folder_path = $default_course_path . $folder . '/';
  554. $files = self::browse_folders(
  555. $default_course_folder_path,
  556. array(),
  557. $folder
  558. );
  559. $sorted_array = self::sort_pictures($files, 'dir');
  560. $sorted_array = array_merge(
  561. $sorted_array,
  562. self::sort_pictures($files, 'file')
  563. );
  564. $default_document_array[$folder] = $sorted_array;
  565. }
  566. // Light protection (adding index.html in every document folder)
  567. $htmlpage = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Not authorized</title>\n </head>\n <body>\n </body>\n</html>";
  568. $example_cert_id = 0;
  569. if (is_array($default_document_array) && count(
  570. $default_document_array
  571. ) > 0
  572. ) {
  573. foreach ($default_document_array as $media_type => $array_media) {
  574. $path_documents = "/$media_type/";
  575. //hack until feature #5242 is implemented
  576. if ($media_type == 'images') {
  577. $media_type = 'images/gallery';
  578. $images_folder = $sys_course_path . $course_repository . "/document/images/";
  579. if (!is_dir($images_folder)) {
  580. //Creating index.html
  581. mkdir($images_folder, $perm);
  582. $fd = fopen($images_folder . 'index.html', 'w');
  583. fwrite($fd, $htmlpage);
  584. @chmod($images_folder . 'index.html', $perm_file);
  585. }
  586. }
  587. $course_documents_folder = $sys_course_path . $course_repository . "/document/$media_type/";
  588. $default_course_path = api_get_path(SYS_CODE_PATH) . 'default_course_document' . $path_documents;
  589. if (!is_dir($course_documents_folder)) {
  590. // Creating index.html
  591. mkdir($course_documents_folder, $perm);
  592. $fd = fopen(
  593. $course_documents_folder . 'index.html',
  594. 'w'
  595. );
  596. fwrite($fd, $htmlpage);
  597. @chmod(
  598. $course_documents_folder . 'index.html',
  599. $perm_file
  600. );
  601. }
  602. if (is_array($array_media) && count($array_media) > 0) {
  603. foreach ($array_media as $key => $value) {
  604. if (isset($value['dir']) && !empty($value['dir'])) {
  605. if (!is_dir($course_documents_folder . $value['dir'])) {
  606. //Creating folder
  607. mkdir(
  608. $course_documents_folder . $value['dir'],
  609. $perm
  610. );
  611. //Creating index.html (for light protection)
  612. $index_html = $course_documents_folder . $value['dir'] . '/index.html';
  613. $fd = fopen($index_html, 'w');
  614. fwrite($fd, $htmlpage);
  615. @chmod($index_html, $perm_file);
  616. //Inserting folder in the DB
  617. $folder_path = substr(
  618. $value['dir'],
  619. 0,
  620. strlen($value['dir']) - 1
  621. );
  622. $temp = explode('/', $folder_path);
  623. $title = $temp[count($temp) - 1];
  624. //hack until feature #5242 is implemented
  625. if ($title == 'gallery') {
  626. $title = get_lang(
  627. 'DefaultCourseImages'
  628. );
  629. }
  630. if ($media_type == 'images/gallery') {
  631. $folder_path = 'gallery/' . $folder_path;
  632. }
  633. Database::query(
  634. "INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size)
  635. VALUES ($course_id,'$path_documents" . $folder_path . "','" . $title . "','folder','0')"
  636. );
  637. $image_id = Database:: insert_id();
  638. Database::insert(
  639. $TABLEITEMPROPERTY,
  640. [
  641. 'c_id' => $course_id,
  642. 'tool' => 'document',
  643. 'insert_user_id' => api_get_user_id(),
  644. 'insert_date' => $now,
  645. 'lastedit_date' => $now,
  646. 'ref' => $image_id,
  647. 'lastedit_type' => 'DocumentAdded',
  648. 'lastedit_user_id' => api_get_user_id(),
  649. 'to_group_id' => null,
  650. 'to_user_id' => null,
  651. 'visibility' => 0
  652. ]
  653. );
  654. }
  655. }
  656. if (isset($value['file']) && !empty($value['file'])) {
  657. if (!file_exists(
  658. $course_documents_folder . $value['file']
  659. )
  660. ) {
  661. //Copying file
  662. copy(
  663. $default_course_path . $value['file'],
  664. $course_documents_folder . $value['file']
  665. );
  666. chmod(
  667. $course_documents_folder . $value['file'],
  668. $perm_file
  669. );
  670. //echo $default_course_path.$value['file']; echo ' - '; echo $course_documents_folder.$value['file']; echo '<br />';
  671. $temp = explode('/', $value['file']);
  672. $file_size = filesize(
  673. $course_documents_folder . $value['file']
  674. );
  675. //hack until feature #5242 is implemented
  676. if ($media_type == 'images/gallery') {
  677. $value["file"] = 'gallery/' . $value["file"];
  678. }
  679. //Inserting file in the DB
  680. Database::query(
  681. "INSERT INTO $TABLETOOLDOCUMENT (c_id, path,title,filetype,size)
  682. VALUES ($course_id,'$path_documents" . $value["file"] . "','" . $temp[count($temp) - 1] . "','file','$file_size')"
  683. );
  684. $image_id = Database:: insert_id();
  685. if ($image_id) {
  686. $sql = "UPDATE $TABLETOOLDOCUMENT SET id = iid WHERE iid = $image_id";
  687. Database::query($sql);
  688. if ($path_documents . $value['file'] == '/certificates/default.html') {
  689. $example_cert_id = $image_id;
  690. }
  691. $docId = Database::insert(
  692. $TABLEITEMPROPERTY,
  693. [
  694. 'c_id' => $course_id,
  695. 'tool' => 'document',
  696. 'insert_user_id' => api_get_user_id(),
  697. 'insert_date' => $now,
  698. 'lastedit_date' => $now,
  699. 'ref' => $image_id,
  700. 'lastedit_type' => 'DocumentAdded',
  701. 'lastedit_user_id' => api_get_user_id(),
  702. 'to_group_id' => null,
  703. 'to_user_id' => null,
  704. 'visibility' => 1
  705. ]
  706. );
  707. if ($docId) {
  708. $sql = "UPDATE $TABLEITEMPROPERTY SET id = iid WHERE iid = $docId";
  709. Database::query($sql);
  710. }
  711. }
  712. }
  713. }
  714. }
  715. }
  716. }
  717. }
  718. $agenda = new Agenda();
  719. $agenda->setType('course');
  720. $agenda->set_course($courseInfo);
  721. $agenda->addEvent(
  722. $now,
  723. $now,
  724. 0,
  725. get_lang('AgendaCreationTitle'),
  726. get_lang('AgendaCreationContenu')
  727. );
  728. /* Links tool */
  729. $link = new Link();
  730. $link->setCourse($courseInfo);
  731. $links = [
  732. [
  733. 'c_id' => $course_id,
  734. 'url' => 'http://www.google.com',
  735. 'title' => 'Google',
  736. 'description' => get_lang('Google') ,
  737. 'category_id' => 0,
  738. 'on_homepage' => 0,
  739. 'target' => '_self',
  740. 'session_id' => 0
  741. ],
  742. [
  743. 'c_id' => $course_id,
  744. 'url' => 'http://www.wikipedia.org',
  745. 'title' => 'Wikipedia',
  746. 'description' => get_lang('Wikipedia') ,
  747. 'category_id' => 0,
  748. 'on_homepage' => 0,
  749. 'target' => '_self',
  750. 'session_id' => 0
  751. ]
  752. ];
  753. foreach($links as $params) {
  754. $link->save($params);
  755. }
  756. /* Announcement tool */
  757. AnnouncementManager::add_announcement(
  758. get_lang('AnnouncementExampleTitle'),
  759. get_lang('AnnouncementEx'),
  760. ['everyone' => 'everyone'],
  761. null,
  762. null,
  763. $now
  764. );
  765. $manager = Database::getManager();
  766. /* Introduction text */
  767. $intro_text = '<p style="text-align: center;">
  768. <img src="' . api_get_path(REL_CODE_PATH) . 'img/mascot.png" alt="Mr. Chamilo" title="Mr. Chamilo" />
  769. <h2>' . get_lang('IntroductionText') . '</h2>
  770. </p>';
  771. $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
  772. $toolIntro
  773. ->setCId($course_id)
  774. ->setId(TOOL_COURSE_HOMEPAGE)
  775. ->setSessionId(0)
  776. ->setIntroText($intro_text);
  777. $manager->persist($toolIntro);
  778. $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
  779. $toolIntro
  780. ->setCId($course_id)
  781. ->setId(TOOL_STUDENTPUBLICATION)
  782. ->setSessionId(0)
  783. ->setIntroText(get_lang('IntroductionTwo'));
  784. $manager->persist($toolIntro);
  785. $toolIntro = new Chamilo\CourseBundle\Entity\CToolIntro();
  786. $toolIntro
  787. ->setCId($course_id)
  788. ->setId(TOOL_WIKI)
  789. ->setSessionId(0)
  790. ->setIntroText(get_lang('IntroductionWiki'));
  791. $manager->persist($toolIntro);
  792. $manager->flush();
  793. /* Exercise tool */
  794. $exercise = new Exercise($course_id);
  795. $exercise->exercise = get_lang('ExerciceEx');
  796. $html = '<table width="100%" border="0" cellpadding="0" cellspacing="0">
  797. <tr>
  798. <td width="220" valign="top" align="left">
  799. <img src="' . api_get_path(WEB_CODE_PATH) . 'default_course_document/images/mr_chamilo/doubts.png">
  800. </td>
  801. <td valign="top" align="left">' . get_lang('Antique') . '</td></tr>
  802. </table>';
  803. $exercise->type = 1;
  804. $exercise->setRandom(0);
  805. $exercise->active = 1;
  806. $exercise->results_disabled = 0;
  807. $exercise->description = $html;
  808. $exercise->save();
  809. $exercise_id = $exercise->id;
  810. $question = new MultipleAnswer();
  811. $question->question = get_lang('SocraticIrony');
  812. $question->description = get_lang('ManyAnswers');
  813. $question->weighting = 10;
  814. $question->position = 1;
  815. $question->course = $courseInfo;
  816. $question->save($exercise_id);
  817. $questionId = $question->id;
  818. $answer = new Answer($questionId, $courseInfo['real_id']);
  819. $answer->createAnswer(get_lang('Ridiculise'), 0, get_lang('NoPsychology'), -5, 1);
  820. $answer->createAnswer(get_lang('AdmitError'), 0, get_lang('NoSeduction'), -5, 2);
  821. $answer->createAnswer(get_lang('Force'), 1, get_lang('Indeed'), 5, 3);
  822. $answer->createAnswer(get_lang('Contradiction'), 1, get_lang('NotFalse'), 5, 4);
  823. $answer->save();
  824. /* Forum tool */
  825. require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
  826. $params = [
  827. 'forum_category_title' => get_lang('ExampleForumCategory'),
  828. 'forum_category_comment' => ''
  829. ];
  830. $forumCategoryId = store_forumcategory($params, $courseInfo, false);
  831. $params = [
  832. 'forum_category' => $forumCategoryId,
  833. 'forum_title' => get_lang('ExampleForum'),
  834. 'forum_comment' => '',
  835. 'default_view_type_group' => ['default_view_type' => 'flat'],
  836. ];
  837. $forumId = store_forum($params, $courseInfo, true);
  838. $forumInfo = get_forum_information($forumId, $courseInfo['real_id']);
  839. $params = [
  840. 'post_title' => get_lang('ExampleThread'),
  841. 'forum_id' => $forumId,
  842. 'post_text' => get_lang('ExampleThreadContent'),
  843. 'calification_notebook_title' => '',
  844. 'numeric_calification' => '',
  845. 'weight_calification' => '',
  846. 'forum_category' => $forumCategoryId,
  847. 'thread_peer_qualify' => 0,
  848. ];
  849. store_thread($forumInfo, $params, $courseInfo, false);
  850. /* Gradebook tool */
  851. $course_code = $courseInfo['code'];
  852. // father gradebook
  853. $gradebookCategory = new Chamilo\CoreBundle\Entity\GradebookCategory();
  854. $gradebookCategory
  855. ->setName($course_code)
  856. ->setDescription('')
  857. ->setUserId(1)
  858. ->setCourse($course)
  859. ->setParentId(0)
  860. ->setWeight(100)
  861. ->setVisible(0)
  862. ->setCertifMinScore(75)
  863. ->setSessionId(null)
  864. ->setDocumentId($example_cert_id);
  865. $manager->persist($gradebookCategory);
  866. $manager->flush();
  867. $gbid = $gradebookCategory->getId();
  868. $gradebookCategory = new Chamilo\CoreBundle\Entity\GradebookCategory();
  869. $gradebookCategory
  870. ->setName($course_code)
  871. ->setDescription('')
  872. ->setUserId(1)
  873. ->setCourse($course)
  874. ->setParentId($gbid)
  875. ->setWeight(100)
  876. ->setVisible(1)
  877. ->setCertifMinScore(75)
  878. ->setSessionId(null)
  879. ->setDocumentId($example_cert_id);
  880. $manager->persist($gradebookCategory);
  881. $manager->flush();
  882. $gbid = $gradebookCategory->getId();
  883. $createdAt = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
  884. $gradebookLink = new \Chamilo\CoreBundle\Entity\GradebookLink();
  885. $gradebookLink
  886. ->setType(1)
  887. ->setRefId($exercise_id)
  888. ->setUserId(1)
  889. ->setCourse($course)
  890. ->setCategoryId($gbid)
  891. ->setCreatedAt($createdAt)
  892. ->setWeight(100)
  893. ->setVisible(1)
  894. ->setLocked(0);
  895. $manager->persist($gradebookLink);
  896. $manager->flush();
  897. }
  898. //Installing plugins in course
  899. $app_plugin = new AppPlugin();
  900. $app_plugin->install_course_plugins($course_id);
  901. return true;
  902. }
  903. /**
  904. * @param int $course_id
  905. * @param int $counter
  906. * @param array $file
  907. * @param int $authorId
  908. */
  909. public static function insertDocument($course_id, $counter, $file, $authorId = 0)
  910. {
  911. $tableItem = Database::get_course_table(TABLE_ITEM_PROPERTY);
  912. $tableDocument = Database::get_course_table(TABLE_DOCUMENT);
  913. $now = api_get_utc_datetime();
  914. $sql = "INSERT INTO $tableDocument (id, c_id, path,title,filetype,size, readonly, session_id)
  915. VALUES ($counter, $course_id, '".$file['path']."', '".$file['title']."', '".$file['filetype']."', '".$file['size']."', 0, 0)";
  916. Database::query($sql);
  917. $docId = Database:: insert_id();
  918. $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
  919. if ($docId) {
  920. $sql = "UPDATE $tableDocument SET id = iid WHERE iid = $docId";
  921. Database::query($sql);
  922. $id = Database::insert(
  923. $tableItem,
  924. [
  925. 'id' => $counter,
  926. 'c_id' => $course_id,
  927. 'tool' => 'document',
  928. 'insert_user_id' => $authorId,
  929. 'insert_date' => $now,
  930. 'lastedit_date' => $now,
  931. 'ref' => $docId,
  932. 'lastedit_type' => 'DocumentAdded',
  933. 'lastedit_user_id' => $authorId,
  934. 'to_group_id' => null,
  935. 'to_user_id' => null,
  936. 'visibility' => 0
  937. ]
  938. );
  939. if ($id) {
  940. $sql = "UPDATE $tableItem SET id = iid WHERE iid = $id";
  941. Database::query($sql);
  942. }
  943. }
  944. }
  945. /**
  946. * string2binary converts the string "true" or "false" to the boolean true false (0 or 1)
  947. * This is used for the Chamilo Config Settings as these store true or false as string
  948. * and the api_get_setting('course_create_active_tools') should be 0 or 1 (used for
  949. * the visibility of the tool)
  950. * @param string $variable
  951. * @author Patrick Cool, patrick.cool@ugent.be
  952. * @assert ('true') === true
  953. * @assert ('false') === false
  954. */
  955. public static function string2binary($variable)
  956. {
  957. if ($variable == 'true') {
  958. return true;
  959. }
  960. if ($variable == 'false') {
  961. return false;
  962. }
  963. }
  964. /**
  965. * Function register_course to create a record in the course table of the main database
  966. * @param array Course details (see code for details)
  967. * @return int Created course ID
  968. * @todo use an array called $params instead of lots of params
  969. * @assert (null) === false
  970. */
  971. public static function register_course($params)
  972. {
  973. global $error_msg;
  974. $title = $params['title'];
  975. $code = $params['code'];
  976. $visual_code = $params['visual_code'];
  977. $directory = $params['directory'];
  978. $tutor_name = isset($params['tutor_name']) ? $params['tutor_name'] : null;
  979. $category_code = isset($params['course_category']) ? $params['course_category'] : '';
  980. $course_language = isset($params['course_language']) && !empty($params['course_language']) ? $params['course_language'] : api_get_setting(
  981. 'language.platform_language'
  982. );
  983. $user_id = empty($params['user_id']) ? api_get_user_id() : intval($params['user_id']);
  984. $department_name = isset($params['department_name']) ?
  985. $params['department_name'] : null;
  986. $department_url = isset($params['department_url']) ?
  987. $params['department_url'] : null;
  988. $disk_quota = isset($params['disk_quota']) ?
  989. $params['disk_quota'] : null;
  990. if (!isset($params['visibility'])) {
  991. $default_course_visibility = api_get_setting('course.courses_default_creation_visibility');
  992. if ($default_course_visibility != '') {
  993. $visibility = $default_course_visibility;
  994. } else {
  995. $visibility = COURSE_VISIBILITY_OPEN_PLATFORM;
  996. }
  997. } else {
  998. $visibility = $params['visibility'];
  999. }
  1000. $subscribe = isset($params['subscribe']) ? intval(
  1001. $params['subscribe']
  1002. ) : ($visibility == COURSE_VISIBILITY_OPEN_PLATFORM ? 1 : 0);
  1003. $unsubscribe = isset($params['unsubscribe']) ? intval(
  1004. $params['unsubscribe']
  1005. ) : 0;
  1006. $expiration_date = isset($params['expiration_date']) ? $params['expiration_date'] : null;
  1007. $teachers = isset($params['teachers']) ? $params['teachers'] : null;
  1008. $status = isset($params['status']) ? $params['status'] : null;
  1009. $TABLECOURSE = Database:: get_main_table(TABLE_MAIN_COURSE);
  1010. $TABLECOURSUSER = Database:: get_main_table(TABLE_MAIN_COURSE_USER);
  1011. $ok_to_register_course = true;
  1012. // Check whether all the needed parameters are present.
  1013. if (empty($code)) {
  1014. $error_msg[] = 'courseSysCode is missing';
  1015. $ok_to_register_course = false;
  1016. }
  1017. if (empty($visual_code)) {
  1018. $error_msg[] = 'courseScreenCode is missing';
  1019. $ok_to_register_course = false;
  1020. }
  1021. if (empty($directory)) {
  1022. $error_msg[] = 'courseRepository is missing';
  1023. $ok_to_register_course = false;
  1024. }
  1025. if (empty($title)) {
  1026. $error_msg[] = 'title is missing';
  1027. $ok_to_register_course = false;
  1028. }
  1029. if (empty($expiration_date)) {
  1030. $expiration_date = api_get_utc_datetime(
  1031. time() + $firstExpirationDelay
  1032. );
  1033. } else {
  1034. $expiration_date = api_get_utc_datetime($expiration_date);
  1035. }
  1036. if ($visibility < 0 || $visibility > 4) {
  1037. $error_msg[] = 'visibility is invalid';
  1038. $ok_to_register_course = false;
  1039. }
  1040. if (empty($disk_quota)) {
  1041. $disk_quota = api_get_setting('document.default_document_quotum');
  1042. }
  1043. $time = api_get_utc_datetime();
  1044. if (stripos($department_url, 'http://') === false && stripos(
  1045. $department_url,
  1046. 'https://'
  1047. ) === false
  1048. ) {
  1049. $department_url = 'http://' . $department_url;
  1050. }
  1051. //just in case
  1052. if ($department_url == 'http://') {
  1053. $department_url = '';
  1054. }
  1055. $course_id = 0;
  1056. if ($ok_to_register_course) {
  1057. $manager = Database::getManager();
  1058. $url = $manager->getRepository('ChamiloCoreBundle:AccessUrl')->find(api_get_current_access_url_id());
  1059. $accessRelCourse = new AccessUrlRelCourse();
  1060. $accessRelCourse->setUrl($url);
  1061. $course = new Course();
  1062. $course
  1063. ->setCode($code)
  1064. ->setDirectory($directory)
  1065. ->setCourseLanguage($course_language)
  1066. ->setTitle($title)
  1067. ->setDescription(self::lang2db(get_lang('CourseDescription')))
  1068. ->setCategoryCode($category_code)
  1069. ->setVisibility($visibility)
  1070. ->setShowScore(1)
  1071. ->setExpirationDate($expiration_date)
  1072. ->setDiskQuota(intval($disk_quota))
  1073. ->setTutorName($tutor_name)
  1074. ->setDepartmentName($department_name)
  1075. ->setDepartmentUrl($department_url)
  1076. ->setSubscribe(intval($subscribe))
  1077. ->setVisualCode($visual_code)
  1078. ->addUrls($accessRelCourse)
  1079. ;
  1080. $manager->persist($course);
  1081. $manager->flush();
  1082. $course_id = $course->getId();
  1083. if ($course_id) {
  1084. $sort = api_max_sort_value('0', api_get_user_id());
  1085. // Default true
  1086. $addTeacher = isset($params['add_user_as_teacher']) ? $params['add_user_as_teacher'] : true;
  1087. if ($addTeacher) {
  1088. $i_course_sort = CourseManager:: userCourseSort(
  1089. $user_id,
  1090. $code
  1091. );
  1092. if (!empty($user_id)) {
  1093. $sql = "INSERT INTO " . $TABLECOURSUSER . " SET
  1094. c_id = '" . $course_id . "',
  1095. user_id = '" . intval($user_id) . "',
  1096. status = '1',
  1097. is_tutor = '0',
  1098. sort = '" . ($i_course_sort) . "',
  1099. relation_type = 0,
  1100. user_course_cat = '0'";
  1101. Database::query($sql);
  1102. }
  1103. }
  1104. if (!empty($teachers)) {
  1105. if (!is_array($teachers)) {
  1106. $teachers = array($teachers);
  1107. }
  1108. foreach ($teachers as $key) {
  1109. //just in case
  1110. if ($key == $user_id) {
  1111. continue;
  1112. }
  1113. if (empty($key)) {
  1114. continue;
  1115. }
  1116. $sql = "INSERT INTO " . $TABLECOURSUSER . " SET
  1117. c_id = '" . Database::escape_string($course_id) . "',
  1118. user_id = '" . Database::escape_string($key) . "',
  1119. status = '1',
  1120. is_tutor = '0',
  1121. sort = '" . ($sort + 1) . "',
  1122. relation_type = 0,
  1123. user_course_cat = '0'";
  1124. Database::query($sql);
  1125. }
  1126. }
  1127. // Adding the course to an URL.
  1128. if (api_is_multiple_url_enabled()) {
  1129. $url_id = 1;
  1130. if (api_get_current_access_url_id() != -1) {
  1131. $url_id = api_get_current_access_url_id();
  1132. }
  1133. UrlManager::add_course_to_url($course_id, $url_id);
  1134. } else {
  1135. UrlManager::add_course_to_url($course_id, 1);
  1136. }
  1137. // Add event to the system log.
  1138. $user_id = api_get_user_id();
  1139. Event::addEvent(
  1140. LOG_COURSE_CREATE,
  1141. LOG_COURSE_CODE,
  1142. $code,
  1143. api_get_utc_datetime(),
  1144. $user_id,
  1145. $course_id
  1146. );
  1147. $send_mail_to_admin = api_get_setting(
  1148. 'course.send_email_to_admin_when_create_course'
  1149. );
  1150. // @todo Improve code to send to all current portal administrators.
  1151. if ($send_mail_to_admin == 'true') {
  1152. $siteName = api_get_setting('platform.site_name');
  1153. $recipient_email = api_get_setting('admin.administrator_email');
  1154. $recipient_name = api_get_person_name(
  1155. api_get_setting('admin.administrator_name'),
  1156. api_get_setting('admin.administrator_surname')
  1157. );
  1158. $iname = api_get_setting('platform.institution');
  1159. $subject = get_lang('NewCourseCreatedIn') . ' ' . $siteName . ' - ' . $iname;
  1160. $message = get_lang('Dear') . ' ' . $recipient_name . ",\n\n" .
  1161. get_lang('MessageOfNewCourseToAdmin') . ' ' . $siteName . ' - ' . $iname . "\n";
  1162. $message .= get_lang('CourseName') . ' ' . $title . "\n";
  1163. $message .= get_lang('Category') . ' ' . $category_code . "\n";
  1164. $message .= get_lang('Tutor') . ' ' . $tutor_name . "\n";
  1165. $message .= get_lang('Language') . ' ' . $course_language;
  1166. $userInfo = api_get_user_info($user_id);
  1167. $additionalParameters = array(
  1168. 'smsType' => SmsPlugin::NEW_COURSE_BEEN_CREATED,
  1169. 'userId' => $user_id,
  1170. 'courseName' => $title,
  1171. 'creatorUsername' => $userInfo['username']
  1172. );
  1173. api_mail_html(
  1174. $recipient_name,
  1175. $recipient_email,
  1176. $subject,
  1177. $message,
  1178. $siteName,
  1179. $recipient_email,
  1180. null,
  1181. null,
  1182. null,
  1183. $additionalParameters
  1184. );
  1185. }
  1186. }
  1187. }
  1188. return $course_id;
  1189. }
  1190. /**
  1191. * Generate a new id for c_tool table
  1192. * @param int $courseId The course id
  1193. * @return int the new id
  1194. */
  1195. public static function generateToolId($courseId)
  1196. {
  1197. $newIdResultData = Database::select(
  1198. 'id + 1 AS new_id',
  1199. Database::get_course_table(TABLE_TOOL_LIST),
  1200. [
  1201. 'where' => ['c_id = ?' => intval($courseId)],
  1202. 'order' => 'id',
  1203. 'limit' => 1
  1204. ],
  1205. 'first'
  1206. );
  1207. if ($newIdResultData === false) {
  1208. return 1;
  1209. }
  1210. return $newIdResultData['new_id'] > 0 ? $newIdResultData['new_id'] : 1;
  1211. }
  1212. }