import_csv.php 29 KB

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