CalDavBackend.php 87 KB

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