import_csv.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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. require_once api_get_path(LIBRARY_PATH).'log.class.php';
  11. /**
  12. * Class ImportCsv
  13. */
  14. class ImportCsv
  15. {
  16. private $logger;
  17. private $dumpValues;
  18. public $test;
  19. public $defaultLanguage = 'dutch';
  20. public $extraFieldIdNameList = array(
  21. 'session' => 'external_session_id',
  22. 'course' => 'external_course_id',
  23. 'user' => 'external_user_id',
  24. );
  25. public $defaultAdminId = 1;
  26. public $defaultSessionVisibility = 1;
  27. /**
  28. * When creating a user the expiration date is set to registration date + this value
  29. * @var int number of years
  30. */
  31. public $expirationDateInUserCreation = 1;
  32. /**
  33. * When updating a user the expiration date is set to update date + this value
  34. * @var int number of years
  35. */
  36. public $expirationDateInUserUpdate = 1;
  37. public $daysCoachAccessBeforeBeginning = 30;
  38. public $daysCoachAccessAfterBeginning = 60;
  39. public $conditions;
  40. /**
  41. * @param Logger $logger
  42. */
  43. public function __construct($logger, $conditions)
  44. {
  45. $this->logger = $logger;
  46. $this->conditions = $conditions;
  47. }
  48. /**
  49. * @param bool $dump
  50. */
  51. function setDumpValues($dump)
  52. {
  53. $this->dumpValues = $dump;
  54. }
  55. /**
  56. * @return mixed
  57. */
  58. function getDumpValues()
  59. {
  60. return $this->dumpValues;
  61. }
  62. /**
  63. * Runs the import process
  64. */
  65. public function run()
  66. {
  67. $path = api_get_path(SYS_CODE_PATH).'cron/incoming/';
  68. if (!is_dir($path)) {
  69. echo "The folder! $path does not exits";
  70. exit;
  71. }
  72. if ($this->getDumpValues()) {
  73. $this->dumpDatabaseTables();
  74. }
  75. echo "Starting with reading the files: ".PHP_EOL.PHP_EOL;
  76. $files = scandir($path);
  77. $fileToProcess = array();
  78. if (!empty($files)) {
  79. foreach ($files as $file) {
  80. $fileInfo = pathinfo($file);
  81. if ($fileInfo['extension'] == 'csv') {
  82. // teachers_yyyymmdd.csv, courses_yyyymmdd.csv, students_yyyymmdd.csv and sessions_yyyymmdd.csv
  83. $parts = explode('_', $fileInfo['filename']);
  84. $preMethod = ucwords($parts[1]);
  85. $preMethod = str_replace('-static', 'Static', $preMethod);
  86. $method = 'import'.$preMethod;
  87. if (method_exists($this, $method)) {
  88. $fileToProcess[$parts[1]][] = array(
  89. 'method' => $method,
  90. 'file' => $path.$fileInfo['basename']
  91. );
  92. //$this->$method($path.$fileInfo['basename']);
  93. } else {
  94. echo "Error - This file '$file' can't be processed.".PHP_EOL;
  95. echo "Trying to call $method".PHP_EOL;
  96. echo "The file have to has this format:".PHP_EOL;
  97. echo "prefix_students_ddmmyyyy.csv, prefix_teachers_ddmmyyyy.csv, prefix_courses_ddmmyyyy.csv, prefix_sessions_ddmmyyyy.csv ".PHP_EOL;
  98. exit;
  99. }
  100. }
  101. }
  102. if (empty($fileToProcess)) {
  103. echo 'Error - no files to process.';
  104. exit;
  105. }
  106. $sections = array('students', 'teachers', 'courses', 'sessions', 'unsubscribe-static');
  107. $this->prepareImport();
  108. foreach ($sections as $section) {
  109. $this->logger->addInfo("-- Import $section --");
  110. if (isset($fileToProcess[$section]) && !empty($fileToProcess[$section])) {
  111. $files = $fileToProcess[$section];
  112. foreach ($files as $fileInfo) {
  113. $method = $fileInfo['method'];
  114. $file = $fileInfo['file'];
  115. echo 'Reading file: '.$file.PHP_EOL;
  116. $this->logger->addInfo("Reading file: $file");
  117. $this->$method($file);
  118. }
  119. }
  120. }
  121. }
  122. }
  123. /**
  124. * Prepares extra fields before the import
  125. */
  126. private function prepareImport()
  127. {
  128. // Create user extra field: extra_external_user_id
  129. UserManager::create_extra_field($this->extraFieldIdNameList['user'], 1, 'External user id', null);
  130. // Create course extra field: extra_external_course_id
  131. CourseManager::create_course_extra_field($this->extraFieldIdNameList['course'], 1, 'External course id');
  132. // Create session extra field extra_external_session_id
  133. SessionManager::create_session_extra_field($this->extraFieldIdNameList['session'], 1, 'External session id');
  134. }
  135. /**
  136. * @param string $file
  137. */
  138. private function moveFile($file)
  139. {
  140. $moved = str_replace('incoming', 'treated', $file);
  141. if ($this->test) {
  142. $result = 1;
  143. } else {
  144. $result = rename($file, $moved);
  145. }
  146. if ($result) {
  147. $this->logger->addInfo("Moving file to the treated folder: $file");
  148. } else {
  149. $this->logger->addError("Error - Cant move file to the treated folder: $file");
  150. }
  151. }
  152. /**
  153. * @param array $row
  154. *
  155. * @return array
  156. */
  157. private function cleanUserRow($row)
  158. {
  159. $row['lastname'] = $row['LastName'];
  160. $row['firstname'] = $row['FirstName'];
  161. $row['email'] = $row['Email'];
  162. $row['username'] = $row['UserName'];
  163. $row['password'] = $row['Password'];
  164. $row['auth_source'] = $row['AuthSource'];
  165. $row['official_code'] = $row['OfficialCode'];
  166. $row['phone'] = $row['PhoneNumber'];
  167. if (isset($row['StudentID'])) {
  168. $row['extra_'.$this->extraFieldIdNameList['user']] = $row['StudentID'];
  169. }
  170. if (isset($row['TeacherID'])) {
  171. $row['extra_'.$this->extraFieldIdNameList['user']] = $row['TeacherID'];
  172. }
  173. //$row['lastname'] = Status
  174. return $row;
  175. }
  176. /**
  177. * @param array $row
  178. * @return array
  179. */
  180. private function cleanCourseRow($row)
  181. {
  182. $row['title'] = $row['Title'];
  183. $row['course_code'] = $row['Code'];
  184. $row['course_category'] = $row['CourseCategory'];
  185. $row['email'] = $row['Teacher'];
  186. $row['language'] = $row['Language'];
  187. $row['teachers'] = array();
  188. if (isset($row['Teacher']) && !empty($row['Teacher'])) {
  189. $teachers = explode(',', $row['Teacher']);
  190. if (!empty($teachers)) {
  191. foreach ($teachers as $teacherUserName) {
  192. $teacherUserName = trim($teacherUserName);
  193. $userInfo = api_get_user_info_from_username($teacherUserName);
  194. if (!empty($userInfo)) {
  195. $row['teachers'][] = $userInfo['user_id'];
  196. }
  197. }
  198. }
  199. }
  200. if (isset($row['CourseID'])) {
  201. $row['extra_'.$this->extraFieldIdNameList['course']] = $row['CourseID'];
  202. }
  203. return $row;
  204. }
  205. /**
  206. * File to import
  207. * @param string $file
  208. */
  209. private function importTeachers($file)
  210. {
  211. $data = Import::csv_to_array($file);
  212. /* Unique identifier: official-code username.
  213. Email address and password should never get updated. *ok
  214. The only fields that I can think of that should update if the data changes in the csv file are FirstName and LastName. *ok
  215. A slight edit of these fields should be taken into account. ???
  216. Adding teachers is no problem, but deleting them shouldn’t be automated, but we should get a log of “to delete teachers”.
  217. We’ll handle that manually if applicable.
  218. No delete!
  219. */
  220. $language = $this->defaultLanguage;
  221. if (!empty($data)) {
  222. $this->logger->addInfo(count($data)." records found.");
  223. foreach ($data as $row) {
  224. $row = $this->cleanUserRow($row);
  225. $user_id = UserManager::get_user_id_from_original_id($row['extra_'.$this->extraFieldIdNameList['user']], $this->extraFieldIdNameList['user']);
  226. $userInfo = array();
  227. $userInfoByOfficialCode = null;
  228. if (!empty($user_id)) {
  229. $userInfo = api_get_user_info($user_id);
  230. //$userInfo = api_get_user_info_from_username($row['username']);
  231. $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
  232. }
  233. $expirationDate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserCreation)."years"));
  234. if (empty($userInfo) && empty($userInfoByOfficialCode)) {
  235. // Create user
  236. $userId = UserManager::create_user(
  237. $row['firstname'],
  238. $row['lastname'],
  239. COURSEMANAGER,
  240. $row['email'],
  241. $row['username'],
  242. $row['password'],
  243. $row['official_code'],
  244. $language, //$row['language'],
  245. $row['phone'],
  246. null, //$row['picture'], //picture
  247. PLATFORM_AUTH_SOURCE, // ?
  248. $expirationDate, //'0000-00-00 00:00:00', //$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
  249. 1, //active
  250. 0,
  251. null, // extra
  252. null, //$encrypt_method = '',
  253. false //$send_mail = false
  254. );
  255. if ($userId) {
  256. foreach ($row as $key => $value) {
  257. if (substr($key, 0, 6) == 'extra_') { //an extra field
  258. UserManager::update_extra_field_value($userId, substr($key, 6), $value);
  259. }
  260. }
  261. $this->logger->addInfo("Teachers - User created: ".$row['username']);
  262. } else {
  263. $this->logger->addError("Teachers - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
  264. }
  265. } else {
  266. if (empty($userInfo)) {
  267. $this->logger->addError("Teachers - Can't update user :".$row['username']);
  268. continue;
  269. }
  270. $expirationDate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserUpdate)."years"));
  271. // Update user
  272. $result = UserManager::update_user(
  273. $userInfo['user_id'],
  274. $row['firstname'], // <<-- changed
  275. $row['lastname'], // <<-- changed
  276. $userInfo['username'],
  277. null, //$password = null,
  278. $auth_source = null,
  279. $userInfo['email'],
  280. COURSEMANAGER,
  281. $userInfo['official_code'],
  282. $userInfo['phone'],
  283. $userInfo['picture_uri'],
  284. $expirationDate,
  285. $userInfo['active'],
  286. null, //$creator_id = null,
  287. 0, //$hr_dept_id = 0,
  288. null, // $extra = null,
  289. null, //$language = 'english',
  290. null, //$encrypt_method = '',
  291. false, //$send_email = false,
  292. 0 //$reset_password = 0
  293. );
  294. if ($result) {
  295. foreach ($row as $key => $value) {
  296. if (substr($key, 0, 6) == 'extra_') { //an extra field
  297. UserManager::update_extra_field_value($userInfo['user_id'], substr($key, 6), $value);
  298. }
  299. }
  300. $this->logger->addInfo("Teachers - User updated: ".$row['username']);
  301. } else {
  302. $this->logger->addError("Teachers - User not updated: ".$row['username']);
  303. }
  304. }
  305. }
  306. }
  307. $this->moveFile($file);
  308. }
  309. /**
  310. * @param string $file
  311. */
  312. private function importStudents($file)
  313. {
  314. $data = Import::csv_to_array($file);
  315. /*
  316. * Another users import.
  317. Unique identifier: official code and username . ok
  318. Password should never get updated. ok
  319. If an update should need to occur (because it changed in the .csv), we’ll want that logged. We will handle this manually in that case.
  320. All other fields should be updateable, though passwords should of course not get updated. ok
  321. If a user gets deleted (not there anymore),
  322. He should be set inactive one year after the current date. So I presume you’ll just update the expiration date. We want to grant access to courses up to a year after deletion.
  323. */
  324. if (!empty($data)) {
  325. $language = $this->defaultLanguage;
  326. $this->logger->addInfo(count($data)." records found.");
  327. foreach ($data as $row) {
  328. $row = $this->cleanUserRow($row);
  329. //$userInfo = api_get_user_info_from_username($row['username']);
  330. $user_id = UserManager::get_user_id_from_original_id($row['extra_'.$this->extraFieldIdNameList['user']], $this->extraFieldIdNameList['user']);
  331. $userInfo = array();
  332. $userInfoByOfficialCode = null;
  333. if (!empty($user_id)) {
  334. $userInfo = api_get_user_info($user_id);
  335. $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
  336. }
  337. $expirationDate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserCreation)."years"));
  338. if (empty($userInfo) && empty($userInfoByOfficialCode)) {
  339. // Create user
  340. $result = UserManager::create_user(
  341. $row['firstname'],
  342. $row['lastname'],
  343. STUDENT,
  344. $row['email'],
  345. $row['username'],
  346. $row['password'],
  347. $row['official_code'],
  348. $language, //$row['language'],
  349. $row['phone'],
  350. null, //$row['picture'], //picture
  351. PLATFORM_AUTH_SOURCE, // ?
  352. $expirationDate, //'0000-00-00 00:00:00', //$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
  353. 1, //active
  354. 0,
  355. null, // extra
  356. null, //$encrypt_method = '',
  357. false //$send_mail = false
  358. );
  359. if ($result) {
  360. foreach ($row as $key => $value) {
  361. if (substr($key, 0, 6) == 'extra_') { //an extra field
  362. UserManager::update_extra_field_value($result, substr($key, 6), $value);
  363. }
  364. }
  365. $this->logger->addInfo("Students - User created: ".$row['username']);
  366. } else {
  367. $this->logger->addError("Students - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
  368. }
  369. } else {
  370. if (empty($userInfo)) {
  371. $this->logger->addError("Students - Can't update user :".$row['username']);
  372. continue;
  373. }
  374. if ($row['action'] == 'delete') {
  375. // Inactive one year later
  376. $userInfo['expiration_date'] = api_get_utc_datetime(api_strtotime(time() + 365*24*60*60));
  377. }
  378. $password = $row['password']; // change password
  379. $email = $row['email']; // change email
  380. $resetPassword = 2; // allow password change
  381. // Conditions that disables the update of password and email:
  382. if (isset($this->conditions['importStudents'])) {
  383. if (isset($this->conditions['importStudents']['update']) && isset($this->conditions['importStudents']['update']['avoid'])) {
  384. // Blocking email update -
  385. // 1. Condition
  386. $avoidUsersWithEmail = $this->conditions['importStudents']['update']['avoid']['email'];
  387. if ($userInfo['email'] != $row['email'] && in_array($row['email'], $avoidUsersWithEmail)) {
  388. $this->logger->addInfo("Students - User email is not updated : ".$row['username']." because the avoid conditions (email).");
  389. // Do not change email keep the old email.
  390. $email = $userInfo['email'];
  391. }
  392. // 2. Condition
  393. if (!in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
  394. $email = $userInfo['email'];
  395. }
  396. // 3. Condition
  397. if (in_array($userInfo['email'], $avoidUsersWithEmail) && !in_array($row['email'], $avoidUsersWithEmail)) {
  398. $email = $row['email'];
  399. }
  400. // Blocking password update
  401. $avoidUsersWithPassword = $this->conditions['importStudents']['update']['avoid']['password'];
  402. if ($userInfo['password'] != api_get_encrypted_password($row['password']) && in_array($row['password'], $avoidUsersWithPassword)) {
  403. $this->logger->addInfo("Students - User password is not updated: ".$row['username']." because the avoid conditions (password).");
  404. $password = null;
  405. $resetPassword = 0; // disallow password change
  406. }
  407. }
  408. }
  409. $expirationDate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserUpdate)."years"));
  410. // Update user
  411. $result = UserManager::update_user(
  412. $userInfo['user_id'],
  413. $row['firstname'], // <<-- changed
  414. $row['lastname'], // <<-- changed
  415. $row['username'], // <<-- changed
  416. $password, //$password = null,
  417. $auth_source = null,
  418. $email,
  419. STUDENT,
  420. $userInfo['official_code'],
  421. $userInfo['phone'],
  422. $userInfo['picture_uri'],
  423. $expirationDate,
  424. $userInfo['active'],
  425. null, //$creator_id = null,
  426. 0, //$hr_dept_id = 0,
  427. null, // $extra = null,
  428. null, //$language = 'english',
  429. null, //$encrypt_method = '',
  430. false, //$send_email = false,
  431. $resetPassword //$reset_password = 0
  432. );
  433. if ($result) {
  434. if ($row['username'] != $userInfo['username']) {
  435. $this->logger->addInfo("Students - Username was changes from '".$userInfo['username']."' to '".$row['username']."' ");
  436. }
  437. foreach ($row as $key => $value) {
  438. if (substr($key, 0, 6) == 'extra_') { //an extra field
  439. UserManager::update_extra_field_value($userInfo['user_id'], substr($key, 6), $value);
  440. }
  441. }
  442. $this->logger->addInfo("Students - User updated: ".$row['username']);
  443. } else {
  444. $this->logger->addError("Students - User NOT updated: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
  445. }
  446. }
  447. }
  448. }
  449. $this->moveFile($file);
  450. }
  451. /**
  452. * @param string $file
  453. */
  454. private function importCourses($file)
  455. {
  456. $data = Import::csv_to_array($file);
  457. //$language = $this->defaultLanguage;
  458. if (!empty($data)) {
  459. $this->logger->addInfo(count($data)." records found.");
  460. foreach ($data as $row) {
  461. $row = $this->cleanCourseRow($row);
  462. $courseCode = CourseManager::get_course_id_from_original_id($row['extra_'.$this->extraFieldIdNameList['course']], $this->extraFieldIdNameList['course']);
  463. $courseInfo = api_get_course_info($courseCode);
  464. if (empty($courseInfo)) {
  465. // Create
  466. $params = array();
  467. $params['title'] = $row['title'];
  468. $params['exemplary_content'] = false;
  469. $params['wanted_code'] = $row['course_code'];
  470. $params['course_category'] = $row['course_category'];
  471. $params['course_language'] = $row['language'];
  472. $params['teachers'] = $row['teachers'];
  473. $courseInfo = CourseManager::create_course($params);
  474. if (!empty($courseInfo)) {
  475. CourseManager::update_course_extra_field_value($courseInfo['code'], 'external_course_id', $row['extra_'.$this->extraFieldIdNameList['course']]);
  476. $this->logger->addInfo("Courses - Course created ".$courseInfo['code']);
  477. } else {
  478. $this->logger->addError("Courses - Can't create course:".$row['title']);
  479. }
  480. } else {
  481. // Update
  482. $params = array(
  483. 'title' => $row['title'],
  484. );
  485. $result = CourseManager::update_attributes($courseInfo['real_id'], $params);
  486. $addTeacherToSession = isset($courseInfo['add_teachers_to_sessions_courses']) && !empty($courseInfo['add_teachers_to_sessions_courses']) ? true : false;
  487. if ($addTeacherToSession) {
  488. CourseManager::updateTeachers($courseInfo['id'], $row['teachers'], false, true, false);
  489. } else {
  490. CourseManager::updateTeachers($courseInfo['id'], $row['teachers'], false, false);
  491. }
  492. if ($result) {
  493. $this->logger->addInfo("Courses - Course updated ".$courseInfo['code']);
  494. } else {
  495. $this->logger->addError("Courses - Course NOT updated ".$courseInfo['code']);
  496. }
  497. }
  498. }
  499. }
  500. $this->moveFile($file);
  501. }
  502. /**
  503. * @param string $file
  504. */
  505. private function importSessions($file)
  506. {
  507. $avoid = null;
  508. if (isset($this->conditions['importSessions']) && isset($this->conditions['importSessions']['update'])) {
  509. $avoid = $this->conditions['importSessions']['update'];
  510. }
  511. $result = SessionManager::importCSV(
  512. $file,
  513. true,
  514. $this->defaultAdminId,
  515. $this->logger,
  516. array('SessionID' => 'extra_'.$this->extraFieldIdNameList['session']),
  517. $this->extraFieldIdNameList['session'],
  518. $this->daysCoachAccessBeforeBeginning,
  519. $this->daysCoachAccessAfterBeginning,
  520. $this->defaultSessionVisibility,
  521. $avoid
  522. );
  523. if (!empty($result['error_message'])) {
  524. $this->logger->addError($result['error_message']);
  525. }
  526. $this->logger->addInfo("Sessions - Sessions parsed: ".$result['session_counter']);
  527. $this->moveFile($file);
  528. }
  529. /**
  530. * @param string $file
  531. */
  532. private function importUnsubscribeStatic($file)
  533. {
  534. $data = Import::csv_reader($file);
  535. if (!empty($data)) {
  536. $this->logger->addInfo(count($data)." records found.");
  537. foreach ($data as $row) {
  538. $chamiloUserName = $row['UserName'];
  539. $chamiloCourseCode = $row['CourseCode'];
  540. //$systemSessionId= $row['SessionID'];
  541. $chamiloSessionId = $row['SessionID'];
  542. //$sessionId = SessionManager::get_session_id_from_original_id($systemSessionId, $this->extraFieldIdNameList['session']);
  543. $sessionInfo = api_get_session_info($chamiloSessionId);
  544. if (empty($sessionInfo)) {
  545. $this->logger->addError('Session does not exists: '.$chamiloSessionId);
  546. continue;
  547. }
  548. $courseInfo = api_get_course_info($chamiloCourseCode);
  549. if (empty($courseInfo)) {
  550. $this->logger->addError('Course does not exists: '.$courseInfo);
  551. continue;
  552. }
  553. $userId = Usermanager::get_user_id_from_username($chamiloUserName);
  554. if (empty($userId)) {
  555. $this->logger->addError('User does not exists: '.$chamiloUserName);
  556. continue;
  557. }
  558. CourseManager::unsubscribe_user($userId, $courseInfo['code'], $chamiloSessionId);
  559. $this->logger->addError("User '$chamiloUserName' was removed from session: #$chamiloSessionId, Course: ".$courseInfo['code']);
  560. }
  561. }
  562. }
  563. /**
  564. * Dump database tables
  565. */
  566. private function dumpDatabaseTables()
  567. {
  568. echo 'Dumping tables'.PHP_EOL;
  569. // User
  570. $table = Database::get_main_table(TABLE_MAIN_USER);
  571. $tableAdmin = Database::get_main_table(TABLE_MAIN_ADMIN);
  572. //$sql = "DELETE FROM $table WHERE username NOT IN ('admin') AND lastname <> 'Anonymous' ";
  573. $sql = "DELETE FROM $table WHERE user_id not in (select user_id from $tableAdmin) and status <> ".ANONYMOUS;
  574. Database::query($sql);
  575. echo $sql.PHP_EOL;
  576. // Course
  577. $table = Database::get_main_table(TABLE_MAIN_COURSE);
  578. $sql = "DELETE FROM $table";
  579. Database::query($sql);
  580. echo $sql.PHP_EOL;
  581. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
  582. $sql = "DELETE FROM $table";
  583. Database::query($sql);
  584. echo $sql.PHP_EOL;
  585. $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  586. $sql = "DELETE FROM $table";
  587. Database::query($sql);
  588. echo $sql.PHP_EOL;
  589. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  590. $sql = "DELETE FROM $table";
  591. Database::query($sql);
  592. echo $sql.PHP_EOL;
  593. // Sessions
  594. $table = Database::get_main_table(TABLE_MAIN_SESSION);
  595. $sql = "DELETE FROM $table";
  596. Database::query($sql);
  597. echo $sql.PHP_EOL;
  598. $table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
  599. $sql = "DELETE FROM $table";
  600. Database::query($sql);
  601. echo $sql.PHP_EOL;
  602. $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
  603. $sql = "DELETE FROM $table";
  604. Database::query($sql);
  605. echo $sql.PHP_EOL;
  606. $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
  607. $sql = "DELETE FROM $table";
  608. Database::query($sql);
  609. echo $sql.PHP_EOL;
  610. $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
  611. $sql = "DELETE FROM $table";
  612. Database::query($sql);
  613. echo $sql.PHP_EOL;
  614. // Extra fields
  615. $table = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
  616. $sql = "DELETE FROM $table";
  617. Database::query($sql);
  618. echo $sql.PHP_EOL;
  619. $table = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
  620. $sql = "DELETE FROM $table";
  621. Database::query($sql);
  622. echo $sql.PHP_EOL;
  623. $table = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
  624. $sql = "DELETE FROM $table";
  625. Database::query($sql);
  626. echo $sql.PHP_EOL;
  627. }
  628. }
  629. use Monolog\Logger;
  630. use Monolog\Handler\StreamHandler;
  631. use Monolog\Handler\NativeMailerHandler;
  632. use Monolog\Handler\RotatingFileHandler;
  633. use Monolog\Handler\BufferHandler;
  634. $logger = new Logger('cron');
  635. $emails = isset($_configuration['cron_notification_mails']) ? $_configuration['cron_notification_mails'] : null;
  636. $minLevel = Logger::DEBUG;
  637. if (!is_array($emails)) {
  638. $emails = array($emails);
  639. }
  640. $subject = "Cron main/cron/import_csv.php ".date('Y-m-d h:i:s');
  641. $from = api_get_setting('emailAdministrator');
  642. /*
  643. if (!empty($emails)) {
  644. foreach ($emails as $email) {
  645. $stream = new NativeMailerHandler($email, $subject, $from, $minLevel);
  646. $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
  647. }
  648. }*/
  649. $stream = new StreamHandler(api_get_path(SYS_ARCHIVE_PATH).'import_csv.log', $minLevel);
  650. $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
  651. $logger->pushHandler(new RotatingFileHandler('import_csv', 5, $minLevel));
  652. $import = new ImportCsv($logger, $_configuration['cron_import_csv_conditions']);
  653. if (isset($_configuration['default_admin_user_id_for_cron'])) {
  654. $import->defaultAdminId = $_configuration['default_admin_user_id_for_cron'];
  655. }
  656. // @todo in production disable the dump option
  657. $dump = false;
  658. if (isset($argv[1]) && $argv[1] = '--dump') {
  659. $dump = true;
  660. }
  661. if (isset($_configuration['import_csv_disable_dump']) && $_configuration['import_csv_disable_dump'] == true) {
  662. $import->setDumpValues(false);
  663. } else {
  664. $import->setDumpValues($dump);
  665. }
  666. // Do not moves the files to treated
  667. if (isset($_configuration['import_csv_test'])) {
  668. $import->test = $_configuration['import_csv_test'];
  669. } else {
  670. $import->test = true;
  671. }
  672. $import->run();
  673. if (isset($_configuration['import_csv_fix_permissions']) && $_configuration['import_csv_fix_permissions'] == true) {
  674. $command = "sudo find ".api_get_path(SYS_COURSE_PATH)." -type d -exec chmod 777 {} \; ";
  675. echo "Executing: ".$command.PHP_EOL;
  676. system($command);
  677. $command = "sudo find ".api_get_path(SYS_CODE_PATH)."upload/users -type d -exec chmod 777 {} \;";
  678. echo "Executing: ".$command.PHP_EOL;
  679. system($command);
  680. }