You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CalDavBackend.php 88KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. * @copyright Copyright (c) 2018 Georg Ehrke
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author dartcafe <github@dartcafe.de>
  8. * @author Georg Ehrke <oc.list@georgehrke.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author nhirokinet <nhirokinet@nhiroki.net>
  13. * @author Robin Appelman <robin@icewind.nl>
  14. * @author Roeland Jago Douma <roeland@famdouma.nl>
  15. * @author Stefan Weil <sw@weilnetz.de>
  16. * @author Thomas Citharel <nextcloud@tcit.fr>
  17. * @author Thomas Müller <thomas.mueller@tmit.eu>
  18. * @author Vinicius Cubas Brand <vinicius@eita.org.br>
  19. *
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. namespace OCA\DAV\CalDAV;
  36. use DateTime;
  37. use OCA\DAV\Connector\Sabre\Principal;
  38. use OCA\DAV\DAV\Sharing\Backend;
  39. use OCA\DAV\DAV\Sharing\IShareable;
  40. use OCP\DB\QueryBuilder\IQueryBuilder;
  41. use OCP\IDBConnection;
  42. use OCP\IGroupManager;
  43. use OCP\ILogger;
  44. use OCP\IUser;
  45. use OCP\IUserManager;
  46. use OCP\Security\ISecureRandom;
  47. use Sabre\CalDAV\Backend\AbstractBackend;
  48. use Sabre\CalDAV\Backend\SchedulingSupport;
  49. use Sabre\CalDAV\Backend\SubscriptionSupport;
  50. use Sabre\CalDAV\Backend\SyncSupport;
  51. use Sabre\CalDAV\Xml\Property\ScheduleCalendarTransp;
  52. use Sabre\CalDAV\Xml\Property\SupportedCalendarComponentSet;
  53. use Sabre\DAV;
  54. use Sabre\DAV\Exception\Forbidden;
  55. use Sabre\DAV\Exception\NotFound;
  56. use Sabre\DAV\PropPatch;
  57. use Sabre\Uri;
  58. use Sabre\VObject\Component;
  59. use Sabre\VObject\Component\VCalendar;
  60. use Sabre\VObject\Component\VTimeZone;
  61. use Sabre\VObject\DateTimeParser;
  62. use Sabre\VObject\InvalidDataException;
  63. use Sabre\VObject\ParseException;
  64. use Sabre\VObject\Property;
  65. use Sabre\VObject\Reader;
  66. use Sabre\VObject\Recur\EventIterator;
  67. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  68. use Symfony\Component\EventDispatcher\GenericEvent;
  69. /**
  70. * Class CalDavBackend
  71. *
  72. * Code is heavily inspired by https://github.com/fruux/sabre-dav/blob/master/lib/CalDAV/Backend/PDO.php
  73. *
  74. * @package OCA\DAV\CalDAV
  75. */
  76. class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
  77. const CALENDAR_TYPE_CALENDAR = 0;
  78. const CALENDAR_TYPE_SUBSCRIPTION = 1;
  79. const PERSONAL_CALENDAR_URI = 'personal';
  80. const PERSONAL_CALENDAR_NAME = 'Personal';
  81. const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
  82. const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
  83. /**
  84. * We need to specify a max date, because we need to stop *somewhere*
  85. *
  86. * On 32 bit system the maximum for a signed integer is 2147483647, so
  87. * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
  88. * in 2038-01-19 to avoid problems when the date is converted
  89. * to a unix timestamp.
  90. */
  91. const MAX_DATE = '2038-01-01';
  92. const ACCESS_PUBLIC = 4;
  93. const CLASSIFICATION_PUBLIC = 0;
  94. const CLASSIFICATION_PRIVATE = 1;
  95. const CLASSIFICATION_CONFIDENTIAL = 2;
  96. /**
  97. * List of CalDAV properties, and how they map to database field names
  98. * Add your own properties by simply adding on to this array.
  99. *
  100. * Note that only string-based properties are supported here.
  101. *
  102. * @var array
  103. */
  104. public $propertyMap = [
  105. '{DAV:}displayname' => 'displayname',
  106. '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
  107. '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone',
  108. '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
  109. '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
  110. ];
  111. /**
  112. * List of subscription properties, and how they map to database field names.
  113. *
  114. * @var array
  115. */
  116. public $subscriptionPropertyMap = [
  117. '{DAV:}displayname' => 'displayname',
  118. '{http://apple.com/ns/ical/}refreshrate' => 'refreshrate',
  119. '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
  120. '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
  121. '{http://calendarserver.org/ns/}subscribed-strip-todos' => 'striptodos',
  122. '{http://calendarserver.org/ns/}subscribed-strip-alarms' => 'stripalarms',
  123. '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
  124. ];
  125. /** @var array properties to index */
  126. public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
  127. 'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
  128. 'ORGANIZER'];
  129. /** @var array parameters to index */
  130. public static $indexParameters = [
  131. 'ATTENDEE' => ['CN'],
  132. 'ORGANIZER' => ['CN'],
  133. ];
  134. /**
  135. * @var string[] Map of uid => display name
  136. */
  137. protected $userDisplayNames;
  138. /** @var IDBConnection */
  139. private $db;
  140. /** @var Backend */
  141. private $calendarSharingBackend;
  142. /** @var Principal */
  143. private $principalBackend;
  144. /** @var IUserManager */
  145. private $userManager;
  146. /** @var ISecureRandom */
  147. private $random;
  148. /** @var ILogger */
  149. private $logger;
  150. /** @var EventDispatcherInterface */
  151. private $dispatcher;
  152. /** @var bool */
  153. private $legacyEndpoint;
  154. /** @var string */
  155. private $dbObjectPropertiesTable = 'calendarobjects_props';
  156. /**
  157. * CalDavBackend constructor.
  158. *
  159. * @param IDBConnection $db
  160. * @param Principal $principalBackend
  161. * @param IUserManager $userManager
  162. * @param IGroupManager $groupManager
  163. * @param ISecureRandom $random
  164. * @param ILogger $logger
  165. * @param EventDispatcherInterface $dispatcher
  166. * @param bool $legacyEndpoint
  167. */
  168. public function __construct(IDBConnection $db,
  169. Principal $principalBackend,
  170. IUserManager $userManager,
  171. IGroupManager $groupManager,
  172. ISecureRandom $random,
  173. ILogger $logger,
  174. EventDispatcherInterface $dispatcher,
  175. bool $legacyEndpoint = false) {
  176. $this->db = $db;
  177. $this->principalBackend = $principalBackend;
  178. $this->userManager = $userManager;
  179. $this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
  180. $this->random = $random;
  181. $this->logger = $logger;
  182. $this->dispatcher = $dispatcher;
  183. $this->legacyEndpoint = $legacyEndpoint;
  184. }
  185. /**
  186. * Return the number of calendars for a principal
  187. *
  188. * By default this excludes the automatically generated birthday calendar
  189. *
  190. * @param $principalUri
  191. * @param bool $excludeBirthday
  192. * @return int
  193. */
  194. public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
  195. $principalUri = $this->convertPrincipal($principalUri, true);
  196. $query = $this->db->getQueryBuilder();
  197. $query->select($query->func()->count('*'))
  198. ->from('calendars')
  199. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  200. if ($excludeBirthday) {
  201. $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
  202. }
  203. return (int)$query->execute()->fetchColumn();
  204. }
  205. /**
  206. * Returns a list of calendars for a principal.
  207. *
  208. * Every project is an array with the following keys:
  209. * * id, a unique id that will be used by other functions to modify the
  210. * calendar. This can be the same as the uri or a database key.
  211. * * uri, which the basename of the uri with which the calendar is
  212. * accessed.
  213. * * principaluri. The owner of the calendar. Almost always the same as
  214. * principalUri passed to this method.
  215. *
  216. * Furthermore it can contain webdav properties in clark notation. A very
  217. * common one is '{DAV:}displayname'.
  218. *
  219. * Many clients also require:
  220. * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
  221. * For this property, you can just return an instance of
  222. * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
  223. *
  224. * If you return {http://sabredav.org/ns}read-only and set the value to 1,
  225. * ACL will automatically be put in read-only mode.
  226. *
  227. * @param string $principalUri
  228. * @return array
  229. */
  230. function getCalendarsForUser($principalUri) {
  231. $principalUriOriginal = $principalUri;
  232. $principalUri = $this->convertPrincipal($principalUri, true);
  233. $fields = array_values($this->propertyMap);
  234. $fields[] = 'id';
  235. $fields[] = 'uri';
  236. $fields[] = 'synctoken';
  237. $fields[] = 'components';
  238. $fields[] = 'principaluri';
  239. $fields[] = 'transparent';
  240. // Making fields a comma-delimited list
  241. $query = $this->db->getQueryBuilder();
  242. $query->select($fields)->from('calendars')
  243. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  244. ->orderBy('calendarorder', 'ASC');
  245. $stmt = $query->execute();
  246. $calendars = [];
  247. while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  248. $components = [];
  249. if ($row['components']) {
  250. $components = explode(',',$row['components']);
  251. }
  252. $calendar = [
  253. 'id' => $row['id'],
  254. 'uri' => $row['uri'],
  255. 'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  256. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  257. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  258. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  259. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
  260. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
  261. ];
  262. foreach($this->propertyMap as $xmlName=>$dbName) {
  263. $calendar[$xmlName] = $row[$dbName];
  264. }
  265. $this->addOwnerPrincipal($calendar);
  266. if (!isset($calendars[$calendar['id']])) {
  267. $calendars[$calendar['id']] = $calendar;
  268. }
  269. }
  270. $stmt->closeCursor();
  271. // query for shared calendars
  272. $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
  273. $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
  274. $principals = array_map(function($principal) {
  275. return urldecode($principal);
  276. }, $principals);
  277. $principals[]= $principalUri;
  278. $fields = array_values($this->propertyMap);
  279. $fields[] = 'a.id';
  280. $fields[] = 'a.uri';
  281. $fields[] = 'a.synctoken';
  282. $fields[] = 'a.components';
  283. $fields[] = 'a.principaluri';
  284. $fields[] = 'a.transparent';
  285. $fields[] = 's.access';
  286. $query = $this->db->getQueryBuilder();
  287. $result = $query->select($fields)
  288. ->from('dav_shares', 's')
  289. ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
  290. ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
  291. ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
  292. ->setParameter('type', 'calendar')
  293. ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
  294. ->execute();
  295. $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
  296. while($row = $result->fetch()) {
  297. if ($row['principaluri'] === $principalUri) {
  298. continue;
  299. }
  300. $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
  301. if (isset($calendars[$row['id']])) {
  302. if ($readOnly) {
  303. // New share can not have more permissions then the old one.
  304. continue;
  305. }
  306. if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
  307. $calendars[$row['id']][$readOnlyPropertyName] === 0) {
  308. // Old share is already read-write, no more permissions can be gained
  309. continue;
  310. }
  311. }
  312. list(, $name) = Uri\split($row['principaluri']);
  313. $uri = $row['uri'] . '_shared_by_' . $name;
  314. $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
  315. $components = [];
  316. if ($row['components']) {
  317. $components = explode(',',$row['components']);
  318. }
  319. $calendar = [
  320. 'id' => $row['id'],
  321. 'uri' => $uri,
  322. 'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
  323. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  324. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  325. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  326. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
  327. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  328. $readOnlyPropertyName => $readOnly,
  329. ];
  330. foreach($this->propertyMap as $xmlName=>$dbName) {
  331. $calendar[$xmlName] = $row[$dbName];
  332. }
  333. $this->addOwnerPrincipal($calendar);
  334. $calendars[$calendar['id']] = $calendar;
  335. }
  336. $result->closeCursor();
  337. return array_values($calendars);
  338. }
  339. /**
  340. * @param $principalUri
  341. * @return array
  342. */
  343. public function getUsersOwnCalendars($principalUri) {
  344. $principalUri = $this->convertPrincipal($principalUri, true);
  345. $fields = array_values($this->propertyMap);
  346. $fields[] = 'id';
  347. $fields[] = 'uri';
  348. $fields[] = 'synctoken';
  349. $fields[] = 'components';
  350. $fields[] = 'principaluri';
  351. $fields[] = 'transparent';
  352. // Making fields a comma-delimited list
  353. $query = $this->db->getQueryBuilder();
  354. $query->select($fields)->from('calendars')
  355. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  356. ->orderBy('calendarorder', 'ASC');
  357. $stmt = $query->execute();
  358. $calendars = [];
  359. while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  360. $components = [];
  361. if ($row['components']) {
  362. $components = explode(',',$row['components']);
  363. }
  364. $calendar = [
  365. 'id' => $row['id'],
  366. 'uri' => $row['uri'],
  367. 'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  368. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  369. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  370. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  371. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
  372. ];
  373. foreach($this->propertyMap as $xmlName=>$dbName) {
  374. $calendar[$xmlName] = $row[$dbName];
  375. }
  376. $this->addOwnerPrincipal($calendar);
  377. if (!isset($calendars[$calendar['id']])) {
  378. $calendars[$calendar['id']] = $calendar;
  379. }
  380. }
  381. $stmt->closeCursor();
  382. return array_values($calendars);
  383. }
  384. /**
  385. * @param $uid
  386. * @return string
  387. */
  388. private function getUserDisplayName($uid) {
  389. if (!isset($this->userDisplayNames[$uid])) {
  390. $user = $this->userManager->get($uid);
  391. if ($user instanceof IUser) {
  392. $this->userDisplayNames[$uid] = $user->getDisplayName();
  393. } else {
  394. $this->userDisplayNames[$uid] = $uid;
  395. }
  396. }
  397. return $this->userDisplayNames[$uid];
  398. }
  399. /**
  400. * @return array
  401. */
  402. public function getPublicCalendars() {
  403. $fields = array_values($this->propertyMap);
  404. $fields[] = 'a.id';
  405. $fields[] = 'a.uri';
  406. $fields[] = 'a.synctoken';
  407. $fields[] = 'a.components';
  408. $fields[] = 'a.principaluri';
  409. $fields[] = 'a.transparent';
  410. $fields[] = 's.access';
  411. $fields[] = 's.publicuri';
  412. $calendars = [];
  413. $query = $this->db->getQueryBuilder();
  414. $result = $query->select($fields)
  415. ->from('dav_shares', 's')
  416. ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
  417. ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
  418. ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
  419. ->execute();
  420. while($row = $result->fetch()) {
  421. list(, $name) = Uri\split($row['principaluri']);
  422. $row['displayname'] = $row['displayname'] . "($name)";
  423. $components = [];
  424. if ($row['components']) {
  425. $components = explode(',',$row['components']);
  426. }
  427. $calendar = [
  428. 'id' => $row['id'],
  429. 'uri' => $row['publicuri'],
  430. 'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  431. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  432. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  433. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  434. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
  435. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
  436. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
  437. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
  438. ];
  439. foreach($this->propertyMap as $xmlName=>$dbName) {
  440. $calendar[$xmlName] = $row[$dbName];
  441. }
  442. $this->addOwnerPrincipal($calendar);
  443. if (!isset($calendars[$calendar['id']])) {
  444. $calendars[$calendar['id']] = $calendar;
  445. }
  446. }
  447. $result->closeCursor();
  448. return array_values($calendars);
  449. }
  450. /**
  451. * @param string $uri
  452. * @return array
  453. * @throws NotFound
  454. */
  455. public function getPublicCalendar($uri) {
  456. $fields = array_values($this->propertyMap);
  457. $fields[] = 'a.id';
  458. $fields[] = 'a.uri';
  459. $fields[] = 'a.synctoken';
  460. $fields[] = 'a.components';
  461. $fields[] = 'a.principaluri';
  462. $fields[] = 'a.transparent';
  463. $fields[] = 's.access';
  464. $fields[] = 's.publicuri';
  465. $query = $this->db->getQueryBuilder();
  466. $result = $query->select($fields)
  467. ->from('dav_shares', 's')
  468. ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
  469. ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
  470. ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
  471. ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
  472. ->execute();
  473. $row = $result->fetch(\PDO::FETCH_ASSOC);
  474. $result->closeCursor();
  475. if ($row === false) {
  476. throw new NotFound('Node with name \'' . $uri . '\' could not be found');
  477. }
  478. list(, $name) = Uri\split($row['principaluri']);
  479. $row['displayname'] = $row['displayname'] . ' ' . "($name)";
  480. $components = [];
  481. if ($row['components']) {
  482. $components = explode(',',$row['components']);
  483. }
  484. $calendar = [
  485. 'id' => $row['id'],
  486. 'uri' => $row['publicuri'],
  487. 'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  488. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  489. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  490. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  491. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
  492. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  493. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
  494. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
  495. ];
  496. foreach($this->propertyMap as $xmlName=>$dbName) {
  497. $calendar[$xmlName] = $row[$dbName];
  498. }
  499. $this->addOwnerPrincipal($calendar);
  500. return $calendar;
  501. }
  502. /**
  503. * @param string $principal
  504. * @param string $uri
  505. * @return array|null
  506. */
  507. public function getCalendarByUri($principal, $uri) {
  508. $fields = array_values($this->propertyMap);
  509. $fields[] = 'id';
  510. $fields[] = 'uri';
  511. $fields[] = 'synctoken';
  512. $fields[] = 'components';
  513. $fields[] = 'principaluri';
  514. $fields[] = 'transparent';
  515. // Making fields a comma-delimited list
  516. $query = $this->db->getQueryBuilder();
  517. $query->select($fields)->from('calendars')
  518. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  519. ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
  520. ->setMaxResults(1);
  521. $stmt = $query->execute();
  522. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  523. $stmt->closeCursor();
  524. if ($row === false) {
  525. return null;
  526. }
  527. $components = [];
  528. if ($row['components']) {
  529. $components = explode(',',$row['components']);
  530. }
  531. $calendar = [
  532. 'id' => $row['id'],
  533. 'uri' => $row['uri'],
  534. 'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  535. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  536. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  537. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  538. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
  539. ];
  540. foreach($this->propertyMap as $xmlName=>$dbName) {
  541. $calendar[$xmlName] = $row[$dbName];
  542. }
  543. $this->addOwnerPrincipal($calendar);
  544. return $calendar;
  545. }
  546. /**
  547. * @param $calendarId
  548. * @return array|null
  549. */
  550. public function getCalendarById($calendarId) {
  551. $fields = array_values($this->propertyMap);
  552. $fields[] = 'id';
  553. $fields[] = 'uri';
  554. $fields[] = 'synctoken';
  555. $fields[] = 'components';
  556. $fields[] = 'principaluri';
  557. $fields[] = 'transparent';
  558. // Making fields a comma-delimited list
  559. $query = $this->db->getQueryBuilder();
  560. $query->select($fields)->from('calendars')
  561. ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
  562. ->setMaxResults(1);
  563. $stmt = $query->execute();
  564. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  565. $stmt->closeCursor();
  566. if ($row === false) {
  567. return null;
  568. }
  569. $components = [];
  570. if ($row['components']) {
  571. $components = explode(',',$row['components']);
  572. }
  573. $calendar = [
  574. 'id' => $row['id'],
  575. 'uri' => $row['uri'],
  576. 'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
  577. '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
  578. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  579. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
  580. '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
  581. ];
  582. foreach($this->propertyMap as $xmlName=>$dbName) {
  583. $calendar[$xmlName] = $row[$dbName];
  584. }
  585. $this->addOwnerPrincipal($calendar);
  586. return $calendar;
  587. }
  588. /**
  589. * @param $subscriptionId
  590. */
  591. public function getSubscriptionById($subscriptionId) {
  592. $fields = array_values($this->subscriptionPropertyMap);
  593. $fields[] = 'id';
  594. $fields[] = 'uri';
  595. $fields[] = 'source';
  596. $fields[] = 'synctoken';
  597. $fields[] = 'principaluri';
  598. $fields[] = 'lastmodified';
  599. $query = $this->db->getQueryBuilder();
  600. $query->select($fields)
  601. ->from('calendarsubscriptions')
  602. ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
  603. ->orderBy('calendarorder', 'asc');
  604. $stmt =$query->execute();
  605. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  606. $stmt->closeCursor();
  607. if ($row === false) {
  608. return null;
  609. }
  610. $subscription = [
  611. 'id' => $row['id'],
  612. 'uri' => $row['uri'],
  613. 'principaluri' => $row['principaluri'],
  614. 'source' => $row['source'],
  615. 'lastmodified' => $row['lastmodified'],
  616. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
  617. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  618. ];
  619. foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
  620. if (!is_null($row[$dbName])) {
  621. $subscription[$xmlName] = $row[$dbName];
  622. }
  623. }
  624. return $subscription;
  625. }
  626. /**
  627. * Creates a new calendar for a principal.
  628. *
  629. * If the creation was a success, an id must be returned that can be used to reference
  630. * this calendar in other methods, such as updateCalendar.
  631. *
  632. * @param string $principalUri
  633. * @param string $calendarUri
  634. * @param array $properties
  635. * @return int
  636. * @suppress SqlInjectionChecker
  637. */
  638. function createCalendar($principalUri, $calendarUri, array $properties) {
  639. $values = [
  640. 'principaluri' => $this->convertPrincipal($principalUri, true),
  641. 'uri' => $calendarUri,
  642. 'synctoken' => 1,
  643. 'transparent' => 0,
  644. 'components' => 'VEVENT,VTODO',
  645. 'displayname' => $calendarUri
  646. ];
  647. // Default value
  648. $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
  649. if (isset($properties[$sccs])) {
  650. if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
  651. throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
  652. }
  653. $values['components'] = implode(',',$properties[$sccs]->getValue());
  654. } else if (isset($properties['components'])) {
  655. // Allow to provide components internally without having
  656. // to create a SupportedCalendarComponentSet object
  657. $values['components'] = $properties['components'];
  658. }
  659. $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
  660. if (isset($properties[$transp])) {
  661. $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
  662. }
  663. foreach($this->propertyMap as $xmlName=>$dbName) {
  664. if (isset($properties[$xmlName])) {
  665. $values[$dbName] = $properties[$xmlName];
  666. }
  667. }
  668. $query = $this->db->getQueryBuilder();
  669. $query->insert('calendars');
  670. foreach($values as $column => $value) {
  671. $query->setValue($column, $query->createNamedParameter($value));
  672. }
  673. $query->execute();
  674. $calendarId = $query->getLastInsertId();
  675. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
  676. '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
  677. [
  678. 'calendarId' => $calendarId,
  679. 'calendarData' => $this->getCalendarById($calendarId),
  680. ]));
  681. return $calendarId;
  682. }
  683. /**
  684. * Updates properties for a calendar.
  685. *
  686. * The list of mutations is stored in a Sabre\DAV\PropPatch object.
  687. * To do the actual updates, you must tell this object which properties
  688. * you're going to process with the handle() method.
  689. *
  690. * Calling the handle method is like telling the PropPatch object "I
  691. * promise I can handle updating this property".
  692. *
  693. * Read the PropPatch documentation for more info and examples.
  694. *
  695. * @param mixed $calendarId
  696. * @param PropPatch $propPatch
  697. * @return void
  698. */
  699. function updateCalendar($calendarId, PropPatch $propPatch) {
  700. $supportedProperties = array_keys($this->propertyMap);
  701. $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
  702. /**
  703. * @suppress SqlInjectionChecker
  704. */
  705. $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
  706. $newValues = [];
  707. foreach ($mutations as $propertyName => $propertyValue) {
  708. switch ($propertyName) {
  709. case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
  710. $fieldName = 'transparent';
  711. $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
  712. break;
  713. default :
  714. $fieldName = $this->propertyMap[$propertyName];
  715. $newValues[$fieldName] = $propertyValue;
  716. break;
  717. }
  718. }
  719. $query = $this->db->getQueryBuilder();
  720. $query->update('calendars');
  721. foreach ($newValues as $fieldName => $value) {
  722. $query->set($fieldName, $query->createNamedParameter($value));
  723. }
  724. $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
  725. $query->execute();
  726. $this->addChange($calendarId, "", 2);
  727. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
  728. '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
  729. [
  730. 'calendarId' => $calendarId,
  731. 'calendarData' => $this->getCalendarById($calendarId),
  732. 'shares' => $this->getShares($calendarId),
  733. 'propertyMutations' => $mutations,
  734. ]));
  735. return true;
  736. });
  737. }
  738. /**
  739. * Delete a calendar and all it's objects
  740. *
  741. * @param mixed $calendarId
  742. * @return void
  743. */
  744. function deleteCalendar($calendarId) {
  745. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
  746. '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
  747. [
  748. 'calendarId' => $calendarId,
  749. 'calendarData' => $this->getCalendarById($calendarId),
  750. 'shares' => $this->getShares($calendarId),
  751. ]));
  752. $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
  753. $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
  754. $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
  755. $stmt->execute([$calendarId]);
  756. $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
  757. $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
  758. $this->calendarSharingBackend->deleteAllShares($calendarId);
  759. $query = $this->db->getQueryBuilder();
  760. $query->delete($this->dbObjectPropertiesTable)
  761. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  762. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
  763. ->execute();
  764. }
  765. /**
  766. * Delete all of an user's shares
  767. *
  768. * @param string $principaluri
  769. * @return void
  770. */
  771. function deleteAllSharesByUser($principaluri) {
  772. $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
  773. }
  774. /**
  775. * Returns all calendar objects within a calendar.
  776. *
  777. * Every item contains an array with the following keys:
  778. * * calendardata - The iCalendar-compatible calendar data
  779. * * uri - a unique key which will be used to construct the uri. This can
  780. * be any arbitrary string, but making sure it ends with '.ics' is a
  781. * good idea. This is only the basename, or filename, not the full
  782. * path.
  783. * * lastmodified - a timestamp of the last modification time
  784. * * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
  785. * '"abcdef"')
  786. * * size - The size of the calendar objects, in bytes.
  787. * * component - optional, a string containing the type of object, such
  788. * as 'vevent' or 'vtodo'. If specified, this will be used to populate
  789. * the Content-Type header.
  790. *
  791. * Note that the etag is optional, but it's highly encouraged to return for
  792. * speed reasons.
  793. *
  794. * The calendardata is also optional. If it's not returned
  795. * 'getCalendarObject' will be called later, which *is* expected to return
  796. * calendardata.
  797. *
  798. * If neither etag or size are specified, the calendardata will be
  799. * used/fetched to determine these numbers. If both are specified the
  800. * amount of times this is needed is reduced by a great degree.
  801. *
  802. * @param mixed $id
  803. * @param int $calendarType
  804. * @return array
  805. */
  806. public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
  807. $query = $this->db->getQueryBuilder();
  808. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
  809. ->from('calendarobjects')
  810. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
  811. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  812. $stmt = $query->execute();
  813. $result = [];
  814. foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
  815. $result[] = [
  816. 'id' => $row['id'],
  817. 'uri' => $row['uri'],
  818. 'lastmodified' => $row['lastmodified'],
  819. 'etag' => '"' . $row['etag'] . '"',
  820. 'calendarid' => $row['calendarid'],
  821. 'size' => (int)$row['size'],
  822. 'component' => strtolower($row['componenttype']),
  823. 'classification'=> (int)$row['classification']
  824. ];
  825. }
  826. return $result;
  827. }
  828. /**
  829. * Returns information from a single calendar object, based on it's object
  830. * uri.
  831. *
  832. * The object uri is only the basename, or filename and not a full path.
  833. *
  834. * The returned array must have the same keys as getCalendarObjects. The
  835. * 'calendardata' object is required here though, while it's not required
  836. * for getCalendarObjects.
  837. *
  838. * This method must return null if the object did not exist.
  839. *
  840. * @param mixed $id
  841. * @param string $objectUri
  842. * @param int $calendarType
  843. * @return array|null
  844. */
  845. public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  846. $query = $this->db->getQueryBuilder();
  847. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
  848. ->from('calendarobjects')
  849. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
  850. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  851. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  852. $stmt = $query->execute();
  853. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  854. if(!$row) {
  855. return null;
  856. }
  857. return [
  858. 'id' => $row['id'],
  859. 'uri' => $row['uri'],
  860. 'lastmodified' => $row['lastmodified'],
  861. 'etag' => '"' . $row['etag'] . '"',
  862. 'calendarid' => $row['calendarid'],
  863. 'size' => (int)$row['size'],
  864. 'calendardata' => $this->readBlob($row['calendardata']),
  865. 'component' => strtolower($row['componenttype']),
  866. 'classification'=> (int)$row['classification']
  867. ];
  868. }
  869. /**
  870. * Returns a list of calendar objects.
  871. *
  872. * This method should work identical to getCalendarObject, but instead
  873. * return all the calendar objects in the list as an array.
  874. *
  875. * If the backend supports this, it may allow for some speed-ups.
  876. *
  877. * @param mixed $calendarId
  878. * @param string[] $uris
  879. * @param int $calendarType
  880. * @return array
  881. */
  882. public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
  883. if (empty($uris)) {
  884. return [];
  885. }
  886. $chunks = array_chunk($uris, 100);
  887. $objects = [];
  888. $query = $this->db->getQueryBuilder();
  889. $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
  890. ->from('calendarobjects')
  891. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
  892. ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
  893. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  894. foreach ($chunks as $uris) {
  895. $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
  896. $result = $query->execute();
  897. while ($row = $result->fetch()) {
  898. $objects[] = [
  899. 'id' => $row['id'],
  900. 'uri' => $row['uri'],
  901. 'lastmodified' => $row['lastmodified'],
  902. 'etag' => '"' . $row['etag'] . '"',
  903. 'calendarid' => $row['calendarid'],
  904. 'size' => (int)$row['size'],
  905. 'calendardata' => $this->readBlob($row['calendardata']),
  906. 'component' => strtolower($row['componenttype']),
  907. 'classification' => (int)$row['classification']
  908. ];
  909. }
  910. $result->closeCursor();
  911. }
  912. return $objects;
  913. }
  914. /**
  915. * Creates a new calendar object.
  916. *
  917. * The object uri is only the basename, or filename and not a full path.
  918. *
  919. * It is possible return an etag from this function, which will be used in
  920. * the response to this PUT request. Note that the ETag must be surrounded
  921. * by double-quotes.
  922. *
  923. * However, you should only really return this ETag if you don't mangle the
  924. * calendar-data. If the result of a subsequent GET to this object is not
  925. * the exact same as this request body, you should omit the ETag.
  926. *
  927. * @param mixed $calendarId
  928. * @param string $objectUri
  929. * @param string $calendarData
  930. * @param int $calendarType
  931. * @return string
  932. */
  933. function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  934. $extraData = $this->getDenormalizedData($calendarData);
  935. $q = $this->db->getQueryBuilder();
  936. $q->select($q->func()->count('*'))
  937. ->from('calendarobjects')
  938. ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
  939. ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
  940. ->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
  941. $result = $q->execute();
  942. $count = (int) $result->fetchColumn();
  943. $result->closeCursor();
  944. if ($count !== 0) {
  945. throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
  946. }
  947. $query = $this->db->getQueryBuilder();
  948. $query->insert('calendarobjects')
  949. ->values([
  950. 'calendarid' => $query->createNamedParameter($calendarId),
  951. 'uri' => $query->createNamedParameter($objectUri),
  952. 'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
  953. 'lastmodified' => $query->createNamedParameter(time()),
  954. 'etag' => $query->createNamedParameter($extraData['etag']),
  955. 'size' => $query->createNamedParameter($extraData['size']),
  956. 'componenttype' => $query->createNamedParameter($extraData['componentType']),
  957. 'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
  958. 'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
  959. 'classification' => $query->createNamedParameter($extraData['classification']),
  960. 'uid' => $query->createNamedParameter($extraData['uid']),
  961. 'calendartype' => $query->createNamedParameter($calendarType),
  962. ])
  963. ->execute();
  964. $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
  965. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  966. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
  967. '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
  968. [
  969. 'calendarId' => $calendarId,
  970. 'calendarData' => $this->getCalendarById($calendarId),
  971. 'shares' => $this->getShares($calendarId),
  972. 'objectData' => $this->getCalendarObject($calendarId, $objectUri),
  973. ]
  974. ));
  975. } else {
  976. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
  977. '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
  978. [
  979. 'subscriptionId' => $calendarId,
  980. 'calendarData' => $this->getCalendarById($calendarId),
  981. 'shares' => $this->getShares($calendarId),
  982. 'objectData' => $this->getCalendarObject($calendarId, $objectUri),
  983. ]
  984. ));
  985. }
  986. $this->addChange($calendarId, $objectUri, 1, $calendarType);
  987. return '"' . $extraData['etag'] . '"';
  988. }
  989. /**
  990. * Updates an existing calendarobject, based on it's uri.
  991. *
  992. * The object uri is only the basename, or filename and not a full path.
  993. *
  994. * It is possible return an etag from this function, which will be used in
  995. * the response to this PUT request. Note that the ETag must be surrounded
  996. * by double-quotes.
  997. *
  998. * However, you should only really return this ETag if you don't mangle the
  999. * calendar-data. If the result of a subsequent GET to this object is not
  1000. * the exact same as this request body, you should omit the ETag.
  1001. *
  1002. * @param mixed $calendarId
  1003. * @param string $objectUri
  1004. * @param string $calendarData
  1005. * @param int $calendarType
  1006. * @return string
  1007. */
  1008. function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  1009. $extraData = $this->getDenormalizedData($calendarData);
  1010. $query = $this->db->getQueryBuilder();
  1011. $query->update('calendarobjects')
  1012. ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
  1013. ->set('lastmodified', $query->createNamedParameter(time()))
  1014. ->set('etag', $query->createNamedParameter($extraData['etag']))
  1015. ->set('size', $query->createNamedParameter($extraData['size']))
  1016. ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
  1017. ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
  1018. ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
  1019. ->set('classification', $query->createNamedParameter($extraData['classification']))
  1020. ->set('uid', $query->createNamedParameter($extraData['uid']))
  1021. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  1022. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  1023. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
  1024. ->execute();
  1025. $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
  1026. $data = $this->getCalendarObject($calendarId, $objectUri);
  1027. if (is_array($data)) {
  1028. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  1029. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
  1030. '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
  1031. [
  1032. 'calendarId' => $calendarId,
  1033. 'calendarData' => $this->getCalendarById($calendarId),
  1034. 'shares' => $this->getShares($calendarId),
  1035. 'objectData' => $data,
  1036. ]
  1037. ));
  1038. } else {
  1039. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
  1040. '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
  1041. [
  1042. 'subscriptionId' => $calendarId,
  1043. 'calendarData' => $this->getCalendarById($calendarId),
  1044. 'shares' => $this->getShares($calendarId),
  1045. 'objectData' => $data,
  1046. ]
  1047. ));
  1048. }
  1049. }
  1050. $this->addChange($calendarId, $objectUri, 2, $calendarType);
  1051. return '"' . $extraData['etag'] . '"';
  1052. }
  1053. /**
  1054. * @param int $calendarObjectId
  1055. * @param int $classification
  1056. */
  1057. public function setClassification($calendarObjectId, $classification) {
  1058. if (!in_array($classification, [
  1059. self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
  1060. ])) {
  1061. throw new \InvalidArgumentException();
  1062. }
  1063. $query = $this->db->getQueryBuilder();
  1064. $query->update('calendarobjects')
  1065. ->set('classification', $query->createNamedParameter($classification))
  1066. ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
  1067. ->execute();
  1068. }
  1069. /**
  1070. * Deletes an existing calendar object.
  1071. *
  1072. * The object uri is only the basename, or filename and not a full path.
  1073. *
  1074. * @param mixed $calendarId
  1075. * @param string $objectUri
  1076. * @param int $calendarType
  1077. * @return void
  1078. */
  1079. function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  1080. $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
  1081. if (is_array($data)) {
  1082. if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
  1083. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
  1084. '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
  1085. [
  1086. 'calendarId' => $calendarId,
  1087. 'calendarData' => $this->getCalendarById($calendarId),
  1088. 'shares' => $this->getShares($calendarId),
  1089. 'objectData' => $data,
  1090. ]
  1091. ));
  1092. } else {
  1093. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
  1094. '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
  1095. [
  1096. 'subscriptionId' => $calendarId,
  1097. 'calendarData' => $this->getCalendarById($calendarId),
  1098. 'shares' => $this->getShares($calendarId),
  1099. 'objectData' => $data,
  1100. ]
  1101. ));
  1102. }
  1103. }
  1104. $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
  1105. $stmt->execute([$calendarId, $objectUri, $calendarType]);
  1106. if (is_array($data)) {
  1107. $this->purgeProperties($calendarId, $data['id'], $calendarType);
  1108. }
  1109. $this->addChange($calendarId, $objectUri, 3, $calendarType);
  1110. }
  1111. /**
  1112. * Performs a calendar-query on the contents of this calendar.
  1113. *
  1114. * The calendar-query is defined in RFC4791 : CalDAV. Using the
  1115. * calendar-query it is possible for a client to request a specific set of
  1116. * object, based on contents of iCalendar properties, date-ranges and
  1117. * iCalendar component types (VTODO, VEVENT).
  1118. *
  1119. * This method should just return a list of (relative) urls that match this
  1120. * query.
  1121. *
  1122. * The list of filters are specified as an array. The exact array is
  1123. * documented by Sabre\CalDAV\CalendarQueryParser.
  1124. *
  1125. * Note that it is extremely likely that getCalendarObject for every path
  1126. * returned from this method will be called almost immediately after. You
  1127. * may want to anticipate this to speed up these requests.
  1128. *
  1129. * This method provides a default implementation, which parses *all* the
  1130. * iCalendar objects in the specified calendar.
  1131. *
  1132. * This default may well be good enough for personal use, and calendars
  1133. * that aren't very large. But if you anticipate high usage, big calendars
  1134. * or high loads, you are strongly advised to optimize certain paths.
  1135. *
  1136. * The best way to do so is override this method and to optimize
  1137. * specifically for 'common filters'.
  1138. *
  1139. * Requests that are extremely common are:
  1140. * * requests for just VEVENTS
  1141. * * requests for just VTODO
  1142. * * requests with a time-range-filter on either VEVENT or VTODO.
  1143. *
  1144. * ..and combinations of these requests. It may not be worth it to try to
  1145. * handle every possible situation and just rely on the (relatively
  1146. * easy to use) CalendarQueryValidator to handle the rest.
  1147. *
  1148. * Note that especially time-range-filters may be difficult to parse. A
  1149. * time-range filter specified on a VEVENT must for instance also handle
  1150. * recurrence rules correctly.
  1151. * A good example of how to interprete all these filters can also simply
  1152. * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
  1153. * as possible, so it gives you a good idea on what type of stuff you need
  1154. * to think of.
  1155. *
  1156. * @param mixed $id
  1157. * @param array $filters
  1158. * @param int $calendarType
  1159. * @return array
  1160. */
  1161. public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
  1162. $componentType = null;
  1163. $requirePostFilter = true;
  1164. $timeRange = null;
  1165. // if no filters were specified, we don't need to filter after a query
  1166. if (!$filters['prop-filters'] && !$filters['comp-filters']) {
  1167. $requirePostFilter = false;
  1168. }
  1169. // Figuring out if there's a component filter
  1170. if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
  1171. $componentType = $filters['comp-filters'][0]['name'];
  1172. // Checking if we need post-filters
  1173. if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
  1174. $requirePostFilter = false;
  1175. }
  1176. // There was a time-range filter
  1177. if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
  1178. $timeRange = $filters['comp-filters'][0]['time-range'];
  1179. // If start time OR the end time is not specified, we can do a
  1180. // 100% accurate mysql query.
  1181. if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
  1182. $requirePostFilter = false;
  1183. }
  1184. }
  1185. }
  1186. $columns = ['uri'];
  1187. if ($requirePostFilter) {
  1188. $columns = ['uri', 'calendardata'];
  1189. }
  1190. $query = $this->db->getQueryBuilder();
  1191. $query->select($columns)
  1192. ->from('calendarobjects')
  1193. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
  1194. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  1195. if ($componentType) {
  1196. $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
  1197. }
  1198. if ($timeRange && $timeRange['start']) {
  1199. $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
  1200. }
  1201. if ($timeRange && $timeRange['end']) {
  1202. $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
  1203. }
  1204. $stmt = $query->execute();
  1205. $result = [];
  1206. while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  1207. if ($requirePostFilter) {
  1208. // validateFilterForObject will parse the calendar data
  1209. // catch parsing errors
  1210. try {
  1211. $matches = $this->validateFilterForObject($row, $filters);
  1212. } catch(ParseException $ex) {
  1213. $this->logger->logException($ex, [
  1214. 'app' => 'dav',
  1215. 'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
  1216. ]);
  1217. continue;
  1218. } catch (InvalidDataException $ex) {
  1219. $this->logger->logException($ex, [
  1220. 'app' => 'dav',
  1221. 'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
  1222. ]);
  1223. continue;
  1224. }
  1225. if (!$matches) {
  1226. continue;
  1227. }
  1228. }
  1229. $result[] = $row['uri'];
  1230. }
  1231. return $result;
  1232. }
  1233. /**
  1234. * custom Nextcloud search extension for CalDAV
  1235. *
  1236. * TODO - this should optionally cover cached calendar objects as well
  1237. *
  1238. * @param string $principalUri
  1239. * @param array $filters
  1240. * @param integer|null $limit
  1241. * @param integer|null $offset
  1242. * @return array
  1243. */
  1244. public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
  1245. $calendars = $this->getCalendarsForUser($principalUri);
  1246. $ownCalendars = [];
  1247. $sharedCalendars = [];
  1248. $uriMapper = [];
  1249. foreach($calendars as $calendar) {
  1250. if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
  1251. $ownCalendars[] = $calendar['id'];
  1252. } else {
  1253. $sharedCalendars[] = $calendar['id'];
  1254. }
  1255. $uriMapper[$calendar['id']] = $calendar['uri'];
  1256. }
  1257. if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
  1258. return [];
  1259. }
  1260. $query = $this->db->getQueryBuilder();
  1261. // Calendar id expressions
  1262. $calendarExpressions = [];
  1263. foreach($ownCalendars as $id) {
  1264. $calendarExpressions[] = $query->expr()->andX(
  1265. $query->expr()->eq('c.calendarid',
  1266. $query->createNamedParameter($id)),
  1267. $query->expr()->eq('c.calendartype',
  1268. $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
  1269. }
  1270. foreach($sharedCalendars as $id) {
  1271. $calendarExpressions[] = $query->expr()->andX(
  1272. $query->expr()->eq('c.calendarid',
  1273. $query->createNamedParameter($id)),
  1274. $query->expr()->eq('c.classification',
  1275. $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
  1276. $query->expr()->eq('c.calendartype',
  1277. $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
  1278. }
  1279. if (count($calendarExpressions) === 1) {
  1280. $calExpr = $calendarExpressions[0];
  1281. } else {
  1282. $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
  1283. }
  1284. // Component expressions
  1285. $compExpressions = [];
  1286. foreach($filters['comps'] as $comp) {
  1287. $compExpressions[] = $query->expr()
  1288. ->eq('c.componenttype', $query->createNamedParameter($comp));
  1289. }
  1290. if (count($compExpressions) === 1) {
  1291. $compExpr = $compExpressions[0];
  1292. } else {
  1293. $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
  1294. }
  1295. if (!isset($filters['props'])) {
  1296. $filters['props'] = [];
  1297. }
  1298. if (!isset($filters['params'])) {
  1299. $filters['params'] = [];
  1300. }
  1301. $propParamExpressions = [];
  1302. foreach($filters['props'] as $prop) {
  1303. $propParamExpressions[] = $query->expr()->andX(
  1304. $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
  1305. $query->expr()->isNull('i.parameter')
  1306. );
  1307. }
  1308. foreach($filters['params'] as $param) {
  1309. $propParamExpressions[] = $query->expr()->andX(
  1310. $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
  1311. $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
  1312. );
  1313. }
  1314. if (count($propParamExpressions) === 1) {
  1315. $propParamExpr = $propParamExpressions[0];
  1316. } else {
  1317. $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
  1318. }
  1319. $query->select(['c.calendarid', 'c.uri'])
  1320. ->from($this->dbObjectPropertiesTable, 'i')
  1321. ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
  1322. ->where($calExpr)
  1323. ->andWhere($compExpr)
  1324. ->andWhere($propParamExpr)
  1325. ->andWhere($query->expr()->iLike('i.value',
  1326. $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
  1327. if ($offset) {
  1328. $query->setFirstResult($offset);
  1329. }
  1330. if ($limit) {
  1331. $query->setMaxResults($limit);
  1332. }
  1333. $stmt = $query->execute();
  1334. $result = [];
  1335. while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  1336. $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
  1337. if (!in_array($path, $result)) {
  1338. $result[] = $path;
  1339. }
  1340. }
  1341. return $result;
  1342. }
  1343. /**
  1344. * used for Nextcloud's calendar API
  1345. *
  1346. * @param array $calendarInfo
  1347. * @param string $pattern
  1348. * @param array $searchProperties
  1349. * @param array $options
  1350. * @param integer|null $limit
  1351. * @param integer|null $offset
  1352. *
  1353. * @return array
  1354. */
  1355. public function search(array $calendarInfo, $pattern, array $searchProperties,
  1356. array $options, $limit, $offset) {
  1357. $outerQuery = $this->db->getQueryBuilder();
  1358. $innerQuery = $this->db->getQueryBuilder();
  1359. $innerQuery->selectDistinct('op.objectid')
  1360. ->from($this->dbObjectPropertiesTable, 'op')
  1361. ->andWhere($innerQuery->expr()->eq('op.calendarid',
  1362. $outerQuery->createNamedParameter($calendarInfo['id'])))
  1363. ->andWhere($innerQuery->expr()->eq('op.calendartype',
  1364. $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
  1365. // only return public items for shared calendars for now
  1366. if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
  1367. $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
  1368. $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
  1369. }
  1370. $or = $innerQuery->expr()->orX();
  1371. foreach($searchProperties as $searchProperty) {
  1372. $or->add($innerQuery->expr()->eq('op.name',
  1373. $outerQuery->createNamedParameter($searchProperty)));
  1374. }
  1375. $innerQuery->andWhere($or);
  1376. if ($pattern !== '') {
  1377. $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
  1378. $outerQuery->createNamedParameter('%' .
  1379. $this->db->escapeLikeParameter($pattern) . '%')));
  1380. }
  1381. $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
  1382. ->from('calendarobjects', 'c');
  1383. if (isset($options['timerange'])) {
  1384. if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
  1385. $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
  1386. $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
  1387. }
  1388. if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
  1389. $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
  1390. $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
  1391. }
  1392. }
  1393. if (isset($options['types'])) {
  1394. $or = $outerQuery->expr()->orX();
  1395. foreach($options['types'] as $type) {
  1396. $or->add($outerQuery->expr()->eq('componenttype',
  1397. $outerQuery->createNamedParameter($type)));
  1398. }
  1399. $outerQuery->andWhere($or);
  1400. }
  1401. $outerQuery->andWhere($outerQuery->expr()->in('c.id',
  1402. $outerQuery->createFunction($innerQuery->getSQL())));
  1403. if ($offset) {
  1404. $outerQuery->setFirstResult($offset);
  1405. }
  1406. if ($limit) {
  1407. $outerQuery->setMaxResults($limit);
  1408. }
  1409. $result = $outerQuery->execute();
  1410. $calendarObjects = $result->fetchAll();
  1411. return array_map(function($o) {
  1412. $calendarData = Reader::read($o['calendardata']);
  1413. $comps = $calendarData->getComponents();
  1414. $objects = [];
  1415. $timezones = [];
  1416. foreach($comps as $comp) {
  1417. if ($comp instanceof VTimeZone) {
  1418. $timezones[] = $comp;
  1419. } else {
  1420. $objects[] = $comp;
  1421. }
  1422. }
  1423. return [
  1424. 'id' => $o['id'],
  1425. 'type' => $o['componenttype'],
  1426. 'uid' => $o['uid'],
  1427. 'uri' => $o['uri'],
  1428. 'objects' => array_map(function($c) {
  1429. return $this->transformSearchData($c);
  1430. }, $objects),
  1431. 'timezones' => array_map(function($c) {
  1432. return $this->transformSearchData($c);
  1433. }, $timezones),
  1434. ];
  1435. }, $calendarObjects);
  1436. }
  1437. /**
  1438. * @param Component $comp
  1439. * @return array
  1440. */
  1441. private function transformSearchData(Component $comp) {
  1442. $data = [];
  1443. /** @var Component[] $subComponents */
  1444. $subComponents = $comp->getComponents();
  1445. /** @var Property[] $properties */
  1446. $properties = array_filter($comp->children(), function($c) {
  1447. return $c instanceof Property;
  1448. });
  1449. $validationRules = $comp->getValidationRules();
  1450. foreach($subComponents as $subComponent) {
  1451. $name = $subComponent->name;
  1452. if (!isset($data[$name])) {
  1453. $data[$name] = [];
  1454. }
  1455. $data[$name][] = $this->transformSearchData($subComponent);
  1456. }
  1457. foreach($properties as $property) {
  1458. $name = $property->name;
  1459. if (!isset($validationRules[$name])) {
  1460. $validationRules[$name] = '*';
  1461. }
  1462. $rule = $validationRules[$property->name];
  1463. if ($rule === '+' || $rule === '*') { // multiple
  1464. if (!isset($data[$name])) {
  1465. $data[$name] = [];
  1466. }
  1467. $data[$name][] = $this->transformSearchProperty($property);
  1468. } else { // once
  1469. $data[$name] = $this->transformSearchProperty($property);
  1470. }
  1471. }
  1472. return $data;
  1473. }
  1474. /**
  1475. * @param Property $prop
  1476. * @return array
  1477. */
  1478. private function transformSearchProperty(Property $prop) {
  1479. // No need to check Date, as it extends DateTime
  1480. if ($prop instanceof Property\ICalendar\DateTime) {
  1481. $value = $prop->getDateTime();
  1482. } else {
  1483. $value = $prop->getValue();
  1484. }
  1485. return [
  1486. $value,
  1487. $prop->parameters()
  1488. ];
  1489. }
  1490. /**
  1491. * Searches through all of a users calendars and calendar objects to find
  1492. * an object with a specific UID.
  1493. *
  1494. * This method should return the path to this object, relative to the
  1495. * calendar home, so this path usually only contains two parts:
  1496. *
  1497. * calendarpath/objectpath.ics
  1498. *
  1499. * If the uid is not found, return null.
  1500. *
  1501. * This method should only consider * objects that the principal owns, so
  1502. * any calendars owned by other principals that also appear in this
  1503. * collection should be ignored.
  1504. *
  1505. * @param string $principalUri
  1506. * @param string $uid
  1507. * @return string|null
  1508. */
  1509. function getCalendarObjectByUID($principalUri, $uid) {
  1510. $query = $this->db->getQueryBuilder();
  1511. $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
  1512. ->from('calendarobjects', 'co')
  1513. ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
  1514. ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
  1515. ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
  1516. ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
  1517. $stmt = $query->execute();
  1518. if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  1519. return $row['calendaruri'] . '/' . $row['objecturi'];
  1520. }
  1521. return null;
  1522. }
  1523. /**
  1524. * The getChanges method returns all the changes that have happened, since
  1525. * the specified syncToken in the specified calendar.
  1526. *
  1527. * This function should return an array, such as the following:
  1528. *
  1529. * [
  1530. * 'syncToken' => 'The current synctoken',
  1531. * 'added' => [
  1532. * 'new.txt',
  1533. * ],
  1534. * 'modified' => [
  1535. * 'modified.txt',
  1536. * ],
  1537. * 'deleted' => [
  1538. * 'foo.php.bak',
  1539. * 'old.txt'
  1540. * ]
  1541. * );
  1542. *
  1543. * The returned syncToken property should reflect the *current* syncToken
  1544. * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
  1545. * property This is * needed here too, to ensure the operation is atomic.
  1546. *
  1547. * If the $syncToken argument is specified as null, this is an initial
  1548. * sync, and all members should be reported.
  1549. *
  1550. * The modified property is an array of nodenames that have changed since
  1551. * the last token.
  1552. *
  1553. * The deleted property is an array with nodenames, that have been deleted
  1554. * from collection.
  1555. *
  1556. * The $syncLevel argument is basically the 'depth' of the report. If it's
  1557. * 1, you only have to report changes that happened only directly in
  1558. * immediate descendants. If it's 2, it should also include changes from
  1559. * the nodes below the child collections. (grandchildren)
  1560. *
  1561. * The $limit argument allows a client to specify how many results should
  1562. * be returned at most. If the limit is not specified, it should be treated
  1563. * as infinite.
  1564. *
  1565. * If the limit (infinite or not) is higher than you're willing to return,
  1566. * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
  1567. *
  1568. * If the syncToken is expired (due to data cleanup) or unknown, you must
  1569. * return null.
  1570. *
  1571. * The limit is 'suggestive'. You are free to ignore it.
  1572. *
  1573. * @param string $calendarId
  1574. * @param string $syncToken
  1575. * @param int $syncLevel
  1576. * @param int $limit
  1577. * @param int $calendarType
  1578. * @return array
  1579. */
  1580. function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  1581. // Current synctoken
  1582. $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
  1583. $stmt->execute([ $calendarId ]);
  1584. $currentToken = $stmt->fetchColumn(0);
  1585. if (is_null($currentToken)) {
  1586. return null;
  1587. }
  1588. $result = [
  1589. 'syncToken' => $currentToken,
  1590. 'added' => [],
  1591. 'modified' => [],
  1592. 'deleted' => [],
  1593. ];
  1594. if ($syncToken) {
  1595. $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
  1596. if ($limit>0) {
  1597. $query.= " LIMIT " . (int)$limit;
  1598. }
  1599. // Fetching all changes
  1600. $stmt = $this->db->prepare($query);
  1601. $stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
  1602. $changes = [];
  1603. // This loop ensures that any duplicates are overwritten, only the
  1604. // last change on a node is relevant.
  1605. while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  1606. $changes[$row['uri']] = $row['operation'];
  1607. }
  1608. foreach($changes as $uri => $operation) {
  1609. switch($operation) {
  1610. case 1 :
  1611. $result['added'][] = $uri;
  1612. break;
  1613. case 2 :
  1614. $result['modified'][] = $uri;
  1615. break;
  1616. case 3 :
  1617. $result['deleted'][] = $uri;
  1618. break;
  1619. }
  1620. }
  1621. } else {
  1622. // No synctoken supplied, this is the initial sync.
  1623. $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
  1624. $stmt = $this->db->prepare($query);
  1625. $stmt->execute([$calendarId, $calendarType]);
  1626. $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
  1627. }
  1628. return $result;
  1629. }
  1630. /**
  1631. * Returns a list of subscriptions for a principal.
  1632. *
  1633. * Every subscription is an array with the following keys:
  1634. * * id, a unique id that will be used by other functions to modify the
  1635. * subscription. This can be the same as the uri or a database key.
  1636. * * uri. This is just the 'base uri' or 'filename' of the subscription.
  1637. * * principaluri. The owner of the subscription. Almost always the same as
  1638. * principalUri passed to this method.
  1639. *
  1640. * Furthermore, all the subscription info must be returned too:
  1641. *
  1642. * 1. {DAV:}displayname
  1643. * 2. {http://apple.com/ns/ical/}refreshrate
  1644. * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
  1645. * should not be stripped).
  1646. * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
  1647. * should not be stripped).
  1648. * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
  1649. * attachments should not be stripped).
  1650. * 6. {http://calendarserver.org/ns/}source (Must be a
  1651. * Sabre\DAV\Property\Href).
  1652. * 7. {http://apple.com/ns/ical/}calendar-color
  1653. * 8. {http://apple.com/ns/ical/}calendar-order
  1654. * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
  1655. * (should just be an instance of
  1656. * Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
  1657. * default components).
  1658. *
  1659. * @param string $principalUri
  1660. * @return array
  1661. */
  1662. function getSubscriptionsForUser($principalUri) {
  1663. $fields = array_values($this->subscriptionPropertyMap);
  1664. $fields[] = 'id';
  1665. $fields[] = 'uri';
  1666. $fields[] = 'source';
  1667. $fields[] = 'principaluri';
  1668. $fields[] = 'lastmodified';
  1669. $fields[] = 'synctoken';
  1670. $query = $this->db->getQueryBuilder();
  1671. $query->select($fields)
  1672. ->from('calendarsubscriptions')
  1673. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  1674. ->orderBy('calendarorder', 'asc');
  1675. $stmt =$query->execute();
  1676. $subscriptions = [];
  1677. while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  1678. $subscription = [
  1679. 'id' => $row['id'],
  1680. 'uri' => $row['uri'],
  1681. 'principaluri' => $row['principaluri'],
  1682. 'source' => $row['source'],
  1683. 'lastmodified' => $row['lastmodified'],
  1684. '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
  1685. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  1686. ];
  1687. foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
  1688. if (!is_null($row[$dbName])) {
  1689. $subscription[$xmlName] = $row[$dbName];
  1690. }
  1691. }
  1692. $subscriptions[] = $subscription;
  1693. }
  1694. return $subscriptions;
  1695. }
  1696. /**
  1697. * Creates a new subscription for a principal.
  1698. *
  1699. * If the creation was a success, an id must be returned that can be used to reference
  1700. * this subscription in other methods, such as updateSubscription.
  1701. *
  1702. * @param string $principalUri
  1703. * @param string $uri
  1704. * @param array $properties
  1705. * @return mixed
  1706. */
  1707. function createSubscription($principalUri, $uri, array $properties) {
  1708. if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
  1709. throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
  1710. }
  1711. $values = [
  1712. 'principaluri' => $principalUri,
  1713. 'uri' => $uri,
  1714. 'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
  1715. 'lastmodified' => time(),
  1716. ];
  1717. $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
  1718. foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
  1719. if (array_key_exists($xmlName, $properties)) {
  1720. $values[$dbName] = $properties[$xmlName];
  1721. if (in_array($dbName, $propertiesBoolean)) {
  1722. $values[$dbName] = true;
  1723. }
  1724. }
  1725. }
  1726. $valuesToInsert = [];
  1727. $query = $this->db->getQueryBuilder();
  1728. foreach (array_keys($values) as $name) {
  1729. $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
  1730. }
  1731. $query->insert('calendarsubscriptions')
  1732. ->values($valuesToInsert)
  1733. ->execute();
  1734. $subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
  1735. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
  1736. '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
  1737. [
  1738. 'subscriptionId' => $subscriptionId,
  1739. 'subscriptionData' => $this->getSubscriptionById($subscriptionId),
  1740. ]));
  1741. return $subscriptionId;
  1742. }
  1743. /**
  1744. * Updates a subscription
  1745. *
  1746. * The list of mutations is stored in a Sabre\DAV\PropPatch object.
  1747. * To do the actual updates, you must tell this object which properties
  1748. * you're going to process with the handle() method.
  1749. *
  1750. * Calling the handle method is like telling the PropPatch object "I
  1751. * promise I can handle updating this property".
  1752. *
  1753. * Read the PropPatch documentation for more info and examples.
  1754. *
  1755. * @param mixed $subscriptionId
  1756. * @param PropPatch $propPatch
  1757. * @return void
  1758. */
  1759. function updateSubscription($subscriptionId, PropPatch $propPatch) {
  1760. $supportedProperties = array_keys($this->subscriptionPropertyMap);
  1761. $supportedProperties[] = '{http://calendarserver.org/ns/}source';
  1762. /**
  1763. * @suppress SqlInjectionChecker
  1764. */
  1765. $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
  1766. $newValues = [];
  1767. foreach($mutations as $propertyName=>$propertyValue) {
  1768. if ($propertyName === '{http://calendarserver.org/ns/}source') {
  1769. $newValues['source'] = $propertyValue->getHref();
  1770. } else {
  1771. $fieldName = $this->subscriptionPropertyMap[$propertyName];
  1772. $newValues[$fieldName] = $propertyValue;
  1773. }
  1774. }
  1775. $query = $this->db->getQueryBuilder();
  1776. $query->update('calendarsubscriptions')
  1777. ->set('lastmodified', $query->createNamedParameter(time()));
  1778. foreach($newValues as $fieldName=>$value) {
  1779. $query->set($fieldName, $query->createNamedParameter($value));
  1780. }
  1781. $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
  1782. ->execute();
  1783. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
  1784. '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
  1785. [
  1786. 'subscriptionId' => $subscriptionId,
  1787. 'subscriptionData' => $this->getSubscriptionById($subscriptionId),
  1788. 'propertyMutations' => $mutations,
  1789. ]));
  1790. return true;
  1791. });
  1792. }
  1793. /**
  1794. * Deletes a subscription.
  1795. *
  1796. * @param mixed $subscriptionId
  1797. * @return void
  1798. */
  1799. function deleteSubscription($subscriptionId) {
  1800. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
  1801. '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
  1802. [
  1803. 'subscriptionId' => $subscriptionId,
  1804. 'subscriptionData' => $this->getSubscriptionById($subscriptionId),
  1805. ]));
  1806. $query = $this->db->getQueryBuilder();
  1807. $query->delete('calendarsubscriptions')
  1808. ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
  1809. ->execute();
  1810. $query = $this->db->getQueryBuilder();
  1811. $query->delete('calendarobjects')
  1812. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  1813. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  1814. ->execute();
  1815. $query->delete('calendarchanges')
  1816. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  1817. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  1818. ->execute();
  1819. $query->delete($this->dbObjectPropertiesTable)
  1820. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  1821. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  1822. ->execute();
  1823. }
  1824. /**
  1825. * Returns a single scheduling object for the inbox collection.
  1826. *
  1827. * The returned array should contain the following elements:
  1828. * * uri - A unique basename for the object. This will be used to
  1829. * construct a full uri.
  1830. * * calendardata - The iCalendar object
  1831. * * lastmodified - The last modification date. Can be an int for a unix
  1832. * timestamp, or a PHP DateTime object.
  1833. * * etag - A unique token that must change if the object changed.
  1834. * * size - The size of the object, in bytes.
  1835. *
  1836. * @param string $principalUri
  1837. * @param string $objectUri
  1838. * @return array
  1839. */
  1840. function getSchedulingObject($principalUri, $objectUri) {
  1841. $query = $this->db->getQueryBuilder();
  1842. $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
  1843. ->from('schedulingobjects')
  1844. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  1845. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  1846. ->execute();
  1847. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  1848. if(!$row) {
  1849. return null;
  1850. }
  1851. return [
  1852. 'uri' => $row['uri'],
  1853. 'calendardata' => $row['calendardata'],
  1854. 'lastmodified' => $row['lastmodified'],
  1855. 'etag' => '"' . $row['etag'] . '"',
  1856. 'size' => (int)$row['size'],
  1857. ];
  1858. }
  1859. /**
  1860. * Returns all scheduling objects for the inbox collection.
  1861. *
  1862. * These objects should be returned as an array. Every item in the array
  1863. * should follow the same structure as returned from getSchedulingObject.
  1864. *
  1865. * The main difference is that 'calendardata' is optional.
  1866. *
  1867. * @param string $principalUri
  1868. * @return array
  1869. */
  1870. function getSchedulingObjects($principalUri) {
  1871. $query = $this->db->getQueryBuilder();
  1872. $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
  1873. ->from('schedulingobjects')
  1874. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  1875. ->execute();
  1876. $result = [];
  1877. foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
  1878. $result[] = [
  1879. 'calendardata' => $row['calendardata'],
  1880. 'uri' => $row['uri'],
  1881. 'lastmodified' => $row['lastmodified'],
  1882. 'etag' => '"' . $row['etag'] . '"',
  1883. 'size' => (int)$row['size'],
  1884. ];
  1885. }
  1886. return $result;
  1887. }
  1888. /**
  1889. * Deletes a scheduling object from the inbox collection.
  1890. *
  1891. * @param string $principalUri
  1892. * @param string $objectUri
  1893. * @return void
  1894. */
  1895. function deleteSchedulingObject($principalUri, $objectUri) {
  1896. $query = $this->db->getQueryBuilder();
  1897. $query->delete('schedulingobjects')
  1898. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
  1899. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
  1900. ->execute();
  1901. }
  1902. /**
  1903. * Creates a new scheduling object. This should land in a users' inbox.
  1904. *
  1905. * @param string $principalUri
  1906. * @param string $objectUri
  1907. * @param string $objectData
  1908. * @return void
  1909. */
  1910. function createSchedulingObject($principalUri, $objectUri, $objectData) {
  1911. $query = $this->db->getQueryBuilder();
  1912. $query->insert('schedulingobjects')
  1913. ->values([
  1914. 'principaluri' => $query->createNamedParameter($principalUri),
  1915. 'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
  1916. 'uri' => $query->createNamedParameter($objectUri),
  1917. 'lastmodified' => $query->createNamedParameter(time()),
  1918. 'etag' => $query->createNamedParameter(md5($objectData)),
  1919. 'size' => $query->createNamedParameter(strlen($objectData))
  1920. ])
  1921. ->execute();
  1922. }
  1923. /**
  1924. * Adds a change record to the calendarchanges table.
  1925. *
  1926. * @param mixed $calendarId
  1927. * @param string $objectUri
  1928. * @param int $operation 1 = add, 2 = modify, 3 = delete.
  1929. * @param int $calendarType
  1930. * @return void
  1931. */
  1932. protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  1933. $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
  1934. $query = $this->db->getQueryBuilder();
  1935. $query->select('synctoken')
  1936. ->from($table)
  1937. ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
  1938. $syncToken = (int)$query->execute()->fetchColumn();
  1939. $query = $this->db->getQueryBuilder();
  1940. $query->insert('calendarchanges')
  1941. ->values([
  1942. 'uri' => $query->createNamedParameter($objectUri),
  1943. 'synctoken' => $query->createNamedParameter($syncToken),
  1944. 'calendarid' => $query->createNamedParameter($calendarId),
  1945. 'operation' => $query->createNamedParameter($operation),
  1946. 'calendartype' => $query->createNamedParameter($calendarType),
  1947. ])
  1948. ->execute();
  1949. $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
  1950. $stmt->execute([
  1951. $calendarId
  1952. ]);
  1953. }
  1954. /**
  1955. * Parses some information from calendar objects, used for optimized
  1956. * calendar-queries.
  1957. *
  1958. * Returns an array with the following keys:
  1959. * * etag - An md5 checksum of the object without the quotes.
  1960. * * size - Size of the object in bytes
  1961. * * componentType - VEVENT, VTODO or VJOURNAL
  1962. * * firstOccurence
  1963. * * lastOccurence
  1964. * * uid - value of the UID property
  1965. *
  1966. * @param string $calendarData
  1967. * @return array
  1968. */
  1969. public function getDenormalizedData($calendarData) {
  1970. $vObject = Reader::read($calendarData);
  1971. $componentType = null;
  1972. $component = null;
  1973. $firstOccurrence = null;
  1974. $lastOccurrence = null;
  1975. $uid = null;
  1976. $classification = self::CLASSIFICATION_PUBLIC;
  1977. foreach($vObject->getComponents() as $component) {
  1978. if ($component->name!=='VTIMEZONE') {
  1979. $componentType = $component->name;
  1980. $uid = (string)$component->UID;
  1981. break;
  1982. }
  1983. }
  1984. if (!$componentType) {
  1985. throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
  1986. }
  1987. if ($componentType === 'VEVENT' && $component->DTSTART) {
  1988. $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
  1989. // Finding the last occurrence is a bit harder
  1990. if (!isset($component->RRULE)) {
  1991. if (isset($component->DTEND)) {
  1992. $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
  1993. } elseif (isset($component->DURATION)) {
  1994. $endDate = clone $component->DTSTART->getDateTime();
  1995. $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
  1996. $lastOccurrence = $endDate->getTimeStamp();
  1997. } elseif (!$component->DTSTART->hasTime()) {
  1998. $endDate = clone $component->DTSTART->getDateTime();
  1999. $endDate->modify('+1 day');
  2000. $lastOccurrence = $endDate->getTimeStamp();
  2001. } else {
  2002. $lastOccurrence = $firstOccurrence;
  2003. }
  2004. } else {
  2005. $it = new EventIterator($vObject, (string)$component->UID);
  2006. $maxDate = new DateTime(self::MAX_DATE);
  2007. if ($it->isInfinite()) {
  2008. $lastOccurrence = $maxDate->getTimestamp();
  2009. } else {
  2010. $end = $it->getDtEnd();
  2011. while($it->valid() && $end < $maxDate) {
  2012. $end = $it->getDtEnd();
  2013. $it->next();
  2014. }
  2015. $lastOccurrence = $end->getTimestamp();
  2016. }
  2017. }
  2018. }
  2019. if ($component->CLASS) {
  2020. $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
  2021. switch ($component->CLASS->getValue()) {
  2022. case 'PUBLIC':
  2023. $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
  2024. break;
  2025. case 'CONFIDENTIAL':
  2026. $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
  2027. break;
  2028. }
  2029. }
  2030. return [
  2031. 'etag' => md5($calendarData),
  2032. 'size' => strlen($calendarData),
  2033. 'componentType' => $componentType,
  2034. 'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
  2035. 'lastOccurence' => $lastOccurrence,
  2036. 'uid' => $uid,
  2037. 'classification' => $classification
  2038. ];
  2039. }
  2040. /**
  2041. * @param $cardData
  2042. * @return bool|string
  2043. */
  2044. private function readBlob($cardData) {
  2045. if (is_resource($cardData)) {
  2046. return stream_get_contents($cardData);
  2047. }
  2048. return $cardData;
  2049. }
  2050. /**
  2051. * @param IShareable $shareable
  2052. * @param array $add
  2053. * @param array $remove
  2054. */
  2055. public function updateShares($shareable, $add, $remove) {
  2056. $calendarId = $shareable->getResourceId();
  2057. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
  2058. '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
  2059. [
  2060. 'calendarId' => $calendarId,
  2061. 'calendarData' => $this->getCalendarById($calendarId),
  2062. 'shares' => $this->getShares($calendarId),
  2063. 'add' => $add,
  2064. 'remove' => $remove,
  2065. ]));
  2066. $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
  2067. }
  2068. /**
  2069. * @param int $resourceId
  2070. * @param int $calendarType
  2071. * @return array
  2072. */
  2073. public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  2074. return $this->calendarSharingBackend->getShares($resourceId);
  2075. }
  2076. /**
  2077. * @param boolean $value
  2078. * @param \OCA\DAV\CalDAV\Calendar $calendar
  2079. * @return string|null
  2080. */
  2081. public function setPublishStatus($value, $calendar) {
  2082. $calendarId = $calendar->getResourceId();
  2083. $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
  2084. '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
  2085. [
  2086. 'calendarId' => $calendarId,
  2087. 'calendarData' => $this->getCalendarById($calendarId),
  2088. 'public' => $value,
  2089. ]));
  2090. $query = $this->db->getQueryBuilder();
  2091. if ($value) {
  2092. $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
  2093. $query->insert('dav_shares')
  2094. ->values([
  2095. 'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
  2096. 'type' => $query->createNamedParameter('calendar'),
  2097. 'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
  2098. 'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
  2099. 'publicuri' => $query->createNamedParameter($publicUri)
  2100. ]);
  2101. $query->execute();
  2102. return $publicUri;
  2103. }
  2104. $query->delete('dav_shares')
  2105. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
  2106. ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
  2107. $query->execute();
  2108. return null;
  2109. }
  2110. /**
  2111. * @param \OCA\DAV\CalDAV\Calendar $calendar
  2112. * @return mixed
  2113. */
  2114. public function getPublishStatus($calendar) {
  2115. $query = $this->db->getQueryBuilder();
  2116. $result = $query->select('publicuri')
  2117. ->from('dav_shares')
  2118. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
  2119. ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
  2120. ->execute();
  2121. $row = $result->fetch();
  2122. $result->closeCursor();
  2123. return $row ? reset($row) : false;
  2124. }
  2125. /**
  2126. * @param int $resourceId
  2127. * @param array $acl
  2128. * @return array
  2129. */
  2130. public function applyShareAcl($resourceId, $acl) {
  2131. return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
  2132. }
  2133. /**
  2134. * update properties table
  2135. *
  2136. * @param int $calendarId
  2137. * @param string $objectUri
  2138. * @param string $calendarData
  2139. * @param int $calendarType
  2140. */
  2141. public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
  2142. $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
  2143. try {
  2144. $vCalendar = $this->readCalendarData($calendarData);
  2145. } catch (\Exception $ex) {
  2146. return;
  2147. }
  2148. $this->purgeProperties($calendarId, $objectId);
  2149. $query = $this->db->getQueryBuilder();
  2150. $query->insert($this->dbObjectPropertiesTable)
  2151. ->values(
  2152. [
  2153. 'calendarid' => $query->createNamedParameter($calendarId),
  2154. 'calendartype' => $query->createNamedParameter($calendarType),
  2155. 'objectid' => $query->createNamedParameter($objectId),
  2156. 'name' => $query->createParameter('name'),
  2157. 'parameter' => $query->createParameter('parameter'),
  2158. 'value' => $query->createParameter('value'),
  2159. ]
  2160. );
  2161. $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
  2162. foreach ($vCalendar->getComponents() as $component) {
  2163. if (!in_array($component->name, $indexComponents)) {
  2164. continue;
  2165. }
  2166. foreach ($component->children() as $property) {
  2167. if (in_array($property->name, self::$indexProperties)) {
  2168. $value = $property->getValue();
  2169. // is this a shitty db?
  2170. if (!$this->db->supports4ByteText()) {
  2171. $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
  2172. }
  2173. $value = mb_substr($value, 0, 254);
  2174. $query->setParameter('name', $property->name);
  2175. $query->setParameter('parameter', null);
  2176. $query->setParameter('value', $value);
  2177. $query->execute();
  2178. }
  2179. if (array_key_exists($property->name, self::$indexParameters)) {
  2180. $parameters = $property->parameters();
  2181. $indexedParametersForProperty = self::$indexParameters[$property->name];
  2182. foreach ($parameters as $key => $value) {
  2183. if (in_array($key, $indexedParametersForProperty)) {
  2184. // is this a shitty db?
  2185. if ($this->db->supports4ByteText()) {
  2186. $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
  2187. }
  2188. $query->setParameter('name', $property->name);
  2189. $query->setParameter('parameter', mb_substr($key, 0, 254));
  2190. $query->setParameter('value', mb_substr($value, 0, 254));
  2191. $query->execute();
  2192. }
  2193. }
  2194. }
  2195. }
  2196. }
  2197. }
  2198. /**
  2199. * deletes all birthday calendars
  2200. */
  2201. public function deleteAllBirthdayCalendars() {
  2202. $query = $this->db->getQueryBuilder();
  2203. $result = $query->select(['id'])->from('calendars')
  2204. ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
  2205. ->execute();
  2206. $ids = $result->fetchAll();
  2207. foreach($ids as $id) {
  2208. $this->deleteCalendar($id['id']);
  2209. }
  2210. }
  2211. /**
  2212. * @param $subscriptionId
  2213. */
  2214. public function purgeAllCachedEventsForSubscription($subscriptionId) {
  2215. $query = $this->db->getQueryBuilder();
  2216. $query->select('uri')
  2217. ->from('calendarobjects')
  2218. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2219. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
  2220. $stmt = $query->execute();
  2221. $uris = [];
  2222. foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
  2223. $uris[] = $row['uri'];
  2224. }
  2225. $stmt->closeCursor();
  2226. $query = $this->db->getQueryBuilder();
  2227. $query->delete('calendarobjects')
  2228. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2229. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2230. ->execute();
  2231. $query->delete('calendarchanges')
  2232. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2233. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2234. ->execute();
  2235. $query->delete($this->dbObjectPropertiesTable)
  2236. ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
  2237. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
  2238. ->execute();
  2239. foreach($uris as $uri) {
  2240. $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
  2241. }
  2242. }
  2243. /**
  2244. * Move a calendar from one user to another
  2245. *
  2246. * @param string $uriName
  2247. * @param string $uriOrigin
  2248. * @param string $uriDestination
  2249. */
  2250. public function moveCalendar($uriName, $uriOrigin, $uriDestination)
  2251. {
  2252. $query = $this->db->getQueryBuilder();
  2253. $query->update('calendars')
  2254. ->set('principaluri', $query->createNamedParameter($uriDestination))
  2255. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
  2256. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
  2257. ->execute();
  2258. }
  2259. /**
  2260. * read VCalendar data into a VCalendar object
  2261. *
  2262. * @param string $objectData
  2263. * @return VCalendar
  2264. */
  2265. protected function readCalendarData($objectData) {
  2266. return Reader::read($objectData);
  2267. }
  2268. /**
  2269. * delete all properties from a given calendar object
  2270. *
  2271. * @param int $calendarId
  2272. * @param int $objectId
  2273. */
  2274. protected function purgeProperties($calendarId, $objectId) {
  2275. $query = $this->db->getQueryBuilder();
  2276. $query->delete($this->dbObjectPropertiesTable)
  2277. ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
  2278. ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
  2279. $query->execute();
  2280. }
  2281. /**
  2282. * get ID from a given calendar object
  2283. *
  2284. * @param int $calendarId
  2285. * @param string $uri
  2286. * @param int $calendarType
  2287. * @return int
  2288. */
  2289. protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
  2290. $query = $this->db->getQueryBuilder();
  2291. $query->select('id')
  2292. ->from('calendarobjects')
  2293. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  2294. ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
  2295. ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
  2296. $result = $query->execute();
  2297. $objectIds = $result->fetch();
  2298. $result->closeCursor();
  2299. if (!isset($objectIds['id'])) {
  2300. throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
  2301. }
  2302. return (int)$objectIds['id'];
  2303. }
  2304. /**
  2305. * return legacy endpoint principal name to new principal name
  2306. *
  2307. * @param $principalUri
  2308. * @param $toV2
  2309. * @return string
  2310. */
  2311. private function convertPrincipal($principalUri, $toV2) {
  2312. if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
  2313. list(, $name) = Uri\split($principalUri);
  2314. if ($toV2 === true) {
  2315. return "principals/users/$name";
  2316. }
  2317. return "principals/$name";
  2318. }
  2319. return $principalUri;
  2320. }
  2321. /**
  2322. * adds information about an owner to the calendar data
  2323. *
  2324. * @param $calendarInfo
  2325. */
  2326. private function addOwnerPrincipal(&$calendarInfo) {
  2327. $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
  2328. $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
  2329. if (isset($calendarInfo[$ownerPrincipalKey])) {
  2330. $uri = $calendarInfo[$ownerPrincipalKey];
  2331. } else {
  2332. $uri = $calendarInfo['principaluri'];
  2333. }
  2334. $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
  2335. if (isset($principalInformation['{DAV:}displayname'])) {
  2336. $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
  2337. }
  2338. }
  2339. }