migrateto17.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. #!/usr/bin/env php
  2. <?php
  3. echo "SabreDAV migrate script for version 1.7\n";
  4. if ($argc < 2) {
  5. echo <<<HELLO
  6. This script help you migrate from a pre-1.7 database to 1.7 and later\n
  7. Both the 'calendarobjects' and 'calendars' tables will be upgraded.
  8. If you do not have this table, or don't use the default PDO CalDAV backend
  9. it's pointless to run this script.
  10. Keep in mind that some processing will be done on every single record of this
  11. table and in addition, ALTER TABLE commands will be executed.
  12. If you have a large calendarobjects table, this may mean that this process
  13. takes a while.
  14. Usage:
  15. php {$argv[0]} [pdo-dsn] [username] [password]
  16. For example:
  17. php {$argv[0]} "mysql:host=localhost;dbname=sabredav" root password
  18. php {$argv[0]} sqlite:data/sabredav.db
  19. HELLO;
  20. exit();
  21. }
  22. // There's a bunch of places where the autoloader could be, so we'll try all of
  23. // them.
  24. $paths = [
  25. __DIR__ . '/../vendor/autoload.php',
  26. __DIR__ . '/../../../autoload.php',
  27. ];
  28. foreach ($paths as $path) {
  29. if (file_exists($path)) {
  30. include $path;
  31. break;
  32. }
  33. }
  34. $dsn = $argv[1];
  35. $user = isset($argv[2]) ? $argv[2] : null;
  36. $pass = isset($argv[3]) ? $argv[3] : null;
  37. echo "Connecting to database: " . $dsn . "\n";
  38. $pdo = new PDO($dsn, $user, $pass);
  39. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  40. $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  41. echo "Validating existing table layout\n";
  42. // The only cross-db way to do this, is to just fetch a single record.
  43. $row = $pdo->query("SELECT * FROM calendarobjects LIMIT 1")->fetch();
  44. if (!$row) {
  45. echo "Error: This database did not have any records in the calendarobjects table, you should just recreate the table.\n";
  46. exit(-1);
  47. }
  48. $requiredFields = [
  49. 'id',
  50. 'calendardata',
  51. 'uri',
  52. 'calendarid',
  53. 'lastmodified',
  54. ];
  55. foreach ($requiredFields as $requiredField) {
  56. if (!array_key_exists($requiredField, $row)) {
  57. echo "Error: The current 'calendarobjects' table was missing a field we expected to exist.\n";
  58. echo "For safety reasons, this process is stopped.\n";
  59. exit(-1);
  60. }
  61. }
  62. $fields17 = [
  63. 'etag',
  64. 'size',
  65. 'componenttype',
  66. 'firstoccurence',
  67. 'lastoccurence',
  68. ];
  69. $found = 0;
  70. foreach ($fields17 as $field) {
  71. if (array_key_exists($field, $row)) {
  72. $found++;
  73. }
  74. }
  75. if ($found === 0) {
  76. echo "The database had the 1.6 schema. Table will now be altered.\n";
  77. echo "This may take some time for large tables\n";
  78. switch ($pdo->getAttribute(PDO::ATTR_DRIVER_NAME)) {
  79. case 'mysql' :
  80. $pdo->exec(<<<SQL
  81. ALTER TABLE calendarobjects
  82. ADD etag VARCHAR(32),
  83. ADD size INT(11) UNSIGNED,
  84. ADD componenttype VARCHAR(8),
  85. ADD firstoccurence INT(11) UNSIGNED,
  86. ADD lastoccurence INT(11) UNSIGNED
  87. SQL
  88. );
  89. break;
  90. case 'sqlite' :
  91. $pdo->exec('ALTER TABLE calendarobjects ADD etag text');
  92. $pdo->exec('ALTER TABLE calendarobjects ADD size integer');
  93. $pdo->exec('ALTER TABLE calendarobjects ADD componenttype TEXT');
  94. $pdo->exec('ALTER TABLE calendarobjects ADD firstoccurence integer');
  95. $pdo->exec('ALTER TABLE calendarobjects ADD lastoccurence integer');
  96. break;
  97. default :
  98. die('This upgrade script does not support this driver (' . $pdo->getAttribute(PDO::ATTR_DRIVER_NAME) . ")\n");
  99. }
  100. echo "Database schema upgraded.\n";
  101. } elseif ($found === 5) {
  102. echo "Database already had the 1.7 schema\n";
  103. } else {
  104. echo "The database had $found out of 5 from the changes for 1.7. This is scary and unusual, so we have to abort.\n";
  105. echo "You can manually try to upgrade the schema, and then run this script again.\n";
  106. exit(-1);
  107. }
  108. echo "Now, we need to parse every record and pull out some information.\n";
  109. $result = $pdo->query('SELECT id, calendardata FROM calendarobjects');
  110. $stmt = $pdo->prepare('UPDATE calendarobjects SET etag = ?, size = ?, componenttype = ?, firstoccurence = ?, lastoccurence = ? WHERE id = ?');
  111. echo "Total records found: " . $result->rowCount() . "\n";
  112. $done = 0;
  113. $total = $result->rowCount();
  114. while ($row = $result->fetch()) {
  115. try {
  116. $newData = getDenormalizedData($row['calendardata']);
  117. } catch (Exception $e) {
  118. echo "===\nException caught will trying to parser calendarobject.\n";
  119. echo "Error message: " . $e->getMessage() . "\n";
  120. echo "Record id: " . $row['id'] . "\n";
  121. echo "This record is ignored, you should inspect it to see if there's anything wrong.\n===\n";
  122. continue;
  123. }
  124. $stmt->execute([
  125. $newData['etag'],
  126. $newData['size'],
  127. $newData['componentType'],
  128. $newData['firstOccurence'],
  129. $newData['lastOccurence'],
  130. $row['id'],
  131. ]);
  132. $done++;
  133. if ($done % 500 === 0) {
  134. echo "Completed: $done / $total\n";
  135. }
  136. }
  137. echo "Completed: $done / $total\n";
  138. echo "Checking the calendars table needs changes.\n";
  139. $row = $pdo->query("SELECT * FROM calendars LIMIT 1")->fetch();
  140. if (array_key_exists('transparent', $row)) {
  141. echo "The calendars table is already up to date\n";
  142. } else {
  143. echo "Adding the 'transparent' field to the calendars table\n";
  144. switch ($pdo->getAttribute(PDO::ATTR_DRIVER_NAME)) {
  145. case 'mysql' :
  146. $pdo->exec("ALTER TABLE calendars ADD transparent TINYINT(1) NOT NULL DEFAULT '0'");
  147. break;
  148. case 'sqlite' :
  149. $pdo->exec("ALTER TABLE calendars ADD transparent bool");
  150. break;
  151. default :
  152. die('This upgrade script does not support this driver (' . $pdo->getAttribute(PDO::ATTR_DRIVER_NAME) . ")\n");
  153. }
  154. }
  155. echo "Process completed!\n";
  156. /**
  157. * Parses some information from calendar objects, used for optimized
  158. * calendar-queries.
  159. *
  160. * Blantently copied from Sabre\CalDAV\Backend\PDO
  161. *
  162. * Returns an array with the following keys:
  163. * * etag
  164. * * size
  165. * * componentType
  166. * * firstOccurence
  167. * * lastOccurence
  168. *
  169. * @param string $calendarData
  170. * @return array
  171. */
  172. function getDenormalizedData($calendarData) {
  173. $vObject = \Sabre\VObject\Reader::read($calendarData);
  174. $componentType = null;
  175. $component = null;
  176. $firstOccurence = null;
  177. $lastOccurence = null;
  178. foreach ($vObject->getComponents() as $component) {
  179. if ($component->name !== 'VTIMEZONE') {
  180. $componentType = $component->name;
  181. break;
  182. }
  183. }
  184. if (!$componentType) {
  185. throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
  186. }
  187. if ($componentType === 'VEVENT') {
  188. $firstOccurence = $component->DTSTART->getDateTime()->getTimeStamp();
  189. // Finding the last occurence is a bit harder
  190. if (!isset($component->RRULE)) {
  191. if (isset($component->DTEND)) {
  192. $lastOccurence = $component->DTEND->getDateTime()->getTimeStamp();
  193. } elseif (isset($component->DURATION)) {
  194. $endDate = clone $component->DTSTART->getDateTime();
  195. $endDate->add(\Sabre\VObject\DateTimeParser::parse($component->DURATION->value));
  196. $lastOccurence = $endDate->getTimeStamp();
  197. } elseif (!$component->DTSTART->hasTime()) {
  198. $endDate = clone $component->DTSTART->getDateTime();
  199. $endDate->modify('+1 day');
  200. $lastOccurence = $endDate->getTimeStamp();
  201. } else {
  202. $lastOccurence = $firstOccurence;
  203. }
  204. } else {
  205. $it = new \Sabre\VObject\Recur\EventIterator($vObject, (string)$component->UID);
  206. $maxDate = new DateTime(\Sabre\CalDAV\Backend\PDO::MAX_DATE);
  207. if ($it->isInfinite()) {
  208. $lastOccurence = $maxDate->getTimeStamp();
  209. } else {
  210. $end = $it->getDtEnd();
  211. while ($it->valid() && $end < $maxDate) {
  212. $end = $it->getDtEnd();
  213. $it->next();
  214. }
  215. $lastOccurence = $end->getTimeStamp();
  216. }
  217. }
  218. }
  219. return [
  220. 'etag' => md5($calendarData),
  221. 'size' => strlen($calendarData),
  222. 'componentType' => $componentType,
  223. 'firstOccurence' => $firstOccurence,
  224. 'lastOccurence' => $lastOccurence,
  225. ];
  226. }