avm99963 | 5b8dde4 | 2020-09-24 18:18:16 +0200 | [diff] [blame] | 1 | <?php |
| 2 | // add_subjects.php - A PHP script used to add subjects to the subjects list |
| 3 | // saved in the DB. |
| 4 | |
| 5 | require_once(__DIR__.'/../core.php'); |
| 6 | |
| 7 | if (php_sapi_name() != 'cli') |
| 8 | exit(); |
| 9 | |
| 10 | $subjects = []; |
| 11 | |
| 12 | if ($argc == 2 && $argv[1] == '--stdin') { |
| 13 | $stdin = file_get_contents('php://stdin'); |
| 14 | $subjects = json_decode($stdin, true); |
| 15 | } elseif ($argc == 3) { |
| 16 | $subjects[] = [ |
| 17 | 'friendly_name' => $argv[1], |
| 18 | 'calendar_name' => $argv[2] |
| 19 | ]; |
| 20 | } else { |
| 21 | echo "Usage: php add_subjects.php friendly_name calendar_name\n"; |
| 22 | echo "php add_subjects.json --stdin < subjects.json\n"; |
| 23 | exit(); |
| 24 | } |
| 25 | |
| 26 | $con->beginTransaction(); |
| 27 | |
| 28 | $query = $con->prepare('INSERT INTO subjects (friendly_name, calendar_name) VALUES (:friendly_name, :calendar_name)'); |
| 29 | foreach ($subjects as $subject) { |
avm99963 | 87a8ba2 | 2020-09-28 17:23:03 +0200 | [diff] [blame^] | 30 | if (!isset($subject['calendar_name']) || empty($subject['calendar_name'])) { |
avm99963 | 5b8dde4 | 2020-09-24 18:18:16 +0200 | [diff] [blame] | 31 | $con->rollback(); |
avm99963 | 87a8ba2 | 2020-09-28 17:23:03 +0200 | [diff] [blame^] | 32 | echo "The JSON file passed is malformed. It should be an array consisting of objects which have a non-empty 'calendar_name' property and optionally a 'friendly_name' property.\n"; |
avm99963 | 5b8dde4 | 2020-09-24 18:18:16 +0200 | [diff] [blame] | 33 | exit(); |
| 34 | } |
| 35 | |
avm99963 | 87a8ba2 | 2020-09-28 17:23:03 +0200 | [diff] [blame^] | 36 | if (!isset($subject['friendly_name']) || empty($subject['friendly_name'])) |
| 37 | $subject['friendly_name'] = $subject['calendar_name']; |
| 38 | |
| 39 | $subject['calendar_name'] = mb_strtolower($subject['calendar_name']); |
| 40 | |
avm99963 | 5b8dde4 | 2020-09-24 18:18:16 +0200 | [diff] [blame] | 41 | if (!$query->execute($subject)) { |
| 42 | echo "An error occurred while adding the subject '".$subject['friendly_name']."' to the database. This doesn't affect the other subjects.\n"; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | $con->commit(); |
| 47 | |
| 48 | echo "Success.\n"; |