import_csv.php 77 KB

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