import_csv.php 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. if (PHP_SAPI != 'cli') {
  4. die('Run this script through the command line or comment this line in the code');
  5. }
  6. if (file_exists('multiple_url_fix.php')) {
  7. require 'multiple_url_fix.php';
  8. }
  9. require_once __DIR__.'/../inc/global.inc.php';
  10. ini_set('memory_limit', -1);
  11. ini_set('max_execution_time', 0);
  12. /**
  13. * Class ImportCsv
  14. */
  15. class ImportCsv
  16. {
  17. private $logger;
  18. private $dumpValues;
  19. public $test;
  20. public $defaultLanguage = 'dutch';
  21. public $extraFieldIdNameList = array(
  22. 'session' => 'external_session_id',
  23. 'course' => 'external_course_id',
  24. 'user' => 'external_user_id',
  25. 'calendar_event' => 'external_calendar_event_id',
  26. );
  27. public $defaultAdminId = 1;
  28. public $defaultSessionVisibility = 1;
  29. /**
  30. * When creating a user the expiration date is set to registration date + this value
  31. * @var int number of years
  32. */
  33. public $expirationDateInUserCreation = 1;
  34. public $batchSize = 20;
  35. /**
  36. * When updating a user the expiration date is set to update date + this value
  37. * @var int number of years
  38. */
  39. public $expirationDateInUserUpdate = 1;
  40. public $daysCoachAccessBeforeBeginning = 14;
  41. public $daysCoachAccessAfterBeginning = 14;
  42. public $conditions;
  43. /**
  44. * @param Monolog\Logger $logger
  45. * @param array
  46. */
  47. public function __construct($logger, $conditions)
  48. {
  49. $this->logger = $logger;
  50. $this->conditions = $conditions;
  51. }
  52. /**
  53. * @param bool $dump
  54. */
  55. public function setDumpValues($dump)
  56. {
  57. $this->dumpValues = $dump;
  58. }
  59. /**
  60. * @return boolean
  61. */
  62. public function getDumpValues()
  63. {
  64. return $this->dumpValues;
  65. }
  66. /**
  67. * Runs the import process
  68. */
  69. public function run()
  70. {
  71. global $_configuration;
  72. $value = api_get_configuration_value('import_csv_custom_url_id');
  73. if (!empty($value)) {
  74. $_configuration['access_url'] = $value;
  75. }
  76. $path = api_get_path(SYS_CODE_PATH).'cron/incoming/';
  77. if (!is_dir($path)) {
  78. echo "The folder! $path does not exits";
  79. return 0;
  80. }
  81. if ($this->getDumpValues()) {
  82. $this->dumpDatabaseTables();
  83. }
  84. echo "Reading files: ".PHP_EOL.PHP_EOL;
  85. $files = scandir($path);
  86. $fileToProcess = array();
  87. $fileToProcessStatic = array();
  88. $teacherBackup = array();
  89. $groupBackup = array();
  90. if (!empty($files)) {
  91. foreach ($files as $file) {
  92. $fileInfo = pathinfo($file);
  93. if (isset($fileInfo['extension']) && $fileInfo['extension'] === 'csv') {
  94. // Checking teachers_yyyymmdd.csv, courses_yyyymmdd.csv, students_yyyymmdd.csv and sessions_yyyymmdd.csv
  95. $parts = explode('_', $fileInfo['filename']);
  96. $preMethod = ucwords($parts[1]);
  97. $preMethod = str_replace('-static', 'Static', $preMethod);
  98. $method = 'import'.$preMethod;
  99. $isStatic = strpos($method, 'Static');
  100. if ($method == 'importSessionsextidStatic') {
  101. $method = 'importSessionsExtIdStatic';
  102. }
  103. if ($method == 'importCourseinsertStatic') {
  104. $method = 'importSubscribeUserToCourse';
  105. }
  106. if ($method == 'importUnsubsessionsextidStatic') {
  107. $method = 'importUnsubsessionsExtidStatic';
  108. }
  109. if ($method == 'importSubsessionsextidStatic') {
  110. $method = 'importSubscribeUserToCourseSessionExtStatic';
  111. }
  112. if (method_exists($this, $method)) {
  113. if (
  114. (
  115. $method == 'importSubscribeStatic' ||
  116. $method == 'importSubscribeUserToCourse'
  117. ) ||
  118. empty($isStatic)
  119. ) {
  120. $fileToProcess[$parts[1]][] = array(
  121. 'method' => $method,
  122. 'file' => $path.$fileInfo['basename']
  123. );
  124. } else {
  125. $fileToProcessStatic[$parts[1]][] = array(
  126. 'method' => $method,
  127. 'file' => $path.$fileInfo['basename']
  128. );
  129. }
  130. } else {
  131. echo "Error - This file '$file' can't be processed.".PHP_EOL;
  132. echo "Trying to call $method".PHP_EOL;
  133. echo "The file have to has this format:".PHP_EOL;
  134. echo "prefix_students_ddmmyyyy.csv, prefix_teachers_ddmmyyyy.csv, prefix_courses_ddmmyyyy.csv, prefix_sessions_ddmmyyyy.csv ".PHP_EOL;
  135. exit;
  136. }
  137. }
  138. }
  139. if (empty($fileToProcess) && empty($fileToProcessStatic)) {
  140. echo 'Error - no files to process.';
  141. return 0;
  142. }
  143. $this->prepareImport();
  144. $sections = array(
  145. 'students',
  146. 'teachers',
  147. 'courses',
  148. 'sessions',
  149. 'subscribe-static',
  150. 'courseinsert-static',
  151. 'unsubscribe-static'
  152. );
  153. foreach ($sections as $section) {
  154. $this->logger->addInfo("-- Import $section --");
  155. if (isset($fileToProcess[$section]) && !empty($fileToProcess[$section])) {
  156. $files = $fileToProcess[$section];
  157. foreach ($files as $fileInfo) {
  158. $method = $fileInfo['method'];
  159. $file = $fileInfo['file'];
  160. echo 'File: '.$file.PHP_EOL;
  161. $this->logger->addInfo("Reading file: $file");
  162. if ($method == 'importSessions') {
  163. $this->$method(
  164. $file,
  165. true,
  166. $teacherBackup,
  167. $groupBackup
  168. );
  169. } else {
  170. $this->$method($file, true);
  171. }
  172. }
  173. }
  174. }
  175. $sections = array(
  176. 'students-static',
  177. 'teachers-static',
  178. 'courses-static',
  179. 'sessions-static',
  180. 'calendar-static',
  181. 'sessionsextid-static',
  182. 'unsubscribe-static',
  183. 'unsubsessionsextid-static',
  184. 'subsessionsextid-static'
  185. );
  186. foreach ($sections as $section) {
  187. $this->logger->addInfo("-- Import static files $section --");
  188. if (isset($fileToProcessStatic[$section]) &&
  189. !empty($fileToProcessStatic[$section])
  190. ) {
  191. $files = $fileToProcessStatic[$section];
  192. foreach ($files as $fileInfo) {
  193. $method = $fileInfo['method'];
  194. $file = $fileInfo['file'];
  195. echo 'Static file: '.$file.PHP_EOL;
  196. $this->logger->addInfo("Reading static file: $file");
  197. $this->$method(
  198. $file,
  199. true,
  200. $teacherBackup,
  201. $groupBackup
  202. );
  203. }
  204. }
  205. }
  206. }
  207. }
  208. /**
  209. * Prepares extra fields before the import
  210. */
  211. private function prepareImport()
  212. {
  213. // Create user extra field: extra_external_user_id
  214. UserManager::create_extra_field(
  215. $this->extraFieldIdNameList['user'],
  216. 1,
  217. 'External user id',
  218. null
  219. );
  220. // Create course extra field: extra_external_course_id
  221. CourseManager::create_course_extra_field(
  222. $this->extraFieldIdNameList['course'],
  223. 1,
  224. 'External course id',
  225. ''
  226. );
  227. // Create session extra field extra_external_session_id
  228. SessionManager::create_session_extra_field(
  229. $this->extraFieldIdNameList['session'],
  230. 1,
  231. 'External session id'
  232. );
  233. // Create calendar_event extra field extra_external_session_id
  234. $extraField = new ExtraField('calendar_event');
  235. $extraField->save(
  236. array(
  237. 'field_type' => ExtraField::FIELD_TYPE_TEXT,
  238. 'variable' => $this->extraFieldIdNameList['calendar_event'],
  239. 'display_text' => 'External calendar event id',
  240. )
  241. );
  242. }
  243. /**
  244. * @param string $file
  245. */
  246. private function moveFile($file)
  247. {
  248. $moved = str_replace('incoming', 'treated', $file);
  249. if ($this->test) {
  250. $result = 1;
  251. } else {
  252. $result = rename($file, $moved);
  253. }
  254. if ($result) {
  255. $this->logger->addInfo("Moving file to the treated folder: $file");
  256. } else {
  257. $this->logger->addError(
  258. "Error - Cant move file to the treated folder: $file"
  259. );
  260. }
  261. }
  262. /**
  263. * @param array $row
  264. *
  265. * @return array
  266. */
  267. private function cleanUserRow($row)
  268. {
  269. $row['lastname'] = $row['LastName'];
  270. $row['firstname'] = $row['FirstName'];
  271. $row['email'] = $row['Email'];
  272. $row['username'] = $row['UserName'];
  273. $row['password'] = $row['Password'];
  274. $row['auth_source'] = isset($row['AuthSource']) ? $row['AuthSource'] : PLATFORM_AUTH_SOURCE;
  275. $row['official_code'] = $row['OfficialCode'];
  276. $row['phone'] = isset($row['PhoneNumber']) ? $row['PhoneNumber'] : '';
  277. if (isset($row['StudentID'])) {
  278. $row['extra_'.$this->extraFieldIdNameList['user']] = $row['StudentID'];
  279. }
  280. if (isset($row['TeacherID'])) {
  281. $row['extra_'.$this->extraFieldIdNameList['user']] = $row['TeacherID'];
  282. }
  283. return $row;
  284. }
  285. /**
  286. * @param array $row
  287. *
  288. * @return array
  289. */
  290. private function cleanCourseRow($row)
  291. {
  292. $row['title'] = $row['Title'];
  293. $row['course_code'] = $row['Code'];
  294. $row['course_category'] = $row['CourseCategory'];
  295. $row['email'] = $row['Teacher'];
  296. $row['language'] = $row['Language'];
  297. $row['teachers'] = array();
  298. if (isset($row['Teacher']) && !empty($row['Teacher'])) {
  299. $teachers = explode(',', $row['Teacher']);
  300. if (!empty($teachers)) {
  301. foreach ($teachers as $teacherUserName) {
  302. $teacherUserName = trim($teacherUserName);
  303. $userInfo = api_get_user_info_from_username($teacherUserName);
  304. if (!empty($userInfo)) {
  305. $row['teachers'][] = $userInfo['user_id'];
  306. }
  307. }
  308. }
  309. }
  310. if (isset($row['CourseID'])) {
  311. $row['extra_'.$this->extraFieldIdNameList['course']] = $row['CourseID'];
  312. }
  313. return $row;
  314. }
  315. /**
  316. * File to import
  317. * @param string $file
  318. */
  319. private function importTeachersStatic($file)
  320. {
  321. $this->importTeachers($file, false);
  322. }
  323. /**
  324. * File to import
  325. * @param string $file
  326. * @param bool $moveFile
  327. */
  328. private function importTeachers($file, $moveFile = true)
  329. {
  330. $this->fixCSVFile($file);
  331. $data = Import::csvToArray($file);
  332. /* Unique identifier: official-code username.
  333. Email address and password should never get updated. *ok
  334. The only fields that I can think of that should update if the data changes in the csv file are FirstName and LastName. *ok
  335. A slight edit of these fields should be taken into account. ???
  336. Adding teachers is no problem, but deleting them shouldn’t be automated, but we should get a log of “to delete teachers”.
  337. We’ll handle that manually if applicable.
  338. No delete!
  339. */
  340. $language = $this->defaultLanguage;
  341. if (!empty($data)) {
  342. $this->logger->addInfo(count($data)." records found.");
  343. $expirationDateOnCreation = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserCreation)."years"));
  344. $expirationDateOnUpdate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserUpdate)."years"));
  345. $batchSize = $this->batchSize;
  346. $em = Database::getManager();
  347. $counter = 1;
  348. foreach ($data as $row) {
  349. $row = $this->cleanUserRow($row);
  350. $user_id = UserManager::get_user_id_from_original_id(
  351. $row['extra_'.$this->extraFieldIdNameList['user']],
  352. $this->extraFieldIdNameList['user']
  353. );
  354. $userInfo = array();
  355. $userInfoByOfficialCode = null;
  356. if (!empty($user_id)) {
  357. $userInfo = api_get_user_info($user_id);
  358. $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
  359. }
  360. if (empty($userInfo) && empty($userInfoByOfficialCode)) {
  361. // Create user
  362. $userId = UserManager::create_user(
  363. $row['firstname'],
  364. $row['lastname'],
  365. COURSEMANAGER,
  366. $row['email'],
  367. $row['username'],
  368. $row['password'],
  369. $row['official_code'],
  370. $language, //$row['language'],
  371. $row['phone'],
  372. null, //$row['picture'], //picture
  373. $row['auth_source'], // ?
  374. $expirationDateOnCreation, //'0000-00-00 00:00:00', //$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
  375. 1, //active
  376. 0,
  377. null, // extra
  378. null, //$encrypt_method = '',
  379. false //$send_mail = false
  380. );
  381. if ($userId) {
  382. foreach ($row as $key => $value) {
  383. if (substr($key, 0, 6) == 'extra_') {
  384. //an extra field
  385. UserManager::update_extra_field_value(
  386. $userId,
  387. substr($key, 6),
  388. $value
  389. );
  390. }
  391. }
  392. $this->logger->addInfo("Teachers - User created: ".$row['username']);
  393. } else {
  394. $this->logger->addError("Teachers - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
  395. $this->logger->addError(strip_tags(Display::getFlashToString()));
  396. Display::cleanFlashMessages();
  397. }
  398. } else {
  399. if (empty($userInfo)) {
  400. $this->logger->addError("Teachers - Can't update user :".$row['username']);
  401. continue;
  402. }
  403. // Update user
  404. $result = UserManager::update_user(
  405. $userInfo['user_id'],
  406. $row['firstname'], // <<-- changed
  407. $row['lastname'], // <<-- changed
  408. $userInfo['username'],
  409. null, //$password = null,
  410. $row['auth_source'],
  411. $userInfo['email'],
  412. COURSEMANAGER,
  413. $userInfo['official_code'],
  414. $userInfo['phone'],
  415. $userInfo['picture_uri'],
  416. $expirationDateOnUpdate,
  417. $userInfo['active'],
  418. null, //$creator_id = null,
  419. 0, //$hr_dept_id = 0,
  420. null, // $extra = null,
  421. null, //$language = 'english',
  422. null, //$encrypt_method = '',
  423. false, //$send_email = false,
  424. 0 //$reset_password = 0
  425. );
  426. if ($result) {
  427. foreach ($row as $key => $value) {
  428. if (substr($key, 0, 6) == 'extra_') {
  429. //an extra field
  430. UserManager::update_extra_field_value(
  431. $userInfo['user_id'],
  432. substr($key, 6),
  433. $value
  434. );
  435. }
  436. }
  437. $this->logger->addInfo("Teachers - User updated: ".$row['username']);
  438. } else {
  439. $this->logger->addError("Teachers - User not updated: ".$row['username']);
  440. }
  441. }
  442. if (($counter % $batchSize) === 0) {
  443. $em->flush();
  444. $em->clear(); // Detaches all objects from Doctrine!
  445. }
  446. $counter++;
  447. }
  448. $em->clear(); // Detaches all objects from Doctrine!
  449. }
  450. if ($moveFile) {
  451. $this->moveFile($file);
  452. }
  453. }
  454. /**
  455. * @param string $file
  456. */
  457. private function importStudentsStatic($file)
  458. {
  459. $this->importStudents($file, false);
  460. }
  461. /**
  462. * @param string $file
  463. * @param bool $moveFile
  464. */
  465. private function importStudents($file, $moveFile = true)
  466. {
  467. $this->fixCSVFile($file);
  468. $data = Import::csvToArray($file);
  469. /*
  470. * Another users import.
  471. Unique identifier: official code and username . ok
  472. Password should never get updated. ok
  473. If an update should need to occur (because it changed in the .csv),
  474. we’ll want that logged. We will handle this manually in that case.
  475. All other fields should be updateable, though passwords should of course not get updated. ok
  476. If a user gets deleted (not there anymore),
  477. He should be set inactive one year after the current date.
  478. So I presume you’ll just update the expiration date.
  479. We want to grant access to courses up to a year after deletion.
  480. */
  481. $timeStart = microtime(true);
  482. $batchSize = $this->batchSize;
  483. $em = Database::getManager();
  484. if (!empty($data)) {
  485. $language = $this->defaultLanguage;
  486. $this->logger->addInfo(count($data)." records found.");
  487. $expirationDateOnCreate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserCreation)."years"));
  488. $expirationDateOnUpdate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserUpdate)."years"));
  489. $counter = 1;
  490. foreach ($data as $row) {
  491. $row = $this->cleanUserRow($row);
  492. $user_id = UserManager::get_user_id_from_original_id(
  493. $row['extra_'.$this->extraFieldIdNameList['user']],
  494. $this->extraFieldIdNameList['user']
  495. );
  496. $userInfo = array();
  497. $userInfoByOfficialCode = null;
  498. if (!empty($user_id)) {
  499. $userInfo = api_get_user_info($user_id, false, true);
  500. $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
  501. }
  502. if (empty($userInfo) && empty($userInfoByOfficialCode)) {
  503. // Create user
  504. $result = UserManager::create_user(
  505. $row['firstname'],
  506. $row['lastname'],
  507. STUDENT,
  508. $row['email'],
  509. $row['username'],
  510. $row['password'],
  511. $row['official_code'],
  512. $language, //$row['language'],
  513. $row['phone'],
  514. null, //$row['picture'], //picture
  515. $row['auth_source'], // ?
  516. $expirationDateOnCreate, //'0000-00-00 00:00:00', //$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
  517. 1, //active
  518. 0,
  519. null, // extra
  520. null, //$encrypt_method = '',
  521. false //$send_mail = false
  522. );
  523. if ($result) {
  524. foreach ($row as $key => $value) {
  525. if (substr($key, 0, 6) === 'extra_') {
  526. //an extra field
  527. UserManager::update_extra_field_value(
  528. $result,
  529. substr($key, 6),
  530. $value
  531. );
  532. }
  533. }
  534. $this->logger->addInfo("Students - User created: ".$row['username']);
  535. } else {
  536. $this->logger->addError("Students - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
  537. $this->logger->addError(strip_tags(Display::getFlashToString()));
  538. Display::cleanFlashMessages();
  539. }
  540. } else {
  541. if (empty($userInfo)) {
  542. $this->logger->addError("Students - Can't update user :".$row['username']);
  543. continue;
  544. }
  545. if (isset($row['action']) && $row['action'] === 'delete') {
  546. // Inactive one year later
  547. $userInfo['expiration_date'] = api_get_utc_datetime(api_strtotime(time() + 365*24*60*60));
  548. }
  549. $password = $row['password']; // change password
  550. $email = $row['email']; // change email
  551. $resetPassword = 2; // allow password change
  552. // Conditions that disables the update of password and email:
  553. if (isset($this->conditions['importStudents'])) {
  554. if (isset($this->conditions['importStudents']['update']) &&
  555. isset($this->conditions['importStudents']['update']['avoid'])
  556. ) {
  557. // Blocking email update -
  558. // 1. Condition
  559. $avoidUsersWithEmail = $this->conditions['importStudents']['update']['avoid']['email'];
  560. if ($userInfo['email'] != $row['email'] && in_array($row['email'], $avoidUsersWithEmail)) {
  561. $this->logger->addInfo("Students - User email is not updated : ".$row['username']." because the avoid conditions (email).");
  562. // Do not change email keep the old email.
  563. $email = $userInfo['email'];
  564. }
  565. // 2. Condition
  566. if (!in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
  567. $email = $userInfo['email'];
  568. }
  569. // 3. Condition
  570. if (in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
  571. $email = $row['email'];
  572. }
  573. // Blocking password update
  574. /*if (isset($row['password'])) {
  575. $user = api_get_user_entity($userInfo['id']);
  576. $encoded = UserManager::encryptPassword(
  577. $row['password'],
  578. $user
  579. );
  580. if ($userInfo['password'] != $encoded &&
  581. in_array($row['password'], $avoidUsersWithPassword)
  582. ) {
  583. $this->logger->addInfo(
  584. "Students - User password is not updated: ".$row['username']." because the avoid conditions (password)."
  585. );
  586. $password = null;
  587. $resetPassword = 0; // disallow password change
  588. }
  589. }*/
  590. }
  591. }
  592. $password = null;
  593. $resetPassword = 0; // disallow password change
  594. // Update user
  595. $result = UserManager::update_user(
  596. $userInfo['user_id'],
  597. $row['firstname'], // <<-- changed
  598. $row['lastname'], // <<-- changed
  599. $row['username'], // <<-- changed
  600. $password, //$password = null,
  601. $row['auth_source'],
  602. $email,
  603. STUDENT,
  604. $userInfo['official_code'],
  605. $userInfo['phone'],
  606. $userInfo['picture_uri'],
  607. $expirationDateOnUpdate,
  608. $userInfo['active'],
  609. null, //$creator_id = null,
  610. 0, //$hr_dept_id = 0,
  611. null, // $extra = null,
  612. null, //$language = 'english',
  613. null, //$encrypt_method = '',
  614. false, //$send_email = false,
  615. $resetPassword //$reset_password = 0
  616. );
  617. if ($result) {
  618. if ($row['username'] != $userInfo['username']) {
  619. $this->logger->addInfo("Students - Username was changes from '".$userInfo['username']."' to '".$row['username']."' ");
  620. }
  621. foreach ($row as $key => $value) {
  622. if (substr($key, 0, 6) === 'extra_') {
  623. //an extra field
  624. UserManager::update_extra_field_value(
  625. $userInfo['user_id'],
  626. substr($key, 6),
  627. $value
  628. );
  629. }
  630. }
  631. $this->logger->addInfo("Students - User updated: ".$row['username']);
  632. } else {
  633. $this->logger->addError("Students - User NOT updated: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
  634. }
  635. }
  636. if (($counter % $batchSize) === 0) {
  637. $em->flush();
  638. $em->clear(); // Detaches all objects from Doctrine!
  639. $this->logger->addInfo("Detaches all objects");
  640. }
  641. $counter++;
  642. }
  643. $em->clear(); // Detaches all objects from Doctrine!
  644. }
  645. $timeEnd = microtime(true);
  646. $executionTime = round(($timeEnd - $timeStart)/60, 2);
  647. $this->logger->addInfo("Execution Time for process students: $executionTime Min");
  648. if ($moveFile) {
  649. $this->moveFile($file);
  650. }
  651. }
  652. /**
  653. * @param string $file
  654. */
  655. private function importCoursesStatic($file, $moveFile, &$teacherBackup = array(), &$groupBackup = array())
  656. {
  657. $this->importCourses($file, false, $teacherBackup, $groupBackup);
  658. }
  659. /**
  660. * @param string $file
  661. * @param bool $moveFile
  662. *
  663. * @return int
  664. */
  665. private function importCalendarStatic($file, $moveFile = true)
  666. {
  667. $this->fixCSVFile($file);
  668. $data = Import::csvToArray($file);
  669. if (!empty($data)) {
  670. $this->logger->addInfo(count($data)." records found.");
  671. $eventsToCreate = array();
  672. $errorFound = false;
  673. foreach ($data as $row) {
  674. $sessionId = null;
  675. $externalSessionId = null;
  676. if (isset($row['external_sessionID'])) {
  677. $externalSessionId = $row['external_sessionID'];
  678. $sessionId = SessionManager::getSessionIdFromOriginalId(
  679. $externalSessionId,
  680. $this->extraFieldIdNameList['session']
  681. );
  682. }
  683. $courseCode = null;
  684. if (isset($row['coursecode'])) {
  685. $courseCode = $row['coursecode'];
  686. }
  687. $courseInfo = api_get_course_info($courseCode);
  688. if (empty($courseInfo)) {
  689. $this->logger->addInfo("Course '$courseCode' does not exists");
  690. }
  691. if (empty($sessionId)) {
  692. $this->logger->addInfo("external_sessionID: ".$externalSessionId." does not exists.");
  693. }
  694. $teacherId = null;
  695. if (!empty($sessionId) && !empty($courseInfo)) {
  696. $courseIncluded = SessionManager::relation_session_course_exist(
  697. $sessionId,
  698. $courseInfo['real_id']
  699. );
  700. if ($courseIncluded == false) {
  701. $this->logger->addInfo(
  702. "Course '$courseCode' is not included in session: $sessionId"
  703. );
  704. $errorFound = true;
  705. } else {
  706. $teachers = CourseManager::get_coach_list_from_course_code(
  707. $courseInfo['code'],
  708. $sessionId
  709. );
  710. // Getting first teacher.
  711. if (!empty($teachers)) {
  712. $teacher = current($teachers);
  713. $teacherId = $teacher['user_id'];
  714. } else {
  715. $sessionInfo = api_get_session_info($sessionId);
  716. $teacherId = $sessionInfo['id_coach'];
  717. }
  718. }
  719. } else {
  720. $errorFound = true;
  721. }
  722. if (empty($teacherId)) {
  723. $errorFound = true;
  724. $this->logger->addInfo(
  725. "No teacher found in course code : '$courseCode' and session: '$sessionId'"
  726. );
  727. }
  728. $date = $row['date'];
  729. $startTime = $row['time_start'];
  730. $endTime = $row['time_end'];
  731. $title = $row['title'];
  732. $comment = $row['comment'];
  733. $color = isset($row['color']) ? $row['color'] : '';
  734. $startDateYear = substr($date, 0, 4);
  735. $startDateMonth = substr($date, 4, 2);
  736. $startDateDay = substr($date, 6, 8);
  737. $startDate = $startDateYear.'-'.$startDateMonth.'-'.$startDateDay.' '.$startTime.":00";
  738. $endDate = $startDateYear.'-'.$startDateMonth.'-'.$startDateDay.' '.$endTime.":00";
  739. if (!api_is_valid_date($startDate) || !api_is_valid_date($endDate)) {
  740. $this->logger->addInfo(
  741. "Verify your dates: '$startDate' : '$endDate' "
  742. );
  743. $errorFound = true;
  744. }
  745. // If old events do nothing.
  746. /*if (api_strtotime($startDate) < time()) {
  747. continue;
  748. }*/
  749. if ($errorFound == false) {
  750. $eventsToCreate[] = array(
  751. 'start' => $startDate,
  752. 'end' => $endDate,
  753. 'title' => $title,
  754. 'sender_id' => $teacherId,
  755. 'course_id' => $courseInfo['real_id'],
  756. 'session_id' => $sessionId,
  757. 'comment' => $comment,
  758. 'color' => $color,
  759. $this->extraFieldIdNameList['calendar_event'] => $row['external_calendar_itemID'],
  760. );
  761. }
  762. $errorFound = false;
  763. }
  764. if (empty($eventsToCreate)) {
  765. $this->logger->addInfo(
  766. "No events to add"
  767. );
  768. return 0;
  769. }
  770. $this->logger->addInfo(
  771. "Ready to insert events"
  772. );
  773. $agenda = new Agenda();
  774. $extraFieldValue = new ExtraFieldValue('calendar_event');
  775. $extraFieldName = $this->extraFieldIdNameList['calendar_event'];
  776. $externalEventId = null;
  777. $extraField = new ExtraField('calendar_event');
  778. $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable(
  779. $extraFieldName
  780. );
  781. if (empty($extraFieldInfo)) {
  782. $this->logger->addInfo(
  783. "No calendar event extra field created: $extraFieldName"
  784. );
  785. return 0;
  786. }
  787. foreach ($eventsToCreate as $event) {
  788. $update = false;
  789. $item = null;
  790. if (!isset($event[$extraFieldName])) {
  791. $this->logger->addInfo(
  792. "No external_calendar_itemID found. Skipping ..."
  793. );
  794. continue;
  795. } else {
  796. $externalEventId = $event[$extraFieldName];
  797. if (empty($externalEventId)) {
  798. $this->logger->addInfo(
  799. "external_calendar_itemID was set but empty. Skipping ..."
  800. );
  801. continue;
  802. }
  803. $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
  804. $extraFieldName,
  805. $externalEventId,
  806. false,
  807. false,
  808. false
  809. );
  810. if (!empty($item)) {
  811. $this->logger->addInfo(
  812. "Event #$externalEventId was already added. Updating ..."
  813. );
  814. $update = true;
  815. //continue;
  816. } else {
  817. $this->logger->addInfo(
  818. "Event #$externalEventId was not added. Preparing to be created ..."
  819. );
  820. }
  821. }
  822. $courseInfo = api_get_course_info_by_id($event['course_id']);
  823. $agenda->set_course($courseInfo);
  824. $agenda->setType('course');
  825. $agenda->setSessionId($event['session_id']);
  826. $agenda->setSenderId($event['sender_id']);
  827. $agenda->setIsAllowedToEdit(true);
  828. $eventComment = $event['comment'];
  829. $color = $event['color'];
  830. // To use the event comment you need
  831. // ALTER TABLE c_calendar_event ADD COLUMN comment TEXT;
  832. // add in configuration.php allow_agenda_event_comment = true
  833. if (empty($courseInfo)) {
  834. $this->logger->addInfo(
  835. "No course found for added: #".$event['course_id']." Skipping ..."
  836. );
  837. continue;
  838. }
  839. if (empty($event['sender_id'])) {
  840. $this->logger->addInfo(
  841. "No sender found: #".$event['sender_id']." Skipping ..."
  842. );
  843. continue;
  844. }
  845. $content = '';
  846. if ($update && isset($item['item_id'])) {
  847. $eventResult = $agenda->editEvent(
  848. $item['item_id'],
  849. $event['start'],
  850. $event['end'],
  851. false,
  852. $event['title'],
  853. $content,
  854. array('everyone'), // send to
  855. array(), //$attachmentArray = array(),
  856. [], //$attachmentCommentList
  857. null, //$attachmentComment = null,
  858. $eventComment,
  859. $color
  860. );
  861. if ($eventResult !== false) {
  862. $this->logger->addInfo(
  863. "Event updated: #$eventId"
  864. );
  865. } else {
  866. $this->logger->addInfo(
  867. "Error while updating event."
  868. );
  869. }
  870. } else {
  871. // New event. Create it.
  872. $eventId = $agenda->addEvent(
  873. $event['start'],
  874. $event['end'],
  875. false,
  876. $event['title'],
  877. $content,
  878. array('everyone'), // send to
  879. false, //$addAsAnnouncement = false
  880. null, // $parentEventId
  881. array(), //$attachmentArray = array(),
  882. [], //$attachmentCommentList
  883. null, //$attachmentComment = null,
  884. $eventComment,
  885. $color
  886. );
  887. if (!empty($eventId)) {
  888. $extraFieldValue->save(
  889. array(
  890. 'value' => $externalEventId,
  891. 'field_id' => $extraFieldInfo['id'],
  892. 'item_id' => $eventId
  893. )
  894. );
  895. $this->logger->addInfo(
  896. "Event added: #$eventId"
  897. );
  898. } else {
  899. $this->logger->addInfo(
  900. "Error while creating event."
  901. );
  902. }
  903. }
  904. }
  905. }
  906. if ($moveFile) {
  907. $this->moveFile($file);
  908. }
  909. }
  910. /**
  911. * @param string $file
  912. * @param bool $moveFile
  913. * @param array $teacherBackup
  914. * @param array $groupBackup
  915. */
  916. private function importCourses(
  917. $file,
  918. $moveFile = true,
  919. &$teacherBackup = array(),
  920. &$groupBackup = array()
  921. ) {
  922. $this->fixCSVFile($file);
  923. $data = Import::csvToArray($file);
  924. if (!empty($data)) {
  925. $this->logger->addInfo(count($data)." records found.");
  926. foreach ($data as $row) {
  927. $row = $this->cleanCourseRow($row);
  928. $courseId = CourseManager::get_course_id_from_original_id(
  929. $row['extra_'.$this->extraFieldIdNameList['course']],
  930. $this->extraFieldIdNameList['course']
  931. );
  932. $courseInfo = api_get_course_info_by_id($courseId);
  933. if (empty($courseInfo)) {
  934. // Create
  935. $params = array();
  936. $params['title'] = $row['title'];
  937. $params['exemplary_content'] = false;
  938. $params['wanted_code'] = $row['course_code'];
  939. $params['course_category'] = $row['course_category'];
  940. $params['course_language'] = $row['language'];
  941. $params['teachers'] = $row['teachers'];
  942. $courseInfo = CourseManager::create_course(
  943. $params,
  944. $this->defaultAdminId
  945. );
  946. if (!empty($courseInfo)) {
  947. CourseManager::update_course_extra_field_value(
  948. $courseInfo['code'],
  949. 'external_course_id',
  950. $row['extra_'.$this->extraFieldIdNameList['course']]
  951. );
  952. $this->logger->addInfo("Courses - Course created ".$courseInfo['code']);
  953. } else {
  954. $this->logger->addError("Courses - Can't create course:".$row['title']);
  955. }
  956. } else {
  957. // Update
  958. $params = array(
  959. 'title' => $row['title'],
  960. 'category_code' => $row['course_category']
  961. );
  962. $result = CourseManager::update_attributes(
  963. $courseInfo['real_id'],
  964. $params
  965. );
  966. $addTeacherToSession = isset($courseInfo['add_teachers_to_sessions_courses']) && !empty($courseInfo['add_teachers_to_sessions_courses']) ? true : false;
  967. $teachers = $row['teachers'];
  968. if (!is_array($teachers)) {
  969. $teachers = array($teachers);
  970. }
  971. if ($addTeacherToSession) {
  972. CourseManager::updateTeachers(
  973. $courseInfo,
  974. $row['teachers'],
  975. false,
  976. true,
  977. false,
  978. $teacherBackup
  979. );
  980. } else {
  981. CourseManager::updateTeachers(
  982. $courseInfo,
  983. $row['teachers'],
  984. true,
  985. false,
  986. false,
  987. $teacherBackup
  988. );
  989. }
  990. foreach ($teachers as $teacherId) {
  991. if (isset($groupBackup['tutor'][$teacherId]) &&
  992. isset($groupBackup['tutor'][$teacherId][$courseInfo['code']])
  993. ) {
  994. foreach ($groupBackup['tutor'][$teacherId][$courseInfo['code']] as $data) {
  995. GroupManager::subscribe_tutors(
  996. array($teacherId),
  997. $data['group_id'],
  998. $data['c_id']
  999. );
  1000. }
  1001. }
  1002. if (isset($groupBackup['user'][$teacherId]) &&
  1003. isset($groupBackup['user'][$teacherId][$courseInfo['code']]) &&
  1004. !empty($groupBackup['user'][$teacherId][$courseInfo['code']])
  1005. ) {
  1006. foreach ($groupBackup['user'][$teacherId][$courseInfo['code']] as $data) {
  1007. GroupManager::subscribe_users(
  1008. array($teacherId),
  1009. $data['group_id'],
  1010. $data['c_id']
  1011. );
  1012. }
  1013. }
  1014. }
  1015. if ($result) {
  1016. $this->logger->addInfo("Courses - Course updated ".$courseInfo['code']);
  1017. } else {
  1018. $this->logger->addError("Courses - Course NOT updated ".$courseInfo['code']);
  1019. }
  1020. }
  1021. }
  1022. }
  1023. if ($moveFile) {
  1024. $this->moveFile($file);
  1025. }
  1026. }
  1027. /**
  1028. * Parse filename: encora_subsessionsextid-static_31082016.csv
  1029. * @param string $file
  1030. */
  1031. private function importSubscribeUserToCourseSessionExtStatic($file)
  1032. {
  1033. $data = Import::csv_reader($file);
  1034. if (!empty($data)) {
  1035. $this->logger->addInfo(count($data)." records found.");
  1036. $userIdList = [];
  1037. foreach ($data as $row) {
  1038. $chamiloUserName = $row['UserName'];
  1039. $chamiloCourseCode = $row['CourseCode'];
  1040. $externalSessionId = $row['ExtSessionID'];
  1041. $status = $row['Status'];
  1042. $chamiloSessionId = null;
  1043. if (!empty($externalSessionId)) {
  1044. $chamiloSessionId = SessionManager::getSessionIdFromOriginalId(
  1045. $externalSessionId,
  1046. $this->extraFieldIdNameList['session']
  1047. );
  1048. }
  1049. $sessionInfo = api_get_session_info($chamiloSessionId);
  1050. if (empty($sessionInfo)) {
  1051. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  1052. continue;
  1053. }
  1054. $courseInfo = api_get_course_info($chamiloCourseCode);
  1055. if (empty($courseInfo)) {
  1056. $this->logger->addError('Course does not exists: '.$courseInfo);
  1057. continue;
  1058. }
  1059. $userId = UserManager::get_user_id_from_username($chamiloUserName);
  1060. if (empty($userId)) {
  1061. $this->logger->addError('User does not exists: '.$chamiloUserName);
  1062. continue;
  1063. }
  1064. switch ($status) {
  1065. case 'student':
  1066. SessionManager::subscribe_users_to_session_course(
  1067. array($userId),
  1068. $chamiloSessionId,
  1069. $courseInfo['code']
  1070. );
  1071. break;
  1072. case 'teacher':
  1073. SessionManager::set_coach_to_course_session(
  1074. $userId,
  1075. $chamiloSessionId,
  1076. $courseInfo['code']
  1077. );
  1078. break;
  1079. case 'drh':
  1080. $removeAllSessionsFromUser = true;
  1081. if (in_array($userId, $userIdList)) {
  1082. $removeAllSessionsFromUser = false;
  1083. } else {
  1084. $userIdList[] = $userId;
  1085. }
  1086. $userInfo = api_get_user_info($userId);
  1087. SessionManager::subscribeSessionsToDrh(
  1088. $userInfo,
  1089. [$chamiloSessionId],
  1090. false,
  1091. $removeAllSessionsFromUser
  1092. );
  1093. break;
  1094. }
  1095. $this->logger->addError(
  1096. "User '$chamiloUserName' was added as '$status' to Session: #$chamiloSessionId - Course: ".$courseInfo['code']
  1097. );
  1098. }
  1099. }
  1100. }
  1101. /**
  1102. * @param string $file
  1103. */
  1104. private function importUnsubSessionsExtIdStatic($file)
  1105. {
  1106. $data = Import::csv_reader($file);
  1107. if (!empty($data)) {
  1108. $this->logger->addInfo(count($data)." records found.");
  1109. foreach ($data as $row) {
  1110. $chamiloUserName = $row['UserName'];
  1111. $chamiloCourseCode = $row['CourseCode'];
  1112. $externalSessionId = $row['ExtSessionID'];
  1113. $dateStop = $row['DateStop'];
  1114. $chamiloSessionId = null;
  1115. if (!empty($externalSessionId)) {
  1116. $chamiloSessionId = SessionManager::getSessionIdFromOriginalId(
  1117. $externalSessionId,
  1118. $this->extraFieldIdNameList['session']
  1119. );
  1120. }
  1121. $sessionInfo = api_get_session_info($chamiloSessionId);
  1122. if (empty($sessionInfo)) {
  1123. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  1124. continue;
  1125. }
  1126. $courseInfo = api_get_course_info($chamiloCourseCode);
  1127. if (empty($courseInfo)) {
  1128. $this->logger->addError('Course does not exists: '.$courseInfo);
  1129. continue;
  1130. }
  1131. $userId = UserManager::get_user_id_from_username($chamiloUserName);
  1132. if (empty($userId)) {
  1133. $this->logger->addError('User does not exists: '.$chamiloUserName);
  1134. continue;
  1135. }
  1136. SessionManager::removeUsersFromCourseSession(
  1137. array($userId),
  1138. $chamiloSessionId,
  1139. $courseInfo
  1140. );
  1141. $this->logger->addError(
  1142. "User '$chamiloUserName' was remove from Session: #$chamiloSessionId - Course: " . $courseInfo['code']
  1143. );
  1144. }
  1145. }
  1146. }
  1147. /**
  1148. *
  1149. * @param string $file
  1150. */
  1151. private function importSessionsExtIdStatic($file)
  1152. {
  1153. $data = Import::csv_reader($file);
  1154. if (!empty($data)) {
  1155. $this->logger->addInfo(count($data)." records found.");
  1156. foreach ($data as $row) {
  1157. $chamiloUserName = $row['UserName'];
  1158. $chamiloCourseCode = $row['CourseCode'];
  1159. $externalSessionId = $row['ExtSessionID'];
  1160. $type = $row['Type'];
  1161. $chamiloSessionId = null;
  1162. if (!empty($externalSessionId)) {
  1163. $chamiloSessionId = SessionManager::getSessionIdFromOriginalId(
  1164. $externalSessionId,
  1165. $this->extraFieldIdNameList['session']
  1166. );
  1167. }
  1168. $sessionInfo = api_get_session_info($chamiloSessionId);
  1169. if (empty($sessionInfo)) {
  1170. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  1171. continue;
  1172. }
  1173. $courseInfo = api_get_course_info($chamiloCourseCode);
  1174. if (empty($courseInfo)) {
  1175. $this->logger->addError('Course does not exists: '.$courseInfo);
  1176. continue;
  1177. }
  1178. $userId = UserManager::get_user_id_from_username($chamiloUserName);
  1179. if (empty($userId)) {
  1180. $this->logger->addError('User does not exists: '.$chamiloUserName);
  1181. continue;
  1182. }
  1183. switch ($type) {
  1184. case 'student':
  1185. SessionManager::subscribe_users_to_session_course(
  1186. array($userId),
  1187. $chamiloSessionId,
  1188. $courseInfo['code'],
  1189. null,
  1190. false
  1191. );
  1192. break;
  1193. case 'teacher':
  1194. SessionManager::set_coach_to_course_session(
  1195. $userId,
  1196. $chamiloSessionId,
  1197. $courseInfo['code']
  1198. );
  1199. break;
  1200. }
  1201. $this->logger->addError(
  1202. "User '$chamiloUserName' with status $type was added to session: #$chamiloSessionId - Course: " . $courseInfo['code']
  1203. );
  1204. }
  1205. }
  1206. }
  1207. /**
  1208. * Updates the session synchronize with the csv file.
  1209. * @param string $file
  1210. */
  1211. private function importSessionsStatic($file)
  1212. {
  1213. $content = file($file);
  1214. $sessions = array();
  1215. $tag_names = array();
  1216. foreach ($content as $key => $enreg) {
  1217. $enreg = explode(';', trim($enreg));
  1218. if ($key) {
  1219. foreach ($tag_names as $tag_key => $tag_name) {
  1220. if (isset($enreg[$tag_key])) {
  1221. $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
  1222. }
  1223. }
  1224. } else {
  1225. foreach ($enreg as $tag_name) {
  1226. $tag_names[] = api_preg_replace(
  1227. '/[^a-zA-Z0-9_\-]/',
  1228. '',
  1229. $tag_name
  1230. );
  1231. }
  1232. if (!in_array('SessionName', $tag_names) || !in_array(
  1233. 'DateStart',
  1234. $tag_names
  1235. ) || !in_array('DateEnd', $tag_names)
  1236. ) {
  1237. $error_message = get_lang('NoNeededData');
  1238. break;
  1239. }
  1240. }
  1241. }
  1242. if (!empty($sessions)) {
  1243. // Looping the sessions.
  1244. foreach ($sessions as $session) {
  1245. if (!empty($session['SessionID'])) {
  1246. $sessionId = SessionManager::getSessionIdFromOriginalId(
  1247. $session['SessionID'],
  1248. $this->extraFieldIdNameList['session']
  1249. );
  1250. $coachUserName = isset($session['Coach']) ? $session['Coach'] : null;
  1251. $categoryId = isset($session['category_id']) ? $session['category_id'] : null;
  1252. // 2014-06-30
  1253. $dateStart = explode('/', $session['DateStart']);
  1254. $dateEnd = explode('/', $session['DateEnd']);
  1255. $visibility = $this->defaultSessionVisibility;
  1256. $coachId = null;
  1257. if (!empty($coachUserName)) {
  1258. $coachInfo = api_get_user_info_from_username($coachUserName);
  1259. $coachId = $coachInfo['user_id'];
  1260. }
  1261. $dateStart = $dateStart[0].'-'.$dateStart[1].'-'.$dateStart[2].' 00:00:00';
  1262. $dateEnd = $dateEnd[0].'-'.$dateEnd[1].'-'.$dateEnd[2].' 23:59:59';
  1263. $date = new \DateTime($dateStart);
  1264. $interval = new DateInterval('P'.$this->daysCoachAccessBeforeBeginning.'D');
  1265. $date->sub($interval);
  1266. $coachBefore = $date->format('Y-m-d h:i');
  1267. $date = new \DateTime($dateStart);
  1268. $interval = new DateInterval('P'.$this->daysCoachAccessAfterBeginning.'D');
  1269. $date->add($interval);
  1270. $coachAfter = $date->format('Y-m-d h:i');
  1271. $dateStart = api_get_utc_datetime($dateStart);
  1272. $dateEnd = api_get_utc_datetime($dateEnd);
  1273. $coachBefore = api_get_utc_datetime($coachBefore);
  1274. $coachAfter = api_get_utc_datetime($coachAfter);
  1275. if (empty($sessionId)) {
  1276. $result = SessionManager::create_session(
  1277. $session['SessionName'],
  1278. $dateStart,
  1279. $dateEnd,
  1280. $dateStart,
  1281. $dateEnd,
  1282. $coachBefore,
  1283. $coachAfter,
  1284. $coachId,
  1285. $categoryId,
  1286. $visibility
  1287. );
  1288. if (is_numeric($result)) {
  1289. $sessionId = $result;
  1290. $this->logger->addInfo("Session #$sessionId created: ".$session['SessionName']);
  1291. SessionManager::update_session_extra_field_value(
  1292. $sessionId,
  1293. $this->extraFieldIdNameList['session'],
  1294. $session['SessionID']
  1295. );
  1296. } else {
  1297. $this->logger->addInfo("Failed creating session: ".$session['SessionName']);
  1298. }
  1299. } else {
  1300. $sessionInfo = api_get_session_info($sessionId);
  1301. $accessBefore = null;
  1302. $accessAfter = null;
  1303. if (empty($sessionInfo['nb_days_access_before_beginning']) ||
  1304. (!empty($sessionInfo['nb_days_access_before_beginning']) &&
  1305. $sessionInfo['nb_days_access_before_beginning'] < $this->daysCoachAccessBeforeBeginning)
  1306. ) {
  1307. $accessBefore = $coachBefore;
  1308. }
  1309. $accessAfter = null;
  1310. if (empty($sessionInfo['nb_days_access_after_end']) ||
  1311. (!empty($sessionInfo['nb_days_access_after_end']) &&
  1312. $sessionInfo['nb_days_access_after_end'] < $this->daysCoachAccessAfterBeginning)
  1313. ) {
  1314. $accessAfter = $coachAfter;
  1315. }
  1316. $showDescription = isset($sessionInfo['show_description']) ? $sessionInfo['show_description'] : 1;
  1317. $result = SessionManager::edit_session(
  1318. $sessionId,
  1319. $session['SessionName'],
  1320. $dateStart,
  1321. $dateEnd,
  1322. $dateStart,
  1323. $dateEnd,
  1324. $accessBefore,
  1325. $accessAfter,
  1326. $coachId,
  1327. $categoryId,
  1328. $visibility,
  1329. null, //$description
  1330. $showDescription
  1331. );
  1332. if (is_numeric($result)) {
  1333. $this->logger->addInfo("Session #$sessionId updated: ".$session['SessionName']);
  1334. $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
  1335. $params = array(
  1336. 'description' => $session['SessionDescription']
  1337. );
  1338. Database::update(
  1339. $tbl_session,
  1340. $params,
  1341. array('id = ?' => $sessionId)
  1342. );
  1343. }
  1344. }
  1345. if (!empty($sessionId)) {
  1346. // Courses
  1347. $courses = explode('|', $session['Courses']);
  1348. $courseList = [];
  1349. $courseListWithCoach = [];
  1350. foreach ($courses as $course) {
  1351. $courseArray = bracketsToArray($course);
  1352. $courseCode = $courseArray[0];
  1353. if (CourseManager::course_exists($courseCode)) {
  1354. $courseInfo = api_get_course_info($courseCode);
  1355. $courseList[] = $courseInfo['real_id'];
  1356. $courseCoaches = isset($courseArray[1]) ? $courseArray[1] : null;
  1357. $courseCoaches = explode(',', $courseCoaches);
  1358. // Extracting students
  1359. $courseUsers = isset($courseArray[2]) ? $courseArray[2] : null;
  1360. $courseUsers = explode(',', $courseUsers);
  1361. $courseListWithCoach[] = [
  1362. 'course_info' => $courseInfo,
  1363. 'coaches' => $courseCoaches,
  1364. 'course_users' => $courseUsers
  1365. ];
  1366. }
  1367. }
  1368. SessionManager::add_courses_to_session(
  1369. $sessionId,
  1370. $courseList,
  1371. true
  1372. );
  1373. $this->logger->addInfo("Session #$sessionId: Courses added: '".implode(', ', $courseList)."'");
  1374. // Coaches
  1375. if (empty($courseListWithCoach)) {
  1376. $this->logger->addInfo("No users/coaches to update");
  1377. continue;
  1378. }
  1379. foreach ($courseListWithCoach as $courseData) {
  1380. $courseInfo = $courseData['course_info'];
  1381. $courseCode = $courseInfo['code'];
  1382. $courseId = $courseInfo['real_id'];
  1383. $courseCoaches = $courseData['coaches'];
  1384. $courseUsers = $courseData['course_users'];
  1385. if (!empty($courseCoaches)) {
  1386. $coachList = array();
  1387. foreach ($courseCoaches as $courseCoach) {
  1388. $courseCoachId = UserManager::get_user_id_from_username(
  1389. $courseCoach
  1390. );
  1391. if ($courseCoachId !== false) {
  1392. // Just insert new coaches
  1393. $coachList[] = $courseCoachId;
  1394. }
  1395. }
  1396. $this->logger->addInfo("Session #$sessionId: course '$courseCode' coaches added: '".implode(', ', $coachList)."'");
  1397. SessionManager::updateCoaches(
  1398. $sessionId,
  1399. $courseId,
  1400. $coachList,
  1401. true
  1402. );
  1403. } else {
  1404. $this->logger->addInfo("No coaches added");
  1405. }
  1406. // Students
  1407. if (!empty($courseUsers)) {
  1408. $userList = array();
  1409. foreach ($courseUsers as $username) {
  1410. $userInfo = api_get_user_info_from_username(trim($username));
  1411. if (!empty($userInfo)) {
  1412. $userList[] = $userInfo['user_id'];
  1413. }
  1414. }
  1415. $this->logger->addInfo("Session #$sessionId: course '$courseCode': Students added '".implode(', ', $userList)."'");
  1416. SessionManager::subscribe_users_to_session_course(
  1417. $userList,
  1418. $sessionId,
  1419. $courseCode,
  1420. SESSION_VISIBLE_READ_ONLY,
  1421. true
  1422. );
  1423. } else {
  1424. $this->logger->addInfo("No users to register.");
  1425. }
  1426. }
  1427. } else {
  1428. $this->logger->addInfo(
  1429. 'SessionID not found in system.'
  1430. );
  1431. }
  1432. } else {
  1433. $this->logger->addInfo('SessionID does not exists');
  1434. }
  1435. }
  1436. } else {
  1437. $this->logger->addInfo($error_message);
  1438. }
  1439. }
  1440. /**
  1441. * @param string $file
  1442. * @param bool $moveFile
  1443. * @param array $teacherBackup
  1444. * @param array $groupBackup
  1445. */
  1446. private function importSessions(
  1447. $file,
  1448. $moveFile = true,
  1449. &$teacherBackup = array(),
  1450. &$groupBackup = array()
  1451. ) {
  1452. $avoid = null;
  1453. if (isset($this->conditions['importSessions']) &&
  1454. isset($this->conditions['importSessions']['update'])
  1455. ) {
  1456. $avoid = $this->conditions['importSessions']['update'];
  1457. }
  1458. $result = SessionManager::importCSV(
  1459. $file,
  1460. true,
  1461. $this->defaultAdminId,
  1462. $this->logger,
  1463. array('SessionID' => 'extra_'.$this->extraFieldIdNameList['session']),
  1464. $this->extraFieldIdNameList['session'],
  1465. $this->daysCoachAccessBeforeBeginning,
  1466. $this->daysCoachAccessAfterBeginning,
  1467. $this->defaultSessionVisibility,
  1468. $avoid,
  1469. false, // deleteUsersNotInList
  1470. false, // updateCourseCoaches
  1471. true, // sessionWithCoursesModifier
  1472. true, //$addOriginalCourseTeachersAsCourseSessionCoaches
  1473. true, //$removeAllTeachersFromCourse
  1474. 1, // $showDescription,
  1475. $teacherBackup,
  1476. $groupBackup
  1477. );
  1478. if (!empty($result['error_message'])) {
  1479. $this->logger->addError($result['error_message']);
  1480. }
  1481. $this->logger->addInfo("Sessions - Sessions parsed: ".$result['session_counter']);
  1482. if ($moveFile) {
  1483. $this->moveFile($file);
  1484. }
  1485. }
  1486. /**
  1487. * @param string $file
  1488. */
  1489. private function importSubscribeStatic($file)
  1490. {
  1491. $data = Import::csv_reader($file);
  1492. if (!empty($data)) {
  1493. $this->logger->addInfo(count($data) . " records found.");
  1494. foreach ($data as $row) {
  1495. $chamiloUserName = $row['UserName'];
  1496. $chamiloCourseCode = $row['CourseCode'];
  1497. $chamiloSessionId = $row['SessionID'];
  1498. $type = $row['Type'];
  1499. $sessionInfo = api_get_session_info($chamiloSessionId);
  1500. if (empty($sessionInfo)) {
  1501. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  1502. continue;
  1503. }
  1504. $courseInfo = api_get_course_info($chamiloCourseCode);
  1505. if (empty($courseInfo)) {
  1506. $this->logger->addError('Course does not exists: '.$courseInfo);
  1507. continue;
  1508. }
  1509. $userId = UserManager::get_user_id_from_username($chamiloUserName);
  1510. if (empty($userId)) {
  1511. $this->logger->addError('User does not exists: '.$chamiloUserName);
  1512. continue;
  1513. }
  1514. switch ($type) {
  1515. case 'student':
  1516. SessionManager::subscribe_users_to_session_course(
  1517. array($userId),
  1518. $chamiloSessionId,
  1519. $courseInfo['code'],
  1520. null,
  1521. false
  1522. );
  1523. break;
  1524. case 'teacher':
  1525. SessionManager::set_coach_to_course_session(
  1526. $userId,
  1527. $chamiloSessionId,
  1528. $courseInfo['real_id']
  1529. );
  1530. break;
  1531. }
  1532. $this->logger->addError(
  1533. "User '$chamiloUserName' with status $type was added to session: #$chamiloSessionId - Course: " . $courseInfo['code']
  1534. );
  1535. }
  1536. }
  1537. }
  1538. /**
  1539. * @param $file
  1540. * @param bool $moveFile
  1541. */
  1542. private function importSubscribeUserToCourse($file, $moveFile = false)
  1543. {
  1544. $data = Import::csv_reader($file);
  1545. if (!empty($data)) {
  1546. $this->logger->addInfo(count($data) . " records found.");
  1547. foreach ($data as $row) {
  1548. $chamiloUserName = $row['UserName'];
  1549. $chamiloCourseCode = $row['CourseCode'];
  1550. $status = $row['Status'];
  1551. $courseInfo = api_get_course_info($chamiloCourseCode);
  1552. if (empty($courseInfo)) {
  1553. $this->logger->addError(
  1554. 'Course does not exists: '.$chamiloCourseCode
  1555. );
  1556. continue;
  1557. }
  1558. $userId = UserManager::get_user_id_from_username(
  1559. $chamiloUserName
  1560. );
  1561. if (empty($userId)) {
  1562. $this->logger->addError(
  1563. 'User does not exists: '.$chamiloUserName
  1564. );
  1565. continue;
  1566. }
  1567. CourseManager::subscribe_user(
  1568. $userId,
  1569. $courseInfo['code'],
  1570. $status
  1571. );
  1572. $this->logger->addInfo(
  1573. "User $userId added to course $chamiloCourseCode as $status"
  1574. );
  1575. }
  1576. }
  1577. }
  1578. /**
  1579. * @param string $file
  1580. */
  1581. private function importUnsubscribeStatic(
  1582. $file,
  1583. $moveFile = false,
  1584. &$teacherBackup = array(),
  1585. &$groupBackup = array()
  1586. ) {
  1587. $data = Import::csv_reader($file);
  1588. if (!empty($data)) {
  1589. $this->logger->addInfo(count($data)." records found.");
  1590. foreach ($data as $row) {
  1591. $chamiloUserName = $row['UserName'];
  1592. $chamiloCourseCode = $row['CourseCode'];
  1593. $chamiloSessionId = $row['SessionID'];
  1594. $sessionInfo = api_get_session_info($chamiloSessionId);
  1595. if (empty($sessionInfo)) {
  1596. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  1597. continue;
  1598. }
  1599. $courseInfo = api_get_course_info($chamiloCourseCode);
  1600. if (empty($courseInfo)) {
  1601. $this->logger->addError('Course does not exists: '.$courseInfo);
  1602. continue;
  1603. }
  1604. $userId = UserManager::get_user_id_from_username($chamiloUserName);
  1605. if (empty($userId)) {
  1606. $this->logger->addError('User does not exists: '.$chamiloUserName);
  1607. continue;
  1608. }
  1609. $sql = "SELECT * FROM ".Database::get_main_table(TABLE_MAIN_COURSE_USER)."
  1610. WHERE
  1611. user_id = ".$userId." AND
  1612. course_code = '".$courseInfo['code']."'
  1613. ";
  1614. $result = Database::query($sql);
  1615. $userCourseData = Database::fetch_array($result, 'ASSOC');
  1616. $teacherBackup[$userId][$courseInfo['code']] = $userCourseData;
  1617. $sql = "SELECT * FROM ".Database::get_course_table(
  1618. TABLE_GROUP_USER
  1619. )."
  1620. WHERE
  1621. user_id = ".$userId." AND
  1622. c_id = '".$courseInfo['real_id']."'
  1623. ";
  1624. $result = Database::query($sql);
  1625. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  1626. $groupBackup['user'][$userId][$courseInfo['code']][$groupData['group_id']] = $groupData;
  1627. }
  1628. $sql = "SELECT * FROM ".Database::get_course_table(TABLE_GROUP_TUTOR)."
  1629. WHERE
  1630. user_id = ".$userId." AND
  1631. c_id = '".$courseInfo['real_id']."'
  1632. ";
  1633. $result = Database::query($sql);
  1634. while ($groupData = Database::fetch_array($result, 'ASSOC')) {
  1635. $groupBackup['tutor'][$userId][$courseInfo['code']][$groupData['group_id']] = $groupData;
  1636. }
  1637. CourseManager::unsubscribe_user(
  1638. $userId,
  1639. $courseInfo['code'],
  1640. $chamiloSessionId
  1641. );
  1642. $this->logger->addError(
  1643. "User '$chamiloUserName' was removed from session: #$chamiloSessionId, Course: ".$courseInfo['code']
  1644. );
  1645. }
  1646. }
  1647. }
  1648. /**
  1649. * Dump database tables
  1650. */
  1651. private function dumpDatabaseTables()
  1652. {
  1653. echo 'Dumping tables'.PHP_EOL;
  1654. // User
  1655. $table = Database::get_main_table(TABLE_MAIN_USER);
  1656. $tableAdmin = Database::get_main_table(TABLE_MAIN_ADMIN);
  1657. $sql = "DELETE FROM $table
  1658. WHERE user_id not in (select user_id from $tableAdmin) and status <> ".ANONYMOUS;
  1659. Database::query($sql);
  1660. echo $sql.PHP_EOL;
  1661. // Truncate tables
  1662. $truncateTables = array(
  1663. Database::get_main_table(TABLE_MAIN_COURSE),
  1664. Database::get_main_table(TABLE_MAIN_COURSE_USER),
  1665. Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE),
  1666. Database::get_main_table(TABLE_MAIN_CATEGORY),
  1667. Database::get_main_table(TABLE_MAIN_COURSE_MODULE),
  1668. Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER),
  1669. Database::get_main_table(TABLE_MAIN_SESSION),
  1670. Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY),
  1671. Database::get_main_table(TABLE_MAIN_SESSION_COURSE),
  1672. Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER),
  1673. Database::get_main_table(TABLE_MAIN_SESSION_USER),
  1674. Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION),
  1675. Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES),
  1676. Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES),
  1677. Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES),
  1678. Database::get_main_table(TABLE_MAIN_USER_FIELD),
  1679. Database::get_main_table(TABLE_MAIN_USER_FIELD_OPTIONS),
  1680. Database::get_main_table(TABLE_MAIN_COURSE_FIELD),
  1681. Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES),
  1682. Database::get_main_table(TABLE_MAIN_SESSION_FIELD),
  1683. Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES),
  1684. Database::get_course_table(TABLE_AGENDA),
  1685. Database::get_course_table(TABLE_AGENDA_ATTACHMENT),
  1686. Database::get_course_table(TABLE_AGENDA_REPEAT),
  1687. Database::get_course_table(TABLE_AGENDA_REPEAT_NOT),
  1688. Database::get_main_table(TABLE_PERSONAL_AGENDA),
  1689. Database::get_main_table(TABLE_PERSONAL_AGENDA_REPEAT_NOT),
  1690. Database::get_main_table(TABLE_PERSONAL_AGENDA_REPEAT),
  1691. Database::get_main_table(TABLE_MAIN_CALENDAR_EVENT_VALUES),
  1692. Database::get_main_table(TABLE_STATISTIC_TRACK_E_LASTACCESS),
  1693. Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS),
  1694. Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN),
  1695. Database::get_main_table(TABLE_STATISTIC_TRACK_E_DOWNLOADS),
  1696. Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES),
  1697. Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT),
  1698. Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING),
  1699. Database::get_main_table(TABLE_STATISTIC_TRACK_E_DEFAULT),
  1700. Database::get_main_table(TABLE_STATISTIC_TRACK_E_UPLOADS),
  1701. Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTSPOT),
  1702. Database::get_main_table(TABLE_STATISTIC_TRACK_E_ITEM_PROPERTY),
  1703. Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY),
  1704. Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION),
  1705. Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG),
  1706. Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT),
  1707. Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT_LOG),
  1708. Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK),
  1709. Database::get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY),
  1710. Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE),
  1711. Database::get_course_table(TABLE_STUDENT_PUBLICATION),
  1712. Database::get_course_table(TABLE_QUIZ_QUESTION),
  1713. Database::get_course_table(TABLE_QUIZ_TEST),
  1714. Database::get_course_table(TABLE_QUIZ_ORDER),
  1715. Database::get_course_table(TABLE_QUIZ_ANSWER),
  1716. Database::get_course_table(TABLE_QUIZ_TEST_QUESTION),
  1717. Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION),
  1718. Database::get_course_table(TABLE_QUIZ_QUESTION_CATEGORY),
  1719. Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY),
  1720. Database::get_course_table(TABLE_LP_MAIN),
  1721. Database::get_course_table(TABLE_LP_ITEM),
  1722. Database::get_course_table(TABLE_LP_VIEW),
  1723. Database::get_course_table(TABLE_LP_ITEM_VIEW),
  1724. Database::get_course_table(TABLE_DOCUMENT),
  1725. Database::get_course_table(TABLE_ITEM_PROPERTY),
  1726. Database::get_course_table(TABLE_TOOL_LIST),
  1727. Database::get_course_table(TABLE_TOOL_INTRO),
  1728. Database::get_course_table(TABLE_COURSE_SETTING),
  1729. Database::get_course_table(TABLE_SURVEY),
  1730. Database::get_course_table(TABLE_SURVEY_QUESTION),
  1731. Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION),
  1732. Database::get_course_table(TABLE_SURVEY_INVITATION),
  1733. Database::get_course_table(TABLE_SURVEY_ANSWER),
  1734. Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP),
  1735. Database::get_course_table(TABLE_SURVEY_REPORT),
  1736. Database::get_course_table(TABLE_GLOSSARY),
  1737. Database::get_course_table(TABLE_LINK),
  1738. Database::get_course_table(TABLE_LINK_CATEGORY),
  1739. Database::get_course_table(TABLE_GROUP),
  1740. Database::get_course_table(TABLE_GROUP_USER),
  1741. Database::get_course_table(TABLE_GROUP_TUTOR),
  1742. Database::get_course_table(TABLE_GROUP_CATEGORY),
  1743. Database::get_course_table(TABLE_DROPBOX_CATEGORY),
  1744. Database::get_course_table(TABLE_DROPBOX_FEEDBACK),
  1745. Database::get_course_table(TABLE_DROPBOX_POST),
  1746. Database::get_course_table(TABLE_DROPBOX_FILE),
  1747. Database::get_course_table(TABLE_DROPBOX_PERSON)
  1748. );
  1749. foreach ($truncateTables as $table) {
  1750. $sql = "TRUNCATE $table";
  1751. Database::query($sql);
  1752. echo $sql.PHP_EOL;
  1753. }
  1754. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1755. $sql = "DELETE FROM $table WHERE tool = 'calendar_event'";
  1756. Database::query($sql);
  1757. echo $sql.PHP_EOL;
  1758. }
  1759. /**
  1760. * If csv file ends with '"' character then a '";' is added
  1761. * @param string $file
  1762. */
  1763. private function fixCSVFile($file)
  1764. {
  1765. /*$f = fopen($file, 'r+');
  1766. $cursor = -1;
  1767. fseek($f, $cursor, SEEK_END);
  1768. $char = fgetc($f);
  1769. while ($char === "\n" || $char === "\r") {
  1770. fseek($f, $cursor--, SEEK_END);
  1771. $char = fgetc($f);
  1772. }
  1773. if ($char === "\"") {
  1774. fseek($f, -1, SEEK_CUR);
  1775. fwrite($f, '";');
  1776. }*/
  1777. }
  1778. }
  1779. use Monolog\Logger;
  1780. use Monolog\Handler\StreamHandler;
  1781. use Monolog\Handler\NativeMailerHandler;
  1782. use Monolog\Handler\RotatingFileHandler;
  1783. use Monolog\Handler\BufferHandler;
  1784. $logger = new Logger('cron');
  1785. $emails = api_get_configuration_value('cron_notification_mails');
  1786. $minLevel = Logger::DEBUG;
  1787. if (!is_array($emails)) {
  1788. $emails = array($emails);
  1789. }
  1790. $subject = "Cron main/cron/import_csv.php ".date('Y-m-d h:i:s');
  1791. $from = api_get_setting('admin.administrator_email');
  1792. /*
  1793. if (!empty($emails)) {
  1794. foreach ($emails as $email) {
  1795. $stream = new NativeMailerHandler($email, $subject, $from, $minLevel);
  1796. $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
  1797. }
  1798. }*/
  1799. $stream = new StreamHandler(api_get_path(SYS_ARCHIVE_PATH).'import_csv.log', $minLevel);
  1800. $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
  1801. $logger->pushHandler(new RotatingFileHandler('import_csv', 5, $minLevel));
  1802. $cronImportCSVConditions = api_get_configuration_value('cron_import_csv_conditions');
  1803. echo 'See the error log here: '.api_get_path(SYS_ARCHIVE_PATH).'import_csv.log'."\n";
  1804. $import = new ImportCsv($logger, $cronImportCSVConditions);
  1805. $import->defaultAdminId = api_get_configuration_value('default_admin_user_id_for_cron');
  1806. // @todo in production disable the dump option
  1807. $dump = false;
  1808. if (isset($argv[1]) && $argv[1] = '--dump') {
  1809. $dump = true;
  1810. }
  1811. $disableDump = api_get_configuration_value('import_csv_disable_dump');
  1812. if (isset($disableDump) && $disableDump == true) {
  1813. $import->setDumpValues(false);
  1814. } else {
  1815. $import->setDumpValues($dump);
  1816. }
  1817. // Do not moves the files to treated
  1818. $importTest = api_get_configuration_value('import_csv_test');
  1819. if (!empty($importTest) && $importTest) {
  1820. $import->test = $importTest;
  1821. } else {
  1822. $import->test = true;
  1823. }
  1824. $timeStart = microtime(true);
  1825. $import->run();
  1826. $timeEnd = microtime(true);
  1827. $executionTime = round(($timeEnd - $timeStart) / 60, 2);
  1828. $logger->addInfo("Total execution Time $executionTime Min");
  1829. $fixPermissions = api_get_configuration_value('import_csv_fix_permissions');
  1830. if ($fixPermissions == true) {
  1831. $command = "sudo find ".api_get_path(SYS_COURSE_PATH)." -type d -exec chmod 777 {} \; ";
  1832. echo "Executing: ".$command.PHP_EOL;
  1833. system($command);
  1834. $command = "sudo find ".api_get_path(SYS_CODE_PATH)."upload/users -type d -exec chmod 777 {} \;";
  1835. echo "Executing: ".$command.PHP_EOL;
  1836. system($command);
  1837. }