repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
sabre-io/dav
lib/DAV/StringUtil.php
StringUtil.ensureUTF8
public static function ensureUTF8($input) { $encoding = mb_detect_encoding($input, ['UTF-8', 'ISO-8859-1'], true); if ('ISO-8859-1' === $encoding) { return utf8_encode($input); } else { return $input; } }
php
public static function ensureUTF8($input) { $encoding = mb_detect_encoding($input, ['UTF-8', 'ISO-8859-1'], true); if ('ISO-8859-1' === $encoding) { return utf8_encode($input); } else { return $input; } }
[ "public", "static", "function", "ensureUTF8", "(", "$", "input", ")", "{", "$", "encoding", "=", "mb_detect_encoding", "(", "$", "input", ",", "[", "'UTF-8'", ",", "'ISO-8859-1'", "]", ",", "true", ")", ";", "if", "(", "'ISO-8859-1'", "===", "$", "encodi...
This method takes an input string, checks if it's not valid UTF-8 and attempts to convert it to UTF-8 if it's not. Note that currently this can only convert ISO-8859-1 to UTF-8 (latin-1), anything else will likely fail. @param string $input @return string
[ "This", "method", "takes", "an", "input", "string", "checks", "if", "it", "s", "not", "valid", "UTF", "-", "8", "and", "attempts", "to", "convert", "it", "to", "UTF", "-", "8", "if", "it", "s", "not", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/StringUtil.php#L78-L87
train
sabre-io/dav
lib/DAV/Locks/Backend/File.php
File.getData
protected function getData() { if (!file_exists($this->locksFile)) { return []; } // opening up the file, and creating a shared lock $handle = fopen($this->locksFile, 'r'); flock($handle, LOCK_SH); // Reading data until the eof $data = stream_get_contents($handle); // We're all good flock($handle, LOCK_UN); fclose($handle); // Unserializing and checking if the resource file contains data for this file $data = unserialize($data); if (!$data) { return []; } return $data; }
php
protected function getData() { if (!file_exists($this->locksFile)) { return []; } // opening up the file, and creating a shared lock $handle = fopen($this->locksFile, 'r'); flock($handle, LOCK_SH); // Reading data until the eof $data = stream_get_contents($handle); // We're all good flock($handle, LOCK_UN); fclose($handle); // Unserializing and checking if the resource file contains data for this file $data = unserialize($data); if (!$data) { return []; } return $data; }
[ "protected", "function", "getData", "(", ")", "{", "if", "(", "!", "file_exists", "(", "$", "this", "->", "locksFile", ")", ")", "{", "return", "[", "]", ";", "}", "// opening up the file, and creating a shared lock", "$", "handle", "=", "fopen", "(", "$", ...
Loads the lockdata from the filesystem. @return array
[ "Loads", "the", "lockdata", "from", "the", "filesystem", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Locks/Backend/File.php#L141-L165
train
sabre-io/dav
lib/DAV/Locks/Backend/File.php
File.putData
protected function putData(array $newData) { // opening up the file, and creating an exclusive lock $handle = fopen($this->locksFile, 'a+'); flock($handle, LOCK_EX); // We can only truncate and rewind once the lock is acquired. ftruncate($handle, 0); rewind($handle); fwrite($handle, serialize($newData)); flock($handle, LOCK_UN); fclose($handle); }
php
protected function putData(array $newData) { // opening up the file, and creating an exclusive lock $handle = fopen($this->locksFile, 'a+'); flock($handle, LOCK_EX); // We can only truncate and rewind once the lock is acquired. ftruncate($handle, 0); rewind($handle); fwrite($handle, serialize($newData)); flock($handle, LOCK_UN); fclose($handle); }
[ "protected", "function", "putData", "(", "array", "$", "newData", ")", "{", "// opening up the file, and creating an exclusive lock", "$", "handle", "=", "fopen", "(", "$", "this", "->", "locksFile", ",", "'a+'", ")", ";", "flock", "(", "$", "handle", ",", "LO...
Saves the lockdata. @param array $newData
[ "Saves", "the", "lockdata", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Locks/Backend/File.php#L172-L185
train
sabre-io/dav
lib/DAVACL/AbstractPrincipalCollection.php
AbstractPrincipalCollection.getChildren
public function getChildren() { if ($this->disableListing) { throw new DAV\Exception\MethodNotAllowed('Listing members of this collection is disabled'); } $children = []; foreach ($this->principalBackend->getPrincipalsByPrefix($this->principalPrefix) as $principalInfo) { $children[] = $this->getChildForPrincipal($principalInfo); } return $children; }
php
public function getChildren() { if ($this->disableListing) { throw new DAV\Exception\MethodNotAllowed('Listing members of this collection is disabled'); } $children = []; foreach ($this->principalBackend->getPrincipalsByPrefix($this->principalPrefix) as $principalInfo) { $children[] = $this->getChildForPrincipal($principalInfo); } return $children; }
[ "public", "function", "getChildren", "(", ")", "{", "if", "(", "$", "this", "->", "disableListing", ")", "{", "throw", "new", "DAV", "\\", "Exception", "\\", "MethodNotAllowed", "(", "'Listing members of this collection is disabled'", ")", ";", "}", "$", "childr...
Return the list of users. @return array
[ "Return", "the", "list", "of", "users", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/AbstractPrincipalCollection.php#L94-L105
train
sabre-io/dav
lib/DAV/Xml/Property/ResourceType.php
ResourceType.add
public function add($type) { $this->value[] = $type; $this->value = array_unique($this->value); }
php
public function add($type) { $this->value[] = $type; $this->value = array_unique($this->value); }
[ "public", "function", "add", "(", "$", "type", ")", "{", "$", "this", "->", "value", "[", "]", "=", "$", "type", ";", "$", "this", "->", "value", "=", "array_unique", "(", "$", "this", "->", "value", ")", ";", "}" ]
Adds a resourcetype value to this property. @param string $type
[ "Adds", "a", "resourcetype", "value", "to", "this", "property", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Xml/Property/ResourceType.php#L69-L73
train
sabre-io/dav
lib/CalDAV/Schedule/IMipPlugin.php
IMipPlugin.mail
protected function mail($to, $subject, $body, array $headers) { mail($to, $subject, $body, implode("\r\n", $headers)); }
php
protected function mail($to, $subject, $body, array $headers) { mail($to, $subject, $body, implode("\r\n", $headers)); }
[ "protected", "function", "mail", "(", "$", "to", ",", "$", "subject", ",", "$", "body", ",", "array", "$", "headers", ")", "{", "mail", "(", "$", "to", ",", "$", "subject", ",", "$", "body", ",", "implode", "(", "\"\\r\\n\"", ",", "$", "headers", ...
This function is responsible for sending the actual email. @param string $to Recipient email address @param string $subject Subject of the email @param string $body iCalendar body @param array $headers List of headers
[ "This", "function", "is", "responsible", "for", "sending", "the", "actual", "email", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Schedule/IMipPlugin.php#L160-L163
train
sabre-io/dav
lib/DAVACL/Xml/Property/Acl.php
Acl.serializeAce
private function serializeAce(Writer $writer, array $ace) { $writer->startElement('{DAV:}ace'); switch ($ace['principal']) { case '{DAV:}authenticated': $principal = new Principal(Principal::AUTHENTICATED); break; case '{DAV:}unauthenticated': $principal = new Principal(Principal::UNAUTHENTICATED); break; case '{DAV:}all': $principal = new Principal(Principal::ALL); break; default: $principal = new Principal(Principal::HREF, $ace['principal']); break; } $writer->writeElement('{DAV:}principal', $principal); $writer->startElement('{DAV:}grant'); $writer->startElement('{DAV:}privilege'); $writer->writeElement($ace['privilege']); $writer->endElement(); // privilege $writer->endElement(); // grant if (!empty($ace['protected'])) { $writer->writeElement('{DAV:}protected'); } $writer->endElement(); // ace }
php
private function serializeAce(Writer $writer, array $ace) { $writer->startElement('{DAV:}ace'); switch ($ace['principal']) { case '{DAV:}authenticated': $principal = new Principal(Principal::AUTHENTICATED); break; case '{DAV:}unauthenticated': $principal = new Principal(Principal::UNAUTHENTICATED); break; case '{DAV:}all': $principal = new Principal(Principal::ALL); break; default: $principal = new Principal(Principal::HREF, $ace['principal']); break; } $writer->writeElement('{DAV:}principal', $principal); $writer->startElement('{DAV:}grant'); $writer->startElement('{DAV:}privilege'); $writer->writeElement($ace['privilege']); $writer->endElement(); // privilege $writer->endElement(); // grant if (!empty($ace['protected'])) { $writer->writeElement('{DAV:}protected'); } $writer->endElement(); // ace }
[ "private", "function", "serializeAce", "(", "Writer", "$", "writer", ",", "array", "$", "ace", ")", "{", "$", "writer", "->", "startElement", "(", "'{DAV:}ace'", ")", ";", "switch", "(", "$", "ace", "[", "'principal'", "]", ")", "{", "case", "'{DAV:}auth...
Serializes a single access control entry. @param Writer $writer @param array $ace
[ "Serializes", "a", "single", "access", "control", "entry", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Xml/Property/Acl.php#L233-L266
train
sabre-io/dav
lib/DAV/FS/Node.php
Node.getName
public function getName() { if ($this->overrideName) { return $this->overrideName; } list(, $name) = Uri\split($this->path); return $name; }
php
public function getName() { if ($this->overrideName) { return $this->overrideName; } list(, $name) = Uri\split($this->path); return $name; }
[ "public", "function", "getName", "(", ")", "{", "if", "(", "$", "this", "->", "overrideName", ")", "{", "return", "$", "this", "->", "overrideName", ";", "}", "list", "(", ",", "$", "name", ")", "=", "Uri", "\\", "split", "(", "$", "this", "->", ...
Returns the name of the node. @return string
[ "Returns", "the", "name", "of", "the", "node", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/FS/Node.php#L56-L65
train
sabre-io/dav
lib/DAV/FS/Node.php
Node.setName
public function setName($name) { if ($this->overrideName) { throw new Forbidden('This node cannot be renamed'); } list($parentPath) = Uri\split($this->path); list(, $newName) = Uri\split($name); $newPath = $parentPath.'/'.$newName; rename($this->path, $newPath); $this->path = $newPath; }
php
public function setName($name) { if ($this->overrideName) { throw new Forbidden('This node cannot be renamed'); } list($parentPath) = Uri\split($this->path); list(, $newName) = Uri\split($name); $newPath = $parentPath.'/'.$newName; rename($this->path, $newPath); $this->path = $newPath; }
[ "public", "function", "setName", "(", "$", "name", ")", "{", "if", "(", "$", "this", "->", "overrideName", ")", "{", "throw", "new", "Forbidden", "(", "'This node cannot be renamed'", ")", ";", "}", "list", "(", "$", "parentPath", ")", "=", "Uri", "\\", ...
Renames the node. @param string $name The new name
[ "Renames", "the", "node", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/FS/Node.php#L72-L85
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.updateCalendar
public function updateCalendar($calendarId, \Sabre\DAV\PropPatch $propPatch) { if (!is_array($calendarId)) { throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId'); } list($calendarId, $instanceId) = $calendarId; $supportedProperties = array_keys($this->propertyMap); $supportedProperties[] = '{'.CalDAV\Plugin::NS_CALDAV.'}schedule-calendar-transp'; $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId, $instanceId) { $newValues = []; foreach ($mutations as $propertyName => $propertyValue) { switch ($propertyName) { case '{'.CalDAV\Plugin::NS_CALDAV.'}schedule-calendar-transp': $fieldName = 'transparent'; $newValues[$fieldName] = 'transparent' === $propertyValue->getValue(); break; default: $fieldName = $this->propertyMap[$propertyName]; $newValues[$fieldName] = $propertyValue; break; } } $valuesSql = []; foreach ($newValues as $fieldName => $value) { $valuesSql[] = $fieldName.' = ?'; } $stmt = $this->pdo->prepare('UPDATE '.$this->calendarInstancesTableName.' SET '.implode(', ', $valuesSql).' WHERE id = ?'); $newValues['id'] = $instanceId; $stmt->execute(array_values($newValues)); $this->addChange($calendarId, '', 2); return true; }); }
php
public function updateCalendar($calendarId, \Sabre\DAV\PropPatch $propPatch) { if (!is_array($calendarId)) { throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId'); } list($calendarId, $instanceId) = $calendarId; $supportedProperties = array_keys($this->propertyMap); $supportedProperties[] = '{'.CalDAV\Plugin::NS_CALDAV.'}schedule-calendar-transp'; $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId, $instanceId) { $newValues = []; foreach ($mutations as $propertyName => $propertyValue) { switch ($propertyName) { case '{'.CalDAV\Plugin::NS_CALDAV.'}schedule-calendar-transp': $fieldName = 'transparent'; $newValues[$fieldName] = 'transparent' === $propertyValue->getValue(); break; default: $fieldName = $this->propertyMap[$propertyName]; $newValues[$fieldName] = $propertyValue; break; } } $valuesSql = []; foreach ($newValues as $fieldName => $value) { $valuesSql[] = $fieldName.' = ?'; } $stmt = $this->pdo->prepare('UPDATE '.$this->calendarInstancesTableName.' SET '.implode(', ', $valuesSql).' WHERE id = ?'); $newValues['id'] = $instanceId; $stmt->execute(array_values($newValues)); $this->addChange($calendarId, '', 2); return true; }); }
[ "public", "function", "updateCalendar", "(", "$", "calendarId", ",", "\\", "Sabre", "\\", "DAV", "\\", "PropPatch", "$", "propPatch", ")", "{", "if", "(", "!", "is_array", "(", "$", "calendarId", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentExcepti...
Updates properties for a calendar. The list of mutations is stored in a Sabre\DAV\PropPatch object. To do the actual updates, you must tell this object which properties you're going to process with the handle() method. Calling the handle method is like telling the PropPatch object "I promise I can handle updating this property". Read the PropPatch documentation for more info and examples. @param mixed $calendarId @param \Sabre\DAV\PropPatch $propPatch
[ "Updates", "properties", "for", "a", "calendar", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L296-L333
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.createCalendarObject
public function createCalendarObject($calendarId, $objectUri, $calendarData) { if (!is_array($calendarId)) { throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId'); } list($calendarId, $instanceId) = $calendarId; $extraData = $this->getDenormalizedData($calendarData); $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarObjectTableName.' (calendarid, uri, calendardata, lastmodified, etag, size, componenttype, firstoccurence, lastoccurence, uid) VALUES (?,?,?,?,?,?,?,?,?,?)'); $stmt->execute([ $calendarId, $objectUri, $calendarData, time(), $extraData['etag'], $extraData['size'], $extraData['componentType'], $extraData['firstOccurence'], $extraData['lastOccurence'], $extraData['uid'], ]); $this->addChange($calendarId, $objectUri, 1); return '"'.$extraData['etag'].'"'; }
php
public function createCalendarObject($calendarId, $objectUri, $calendarData) { if (!is_array($calendarId)) { throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId'); } list($calendarId, $instanceId) = $calendarId; $extraData = $this->getDenormalizedData($calendarData); $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarObjectTableName.' (calendarid, uri, calendardata, lastmodified, etag, size, componenttype, firstoccurence, lastoccurence, uid) VALUES (?,?,?,?,?,?,?,?,?,?)'); $stmt->execute([ $calendarId, $objectUri, $calendarData, time(), $extraData['etag'], $extraData['size'], $extraData['componentType'], $extraData['firstOccurence'], $extraData['lastOccurence'], $extraData['uid'], ]); $this->addChange($calendarId, $objectUri, 1); return '"'.$extraData['etag'].'"'; }
[ "public", "function", "createCalendarObject", "(", "$", "calendarId", ",", "$", "objectUri", ",", "$", "calendarData", ")", "{", "if", "(", "!", "is_array", "(", "$", "calendarId", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The v...
Creates a new calendar object. The object uri is only the basename, or filename and not a full path. It is possible return an etag from this function, which will be used in the response to this PUT request. Note that the ETag must be surrounded by double-quotes. However, you should only really return this ETag if you don't mangle the calendar-data. If the result of a subsequent GET to this object is not the exact same as this request body, you should omit the ETag. @param mixed $calendarId @param string $objectUri @param string $calendarData @return string|null
[ "Creates", "a", "new", "calendar", "object", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L542-L567
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.getDenormalizedData
protected function getDenormalizedData($calendarData) { $vObject = VObject\Reader::read($calendarData); $componentType = null; $component = null; $firstOccurence = null; $lastOccurence = null; $uid = null; foreach ($vObject->getComponents() as $component) { if ('VTIMEZONE' !== $component->name) { $componentType = $component->name; $uid = (string) $component->UID; break; } } if (!$componentType) { throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component'); } if ('VEVENT' === $componentType) { $firstOccurence = $component->DTSTART->getDateTime()->getTimeStamp(); // Finding the last occurence is a bit harder if (!isset($component->RRULE)) { if (isset($component->DTEND)) { $lastOccurence = $component->DTEND->getDateTime()->getTimeStamp(); } elseif (isset($component->DURATION)) { $endDate = clone $component->DTSTART->getDateTime(); $endDate = $endDate->add(VObject\DateTimeParser::parse($component->DURATION->getValue())); $lastOccurence = $endDate->getTimeStamp(); } elseif (!$component->DTSTART->hasTime()) { $endDate = clone $component->DTSTART->getDateTime(); $endDate = $endDate->modify('+1 day'); $lastOccurence = $endDate->getTimeStamp(); } else { $lastOccurence = $firstOccurence; } } else { $it = new VObject\Recur\EventIterator($vObject, (string) $component->UID); $maxDate = new \DateTime(self::MAX_DATE); if ($it->isInfinite()) { $lastOccurence = $maxDate->getTimeStamp(); } else { $end = $it->getDtEnd(); while ($it->valid() && $end < $maxDate) { $end = $it->getDtEnd(); $it->next(); } $lastOccurence = $end->getTimeStamp(); } } // Ensure Occurence values are positive if ($firstOccurence < 0) { $firstOccurence = 0; } if ($lastOccurence < 0) { $lastOccurence = 0; } } // Destroy circular references to PHP will GC the object. $vObject->destroy(); return [ 'etag' => md5($calendarData), 'size' => strlen($calendarData), 'componentType' => $componentType, 'firstOccurence' => $firstOccurence, 'lastOccurence' => $lastOccurence, 'uid' => $uid, ]; }
php
protected function getDenormalizedData($calendarData) { $vObject = VObject\Reader::read($calendarData); $componentType = null; $component = null; $firstOccurence = null; $lastOccurence = null; $uid = null; foreach ($vObject->getComponents() as $component) { if ('VTIMEZONE' !== $component->name) { $componentType = $component->name; $uid = (string) $component->UID; break; } } if (!$componentType) { throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component'); } if ('VEVENT' === $componentType) { $firstOccurence = $component->DTSTART->getDateTime()->getTimeStamp(); // Finding the last occurence is a bit harder if (!isset($component->RRULE)) { if (isset($component->DTEND)) { $lastOccurence = $component->DTEND->getDateTime()->getTimeStamp(); } elseif (isset($component->DURATION)) { $endDate = clone $component->DTSTART->getDateTime(); $endDate = $endDate->add(VObject\DateTimeParser::parse($component->DURATION->getValue())); $lastOccurence = $endDate->getTimeStamp(); } elseif (!$component->DTSTART->hasTime()) { $endDate = clone $component->DTSTART->getDateTime(); $endDate = $endDate->modify('+1 day'); $lastOccurence = $endDate->getTimeStamp(); } else { $lastOccurence = $firstOccurence; } } else { $it = new VObject\Recur\EventIterator($vObject, (string) $component->UID); $maxDate = new \DateTime(self::MAX_DATE); if ($it->isInfinite()) { $lastOccurence = $maxDate->getTimeStamp(); } else { $end = $it->getDtEnd(); while ($it->valid() && $end < $maxDate) { $end = $it->getDtEnd(); $it->next(); } $lastOccurence = $end->getTimeStamp(); } } // Ensure Occurence values are positive if ($firstOccurence < 0) { $firstOccurence = 0; } if ($lastOccurence < 0) { $lastOccurence = 0; } } // Destroy circular references to PHP will GC the object. $vObject->destroy(); return [ 'etag' => md5($calendarData), 'size' => strlen($calendarData), 'componentType' => $componentType, 'firstOccurence' => $firstOccurence, 'lastOccurence' => $lastOccurence, 'uid' => $uid, ]; }
[ "protected", "function", "getDenormalizedData", "(", "$", "calendarData", ")", "{", "$", "vObject", "=", "VObject", "\\", "Reader", "::", "read", "(", "$", "calendarData", ")", ";", "$", "componentType", "=", "null", ";", "$", "component", "=", "null", ";"...
Parses some information from calendar objects, used for optimized calendar-queries. Returns an array with the following keys: * etag - An md5 checksum of the object without the quotes. * size - Size of the object in bytes * componentType - VEVENT, VTODO or VJOURNAL * firstOccurence * lastOccurence * uid - value of the UID property @param string $calendarData @return array
[ "Parses", "some", "information", "from", "calendar", "objects", "used", "for", "optimized", "calendar", "-", "queries", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L621-L691
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.getChangesForCalendar
public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) { if (!is_array($calendarId)) { throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId'); } list($calendarId, $instanceId) = $calendarId; // Current synctoken $stmt = $this->pdo->prepare('SELECT synctoken FROM '.$this->calendarTableName.' WHERE id = ?'); $stmt->execute([$calendarId]); $currentToken = $stmt->fetchColumn(0); if (is_null($currentToken)) { return null; } $result = [ 'syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => [], ]; if ($syncToken) { $query = 'SELECT uri, operation FROM '.$this->calendarChangesTableName.' WHERE synctoken >= ? AND synctoken < ? AND calendarid = ? ORDER BY synctoken'; if ($limit > 0) { $query .= ' LIMIT '.(int) $limit; } // Fetching all changes $stmt = $this->pdo->prepare($query); $stmt->execute([$syncToken, $currentToken, $calendarId]); $changes = []; // This loop ensures that any duplicates are overwritten, only the // last change on a node is relevant. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $changes[$row['uri']] = $row['operation']; } foreach ($changes as $uri => $operation) { switch ($operation) { case 1: $result['added'][] = $uri; break; case 2: $result['modified'][] = $uri; break; case 3: $result['deleted'][] = $uri; break; } } } else { // No synctoken supplied, this is the initial sync. $query = 'SELECT uri FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?'; $stmt = $this->pdo->prepare($query); $stmt->execute([$calendarId]); $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN); } return $result; }
php
public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null) { if (!is_array($calendarId)) { throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId'); } list($calendarId, $instanceId) = $calendarId; // Current synctoken $stmt = $this->pdo->prepare('SELECT synctoken FROM '.$this->calendarTableName.' WHERE id = ?'); $stmt->execute([$calendarId]); $currentToken = $stmt->fetchColumn(0); if (is_null($currentToken)) { return null; } $result = [ 'syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => [], ]; if ($syncToken) { $query = 'SELECT uri, operation FROM '.$this->calendarChangesTableName.' WHERE synctoken >= ? AND synctoken < ? AND calendarid = ? ORDER BY synctoken'; if ($limit > 0) { $query .= ' LIMIT '.(int) $limit; } // Fetching all changes $stmt = $this->pdo->prepare($query); $stmt->execute([$syncToken, $currentToken, $calendarId]); $changes = []; // This loop ensures that any duplicates are overwritten, only the // last change on a node is relevant. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $changes[$row['uri']] = $row['operation']; } foreach ($changes as $uri => $operation) { switch ($operation) { case 1: $result['added'][] = $uri; break; case 2: $result['modified'][] = $uri; break; case 3: $result['deleted'][] = $uri; break; } } } else { // No synctoken supplied, this is the initial sync. $query = 'SELECT uri FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?'; $stmt = $this->pdo->prepare($query); $stmt->execute([$calendarId]); $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN); } return $result; }
[ "public", "function", "getChangesForCalendar", "(", "$", "calendarId", ",", "$", "syncToken", ",", "$", "syncLevel", ",", "$", "limit", "=", "null", ")", "{", "if", "(", "!", "is_array", "(", "$", "calendarId", ")", ")", "{", "throw", "new", "\\", "Inv...
The getChanges method returns all the changes that have happened, since the specified syncToken in the specified calendar. This function should return an array, such as the following: [ 'syncToken' => 'The current synctoken', 'added' => [ 'new.txt', ], 'modified' => [ 'modified.txt', ], 'deleted' => [ 'foo.php.bak', 'old.txt' ] ]; The returned syncToken property should reflect the *current* syncToken of the calendar, as reported in the {http://sabredav.org/ns}sync-token property this is needed here too, to ensure the operation is atomic. If the $syncToken argument is specified as null, this is an initial sync, and all members should be reported. The modified property is an array of nodenames that have changed since the last token. The deleted property is an array with nodenames, that have been deleted from collection. The $syncLevel argument is basically the 'depth' of the report. If it's 1, you only have to report changes that happened only directly in immediate descendants. If it's 2, it should also include changes from the nodes below the child collections. (grandchildren) The $limit argument allows a client to specify how many results should be returned at most. If the limit is not specified, it should be treated as infinite. If the limit (infinite or not) is higher than you're willing to return, you should throw a Sabre\DAV\Exception\TooMuchMatches() exception. If the syncToken is expired (due to data cleanup) or unknown, you must return null. The limit is 'suggestive'. You are free to ignore it. @param mixed $calendarId @param string $syncToken @param int $syncLevel @param int $limit @return array
[ "The", "getChanges", "method", "returns", "all", "the", "changes", "that", "have", "happened", "since", "the", "specified", "syncToken", "in", "the", "specified", "calendar", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L944-L1008
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.addChange
protected function addChange($calendarId, $objectUri, $operation) { $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarChangesTableName.' (uri, synctoken, calendarid, operation) SELECT ?, synctoken, ?, ? FROM '.$this->calendarTableName.' WHERE id = ?'); $stmt->execute([ $objectUri, $calendarId, $operation, $calendarId, ]); $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET synctoken = synctoken + 1 WHERE id = ?'); $stmt->execute([ $calendarId, ]); }
php
protected function addChange($calendarId, $objectUri, $operation) { $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarChangesTableName.' (uri, synctoken, calendarid, operation) SELECT ?, synctoken, ?, ? FROM '.$this->calendarTableName.' WHERE id = ?'); $stmt->execute([ $objectUri, $calendarId, $operation, $calendarId, ]); $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET synctoken = synctoken + 1 WHERE id = ?'); $stmt->execute([ $calendarId, ]); }
[ "protected", "function", "addChange", "(", "$", "calendarId", ",", "$", "objectUri", ",", "$", "operation", ")", "{", "$", "stmt", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "'INSERT INTO '", ".", "$", "this", "->", "calendarChangesTableName", "....
Adds a change record to the calendarchanges table. @param mixed $calendarId @param string $objectUri @param int $operation 1 = add, 2 = modify, 3 = delete
[ "Adds", "a", "change", "record", "to", "the", "calendarchanges", "table", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L1017-L1030
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.getSubscriptionsForUser
public function getSubscriptionsForUser($principalUri) { $fields = array_values($this->subscriptionPropertyMap); $fields[] = 'id'; $fields[] = 'uri'; $fields[] = 'source'; $fields[] = 'principaluri'; $fields[] = 'lastmodified'; // Making fields a comma-delimited list $fields = implode(', ', $fields); $stmt = $this->pdo->prepare('SELECT '.$fields.' FROM '.$this->calendarSubscriptionsTableName.' WHERE principaluri = ? ORDER BY calendarorder ASC'); $stmt->execute([$principalUri]); $subscriptions = []; while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $subscription = [ 'id' => $row['id'], 'uri' => $row['uri'], 'principaluri' => $row['principaluri'], 'source' => $row['source'], 'lastmodified' => $row['lastmodified'], '{'.CalDAV\Plugin::NS_CALDAV.'}supported-calendar-component-set' => new CalDAV\Xml\Property\SupportedCalendarComponentSet(['VTODO', 'VEVENT']), ]; foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) { if (!is_null($row[$dbName])) { $subscription[$xmlName] = $row[$dbName]; } } $subscriptions[] = $subscription; } return $subscriptions; }
php
public function getSubscriptionsForUser($principalUri) { $fields = array_values($this->subscriptionPropertyMap); $fields[] = 'id'; $fields[] = 'uri'; $fields[] = 'source'; $fields[] = 'principaluri'; $fields[] = 'lastmodified'; // Making fields a comma-delimited list $fields = implode(', ', $fields); $stmt = $this->pdo->prepare('SELECT '.$fields.' FROM '.$this->calendarSubscriptionsTableName.' WHERE principaluri = ? ORDER BY calendarorder ASC'); $stmt->execute([$principalUri]); $subscriptions = []; while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $subscription = [ 'id' => $row['id'], 'uri' => $row['uri'], 'principaluri' => $row['principaluri'], 'source' => $row['source'], 'lastmodified' => $row['lastmodified'], '{'.CalDAV\Plugin::NS_CALDAV.'}supported-calendar-component-set' => new CalDAV\Xml\Property\SupportedCalendarComponentSet(['VTODO', 'VEVENT']), ]; foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) { if (!is_null($row[$dbName])) { $subscription[$xmlName] = $row[$dbName]; } } $subscriptions[] = $subscription; } return $subscriptions; }
[ "public", "function", "getSubscriptionsForUser", "(", "$", "principalUri", ")", "{", "$", "fields", "=", "array_values", "(", "$", "this", "->", "subscriptionPropertyMap", ")", ";", "$", "fields", "[", "]", "=", "'id'", ";", "$", "fields", "[", "]", "=", ...
Returns a list of subscriptions for a principal. Every subscription is an array with the following keys: * id, a unique id that will be used by other functions to modify the subscription. This can be the same as the uri or a database key. * uri. This is just the 'base uri' or 'filename' of the subscription. * principaluri. The owner of the subscription. Almost always the same as principalUri passed to this method. * source. Url to the actual feed Furthermore, all the subscription info must be returned too: 1. {DAV:}displayname 2. {http://apple.com/ns/ical/}refreshrate 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos should not be stripped). 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms should not be stripped). 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if attachments should not be stripped). 7. {http://apple.com/ns/ical/}calendar-color 8. {http://apple.com/ns/ical/}calendar-order 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set (should just be an instance of Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of default components). @param string $principalUri @return array
[ "Returns", "a", "list", "of", "subscriptions", "for", "a", "principal", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L1064-L1100
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.createSubscription
public function createSubscription($principalUri, $uri, array $properties) { $fieldNames = [ 'principaluri', 'uri', 'source', 'lastmodified', ]; if (!isset($properties['{http://calendarserver.org/ns/}source'])) { throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions'); } $values = [ ':principaluri' => $principalUri, ':uri' => $uri, ':source' => $properties['{http://calendarserver.org/ns/}source']->getHref(), ':lastmodified' => time(), ]; foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) { if (isset($properties[$xmlName])) { $values[':'.$dbName] = $properties[$xmlName]; $fieldNames[] = $dbName; } } $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarSubscriptionsTableName.' ('.implode(', ', $fieldNames).') VALUES ('.implode(', ', array_keys($values)).')'); $stmt->execute($values); return $this->pdo->lastInsertId( $this->calendarSubscriptionsTableName.'_id_seq' ); }
php
public function createSubscription($principalUri, $uri, array $properties) { $fieldNames = [ 'principaluri', 'uri', 'source', 'lastmodified', ]; if (!isset($properties['{http://calendarserver.org/ns/}source'])) { throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions'); } $values = [ ':principaluri' => $principalUri, ':uri' => $uri, ':source' => $properties['{http://calendarserver.org/ns/}source']->getHref(), ':lastmodified' => time(), ]; foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) { if (isset($properties[$xmlName])) { $values[':'.$dbName] = $properties[$xmlName]; $fieldNames[] = $dbName; } } $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarSubscriptionsTableName.' ('.implode(', ', $fieldNames).') VALUES ('.implode(', ', array_keys($values)).')'); $stmt->execute($values); return $this->pdo->lastInsertId( $this->calendarSubscriptionsTableName.'_id_seq' ); }
[ "public", "function", "createSubscription", "(", "$", "principalUri", ",", "$", "uri", ",", "array", "$", "properties", ")", "{", "$", "fieldNames", "=", "[", "'principaluri'", ",", "'uri'", ",", "'source'", ",", "'lastmodified'", ",", "]", ";", "if", "(",...
Creates a new subscription for a principal. If the creation was a success, an id must be returned that can be used to reference this subscription in other methods, such as updateSubscription. @param string $principalUri @param string $uri @param array $properties @return mixed
[ "Creates", "a", "new", "subscription", "for", "a", "principal", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L1114-L1147
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.updateSubscription
public function updateSubscription($subscriptionId, DAV\PropPatch $propPatch) { $supportedProperties = array_keys($this->subscriptionPropertyMap); $supportedProperties[] = '{http://calendarserver.org/ns/}source'; $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) { $newValues = []; foreach ($mutations as $propertyName => $propertyValue) { if ('{http://calendarserver.org/ns/}source' === $propertyName) { $newValues['source'] = $propertyValue->getHref(); } else { $fieldName = $this->subscriptionPropertyMap[$propertyName]; $newValues[$fieldName] = $propertyValue; } } // Now we're generating the sql query. $valuesSql = []; foreach ($newValues as $fieldName => $value) { $valuesSql[] = $fieldName.' = ?'; } $stmt = $this->pdo->prepare('UPDATE '.$this->calendarSubscriptionsTableName.' SET '.implode(', ', $valuesSql).', lastmodified = ? WHERE id = ?'); $newValues['lastmodified'] = time(); $newValues['id'] = $subscriptionId; $stmt->execute(array_values($newValues)); return true; }); }
php
public function updateSubscription($subscriptionId, DAV\PropPatch $propPatch) { $supportedProperties = array_keys($this->subscriptionPropertyMap); $supportedProperties[] = '{http://calendarserver.org/ns/}source'; $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) { $newValues = []; foreach ($mutations as $propertyName => $propertyValue) { if ('{http://calendarserver.org/ns/}source' === $propertyName) { $newValues['source'] = $propertyValue->getHref(); } else { $fieldName = $this->subscriptionPropertyMap[$propertyName]; $newValues[$fieldName] = $propertyValue; } } // Now we're generating the sql query. $valuesSql = []; foreach ($newValues as $fieldName => $value) { $valuesSql[] = $fieldName.' = ?'; } $stmt = $this->pdo->prepare('UPDATE '.$this->calendarSubscriptionsTableName.' SET '.implode(', ', $valuesSql).', lastmodified = ? WHERE id = ?'); $newValues['lastmodified'] = time(); $newValues['id'] = $subscriptionId; $stmt->execute(array_values($newValues)); return true; }); }
[ "public", "function", "updateSubscription", "(", "$", "subscriptionId", ",", "DAV", "\\", "PropPatch", "$", "propPatch", ")", "{", "$", "supportedProperties", "=", "array_keys", "(", "$", "this", "->", "subscriptionPropertyMap", ")", ";", "$", "supportedProperties...
Updates a subscription. The list of mutations is stored in a Sabre\DAV\PropPatch object. To do the actual updates, you must tell this object which properties you're going to process with the handle() method. Calling the handle method is like telling the PropPatch object "I promise I can handle updating this property". Read the PropPatch documentation for more info and examples. @param mixed $subscriptionId @param \Sabre\DAV\PropPatch $propPatch
[ "Updates", "a", "subscription", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L1164-L1194
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.getSchedulingObject
public function getSchedulingObject($principalUri, $objectUri) { $stmt = $this->pdo->prepare('SELECT uri, calendardata, lastmodified, etag, size FROM '.$this->schedulingObjectTableName.' WHERE principaluri = ? AND uri = ?'); $stmt->execute([$principalUri, $objectUri]); $row = $stmt->fetch(\PDO::FETCH_ASSOC); if (!$row) { return null; } return [ 'uri' => $row['uri'], 'calendardata' => $row['calendardata'], 'lastmodified' => $row['lastmodified'], 'etag' => '"'.$row['etag'].'"', 'size' => (int) $row['size'], ]; }
php
public function getSchedulingObject($principalUri, $objectUri) { $stmt = $this->pdo->prepare('SELECT uri, calendardata, lastmodified, etag, size FROM '.$this->schedulingObjectTableName.' WHERE principaluri = ? AND uri = ?'); $stmt->execute([$principalUri, $objectUri]); $row = $stmt->fetch(\PDO::FETCH_ASSOC); if (!$row) { return null; } return [ 'uri' => $row['uri'], 'calendardata' => $row['calendardata'], 'lastmodified' => $row['lastmodified'], 'etag' => '"'.$row['etag'].'"', 'size' => (int) $row['size'], ]; }
[ "public", "function", "getSchedulingObject", "(", "$", "principalUri", ",", "$", "objectUri", ")", "{", "$", "stmt", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "'SELECT uri, calendardata, lastmodified, etag, size FROM '", ".", "$", "this", "->", "schedul...
Returns a single scheduling object. The returned array should contain the following elements: * uri - A unique basename for the object. This will be used to construct a full uri. * calendardata - The iCalendar object * lastmodified - The last modification date. Can be an int for a unix timestamp, or a PHP DateTime object. * etag - A unique token that must change if the object changed. * size - The size of the object, in bytes. @param string $principalUri @param string $objectUri @return array
[ "Returns", "a", "single", "scheduling", "object", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L1224-L1241
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.getSchedulingObjects
public function getSchedulingObjects($principalUri) { $stmt = $this->pdo->prepare('SELECT id, calendardata, uri, lastmodified, etag, size FROM '.$this->schedulingObjectTableName.' WHERE principaluri = ?'); $stmt->execute([$principalUri]); $result = []; foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) { $result[] = [ 'calendardata' => $row['calendardata'], 'uri' => $row['uri'], 'lastmodified' => $row['lastmodified'], 'etag' => '"'.$row['etag'].'"', 'size' => (int) $row['size'], ]; } return $result; }
php
public function getSchedulingObjects($principalUri) { $stmt = $this->pdo->prepare('SELECT id, calendardata, uri, lastmodified, etag, size FROM '.$this->schedulingObjectTableName.' WHERE principaluri = ?'); $stmt->execute([$principalUri]); $result = []; foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) { $result[] = [ 'calendardata' => $row['calendardata'], 'uri' => $row['uri'], 'lastmodified' => $row['lastmodified'], 'etag' => '"'.$row['etag'].'"', 'size' => (int) $row['size'], ]; } return $result; }
[ "public", "function", "getSchedulingObjects", "(", "$", "principalUri", ")", "{", "$", "stmt", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "'SELECT id, calendardata, uri, lastmodified, etag, size FROM '", ".", "$", "this", "->", "schedulingObjectTableName", "...
Returns all scheduling objects for the inbox collection. These objects should be returned as an array. Every item in the array should follow the same structure as returned from getSchedulingObject. The main difference is that 'calendardata' is optional. @param string $principalUri @return array
[ "Returns", "all", "scheduling", "objects", "for", "the", "inbox", "collection", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L1255-L1272
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.deleteSchedulingObject
public function deleteSchedulingObject($principalUri, $objectUri) { $stmt = $this->pdo->prepare('DELETE FROM '.$this->schedulingObjectTableName.' WHERE principaluri = ? AND uri = ?'); $stmt->execute([$principalUri, $objectUri]); }
php
public function deleteSchedulingObject($principalUri, $objectUri) { $stmt = $this->pdo->prepare('DELETE FROM '.$this->schedulingObjectTableName.' WHERE principaluri = ? AND uri = ?'); $stmt->execute([$principalUri, $objectUri]); }
[ "public", "function", "deleteSchedulingObject", "(", "$", "principalUri", ",", "$", "objectUri", ")", "{", "$", "stmt", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "'DELETE FROM '", ".", "$", "this", "->", "schedulingObjectTableName", ".", "' WHERE pr...
Deletes a scheduling object. @param string $principalUri @param string $objectUri
[ "Deletes", "a", "scheduling", "object", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L1280-L1284
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.createSchedulingObject
public function createSchedulingObject($principalUri, $objectUri, $objectData) { $stmt = $this->pdo->prepare('INSERT INTO '.$this->schedulingObjectTableName.' (principaluri, calendardata, uri, lastmodified, etag, size) VALUES (?, ?, ?, ?, ?, ?)'); $stmt->execute([$principalUri, $objectData, $objectUri, time(), md5($objectData), strlen($objectData)]); }
php
public function createSchedulingObject($principalUri, $objectUri, $objectData) { $stmt = $this->pdo->prepare('INSERT INTO '.$this->schedulingObjectTableName.' (principaluri, calendardata, uri, lastmodified, etag, size) VALUES (?, ?, ?, ?, ?, ?)'); $stmt->execute([$principalUri, $objectData, $objectUri, time(), md5($objectData), strlen($objectData)]); }
[ "public", "function", "createSchedulingObject", "(", "$", "principalUri", ",", "$", "objectUri", ",", "$", "objectData", ")", "{", "$", "stmt", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "'INSERT INTO '", ".", "$", "this", "->", "schedulingObjectTa...
Creates a new scheduling object. This should land in a users' inbox. @param string $principalUri @param string $objectUri @param string $objectData
[ "Creates", "a", "new", "scheduling", "object", ".", "This", "should", "land", "in", "a", "users", "inbox", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L1293-L1297
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.updateInvites
public function updateInvites($calendarId, array $sharees) { if (!is_array($calendarId)) { throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId'); } $currentInvites = $this->getInvites($calendarId); list($calendarId, $instanceId) = $calendarId; $removeStmt = $this->pdo->prepare('DELETE FROM '.$this->calendarInstancesTableName.' WHERE calendarid = ? AND share_href = ? AND access IN (2,3)'); $updateStmt = $this->pdo->prepare('UPDATE '.$this->calendarInstancesTableName.' SET access = ?, share_displayname = ?, share_invitestatus = ? WHERE calendarid = ? AND share_href = ?'); $insertStmt = $this->pdo->prepare(' INSERT INTO '.$this->calendarInstancesTableName.' ( calendarid, principaluri, access, displayname, uri, description, calendarorder, calendarcolor, timezone, transparent, share_href, share_displayname, share_invitestatus ) SELECT ?, ?, ?, displayname, ?, description, calendarorder, calendarcolor, timezone, 1, ?, ?, ? FROM '.$this->calendarInstancesTableName.' WHERE id = ?'); foreach ($sharees as $sharee) { if (\Sabre\DAV\Sharing\Plugin::ACCESS_NOACCESS === $sharee->access) { // if access was set no NOACCESS, it means access for an // existing sharee was removed. $removeStmt->execute([$calendarId, $sharee->href]); continue; } if (is_null($sharee->principal)) { // If the server could not determine the principal automatically, // we will mark the invite status as invalid. $sharee->inviteStatus = \Sabre\DAV\Sharing\Plugin::INVITE_INVALID; } else { // Because sabre/dav does not yet have an invitation system, // every invite is automatically accepted for now. $sharee->inviteStatus = \Sabre\DAV\Sharing\Plugin::INVITE_ACCEPTED; } foreach ($currentInvites as $oldSharee) { if ($oldSharee->href === $sharee->href) { // This is an update $sharee->properties = array_merge( $oldSharee->properties, $sharee->properties ); $updateStmt->execute([ $sharee->access, isset($sharee->properties['{DAV:}displayname']) ? $sharee->properties['{DAV:}displayname'] : null, $sharee->inviteStatus ?: $oldSharee->inviteStatus, $calendarId, $sharee->href, ]); continue 2; } } // If we got here, it means it was a new sharee $insertStmt->execute([ $calendarId, $sharee->principal, $sharee->access, \Sabre\DAV\UUIDUtil::getUUID(), $sharee->href, isset($sharee->properties['{DAV:}displayname']) ? $sharee->properties['{DAV:}displayname'] : null, $sharee->inviteStatus ?: \Sabre\DAV\Sharing\Plugin::INVITE_NORESPONSE, $instanceId, ]); } }
php
public function updateInvites($calendarId, array $sharees) { if (!is_array($calendarId)) { throw new \InvalidArgumentException('The value passed to $calendarId is expected to be an array with a calendarId and an instanceId'); } $currentInvites = $this->getInvites($calendarId); list($calendarId, $instanceId) = $calendarId; $removeStmt = $this->pdo->prepare('DELETE FROM '.$this->calendarInstancesTableName.' WHERE calendarid = ? AND share_href = ? AND access IN (2,3)'); $updateStmt = $this->pdo->prepare('UPDATE '.$this->calendarInstancesTableName.' SET access = ?, share_displayname = ?, share_invitestatus = ? WHERE calendarid = ? AND share_href = ?'); $insertStmt = $this->pdo->prepare(' INSERT INTO '.$this->calendarInstancesTableName.' ( calendarid, principaluri, access, displayname, uri, description, calendarorder, calendarcolor, timezone, transparent, share_href, share_displayname, share_invitestatus ) SELECT ?, ?, ?, displayname, ?, description, calendarorder, calendarcolor, timezone, 1, ?, ?, ? FROM '.$this->calendarInstancesTableName.' WHERE id = ?'); foreach ($sharees as $sharee) { if (\Sabre\DAV\Sharing\Plugin::ACCESS_NOACCESS === $sharee->access) { // if access was set no NOACCESS, it means access for an // existing sharee was removed. $removeStmt->execute([$calendarId, $sharee->href]); continue; } if (is_null($sharee->principal)) { // If the server could not determine the principal automatically, // we will mark the invite status as invalid. $sharee->inviteStatus = \Sabre\DAV\Sharing\Plugin::INVITE_INVALID; } else { // Because sabre/dav does not yet have an invitation system, // every invite is automatically accepted for now. $sharee->inviteStatus = \Sabre\DAV\Sharing\Plugin::INVITE_ACCEPTED; } foreach ($currentInvites as $oldSharee) { if ($oldSharee->href === $sharee->href) { // This is an update $sharee->properties = array_merge( $oldSharee->properties, $sharee->properties ); $updateStmt->execute([ $sharee->access, isset($sharee->properties['{DAV:}displayname']) ? $sharee->properties['{DAV:}displayname'] : null, $sharee->inviteStatus ?: $oldSharee->inviteStatus, $calendarId, $sharee->href, ]); continue 2; } } // If we got here, it means it was a new sharee $insertStmt->execute([ $calendarId, $sharee->principal, $sharee->access, \Sabre\DAV\UUIDUtil::getUUID(), $sharee->href, isset($sharee->properties['{DAV:}displayname']) ? $sharee->properties['{DAV:}displayname'] : null, $sharee->inviteStatus ?: \Sabre\DAV\Sharing\Plugin::INVITE_NORESPONSE, $instanceId, ]); } }
[ "public", "function", "updateInvites", "(", "$", "calendarId", ",", "array", "$", "sharees", ")", "{", "if", "(", "!", "is_array", "(", "$", "calendarId", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The value passed to $calendarId is ...
Updates the list of shares. @param mixed $calendarId @param \Sabre\DAV\Xml\Element\Sharee[] $sharees
[ "Updates", "the", "list", "of", "shares", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L1305-L1396
train
sabre-io/dav
lib/CalDAV/Backend/PDO.php
PDO.getInvites
public function getInvites($calendarId) { if (!is_array($calendarId)) { throw new \InvalidArgumentException('The value passed to getInvites() is expected to be an array with a calendarId and an instanceId'); } list($calendarId, $instanceId) = $calendarId; $query = <<<SQL SELECT principaluri, access, share_href, share_displayname, share_invitestatus FROM {$this->calendarInstancesTableName} WHERE calendarid = ? SQL; $stmt = $this->pdo->prepare($query); $stmt->execute([$calendarId]); $result = []; while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $result[] = new Sharee([ 'href' => isset($row['share_href']) ? $row['share_href'] : \Sabre\HTTP\encodePath($row['principaluri']), 'access' => (int) $row['access'], /// Everyone is always immediately accepted, for now. 'inviteStatus' => (int) $row['share_invitestatus'], 'properties' => !empty($row['share_displayname']) ? ['{DAV:}displayname' => $row['share_displayname']] : [], 'principal' => $row['principaluri'], ]); } return $result; }
php
public function getInvites($calendarId) { if (!is_array($calendarId)) { throw new \InvalidArgumentException('The value passed to getInvites() is expected to be an array with a calendarId and an instanceId'); } list($calendarId, $instanceId) = $calendarId; $query = <<<SQL SELECT principaluri, access, share_href, share_displayname, share_invitestatus FROM {$this->calendarInstancesTableName} WHERE calendarid = ? SQL; $stmt = $this->pdo->prepare($query); $stmt->execute([$calendarId]); $result = []; while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $result[] = new Sharee([ 'href' => isset($row['share_href']) ? $row['share_href'] : \Sabre\HTTP\encodePath($row['principaluri']), 'access' => (int) $row['access'], /// Everyone is always immediately accepted, for now. 'inviteStatus' => (int) $row['share_invitestatus'], 'properties' => !empty($row['share_displayname']) ? ['{DAV:}displayname' => $row['share_displayname']] : [], 'principal' => $row['principaluri'], ]); } return $result; }
[ "public", "function", "getInvites", "(", "$", "calendarId", ")", "{", "if", "(", "!", "is_array", "(", "$", "calendarId", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The value passed to getInvites() is expected to be an array with a calendarI...
Returns the list of people whom a calendar is shared with. Every item in the returned list must be a Sharee object with at least the following properties set: $href $shareAccess $inviteStatus and optionally: $properties @param mixed $calendarId @return \Sabre\DAV\Xml\Element\Sharee[]
[ "Returns", "the", "list", "of", "people", "whom", "a", "calendar", "is", "shared", "with", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Backend/PDO.php#L1414-L1451
train
sabre-io/dav
lib/DAV/PropertyStorage/Backend/PDO.php
PDO.propFind
public function propFind($path, PropFind $propFind) { if (!$propFind->isAllProps() && 0 === count($propFind->get404Properties())) { return; } $query = 'SELECT name, value, valuetype FROM '.$this->tableName.' WHERE path = ?'; $stmt = $this->pdo->prepare($query); $stmt->execute([$path]); while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { if ('resource' === gettype($row['value'])) { $row['value'] = stream_get_contents($row['value']); } switch ($row['valuetype']) { case null: case self::VT_STRING: $propFind->set($row['name'], $row['value']); break; case self::VT_XML: $propFind->set($row['name'], new Complex($row['value'])); break; case self::VT_OBJECT: $propFind->set($row['name'], unserialize($row['value'])); break; } } }
php
public function propFind($path, PropFind $propFind) { if (!$propFind->isAllProps() && 0 === count($propFind->get404Properties())) { return; } $query = 'SELECT name, value, valuetype FROM '.$this->tableName.' WHERE path = ?'; $stmt = $this->pdo->prepare($query); $stmt->execute([$path]); while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { if ('resource' === gettype($row['value'])) { $row['value'] = stream_get_contents($row['value']); } switch ($row['valuetype']) { case null: case self::VT_STRING: $propFind->set($row['name'], $row['value']); break; case self::VT_XML: $propFind->set($row['name'], new Complex($row['value'])); break; case self::VT_OBJECT: $propFind->set($row['name'], unserialize($row['value'])); break; } } }
[ "public", "function", "propFind", "(", "$", "path", ",", "PropFind", "$", "propFind", ")", "{", "if", "(", "!", "$", "propFind", "->", "isAllProps", "(", ")", "&&", "0", "===", "count", "(", "$", "propFind", "->", "get404Properties", "(", ")", ")", "...
Fetches properties for a path. This method received a PropFind object, which contains all the information about the properties that need to be fetched. Usually you would just want to call 'get404Properties' on this object, as this will give you the _exact_ list of properties that need to be fetched, and haven't yet. However, you can also support the 'allprops' property here. In that case, you should check for $propFind->isAllProps(). @param string $path @param PropFind $propFind
[ "Fetches", "properties", "for", "a", "path", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropertyStorage/Backend/PDO.php#L80-L107
train
sabre-io/dav
lib/DAV/PropertyStorage/Backend/PDO.php
PDO.propPatch
public function propPatch($path, PropPatch $propPatch) { $propPatch->handleRemaining(function ($properties) use ($path) { if ('pgsql' === $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME)) { $updateSql = <<<SQL INSERT INTO {$this->tableName} (path, name, valuetype, value) VALUES (:path, :name, :valuetype, :value) ON CONFLICT (path, name) DO UPDATE SET valuetype = :valuetype, value = :value SQL; } else { $updateSql = <<<SQL REPLACE INTO {$this->tableName} (path, name, valuetype, value) VALUES (:path, :name, :valuetype, :value) SQL; } $updateStmt = $this->pdo->prepare($updateSql); $deleteStmt = $this->pdo->prepare('DELETE FROM '.$this->tableName.' WHERE path = ? AND name = ?'); foreach ($properties as $name => $value) { if (!is_null($value)) { if (is_scalar($value)) { $valueType = self::VT_STRING; } elseif ($value instanceof Complex) { $valueType = self::VT_XML; $value = $value->getXml(); } else { $valueType = self::VT_OBJECT; $value = serialize($value); } $updateStmt->bindParam('path', $path, \PDO::PARAM_STR); $updateStmt->bindParam('name', $name, \PDO::PARAM_STR); $updateStmt->bindParam('valuetype', $valueType, \PDO::PARAM_INT); $updateStmt->bindParam('value', $value, \PDO::PARAM_LOB); $updateStmt->execute(); } else { $deleteStmt->execute([$path, $name]); } } return true; }); }
php
public function propPatch($path, PropPatch $propPatch) { $propPatch->handleRemaining(function ($properties) use ($path) { if ('pgsql' === $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME)) { $updateSql = <<<SQL INSERT INTO {$this->tableName} (path, name, valuetype, value) VALUES (:path, :name, :valuetype, :value) ON CONFLICT (path, name) DO UPDATE SET valuetype = :valuetype, value = :value SQL; } else { $updateSql = <<<SQL REPLACE INTO {$this->tableName} (path, name, valuetype, value) VALUES (:path, :name, :valuetype, :value) SQL; } $updateStmt = $this->pdo->prepare($updateSql); $deleteStmt = $this->pdo->prepare('DELETE FROM '.$this->tableName.' WHERE path = ? AND name = ?'); foreach ($properties as $name => $value) { if (!is_null($value)) { if (is_scalar($value)) { $valueType = self::VT_STRING; } elseif ($value instanceof Complex) { $valueType = self::VT_XML; $value = $value->getXml(); } else { $valueType = self::VT_OBJECT; $value = serialize($value); } $updateStmt->bindParam('path', $path, \PDO::PARAM_STR); $updateStmt->bindParam('name', $name, \PDO::PARAM_STR); $updateStmt->bindParam('valuetype', $valueType, \PDO::PARAM_INT); $updateStmt->bindParam('value', $value, \PDO::PARAM_LOB); $updateStmt->execute(); } else { $deleteStmt->execute([$path, $name]); } } return true; }); }
[ "public", "function", "propPatch", "(", "$", "path", ",", "PropPatch", "$", "propPatch", ")", "{", "$", "propPatch", "->", "handleRemaining", "(", "function", "(", "$", "properties", ")", "use", "(", "$", "path", ")", "{", "if", "(", "'pgsql'", "===", ...
Updates properties for a path. This method received a PropPatch object, which contains all the information about the update. Usually you would want to call 'handleRemaining' on this object, to get; a list of all properties that need to be stored. @param string $path @param PropPatch $propPatch
[ "Updates", "properties", "for", "a", "path", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropertyStorage/Backend/PDO.php#L121-L166
train
sabre-io/dav
lib/DAV/PropertyStorage/Backend/PDO.php
PDO.move
public function move($source, $destination) { // I don't know a way to write this all in a single sql query that's // also compatible across db engines, so we're letting PHP do all the // updates. Much slower, but it should still be pretty fast in most // cases. $select = $this->pdo->prepare('SELECT id, path FROM '.$this->tableName.' WHERE path = ? OR path LIKE ?'); $select->execute([$source, $source.'/%']); $update = $this->pdo->prepare('UPDATE '.$this->tableName.' SET path = ? WHERE id = ?'); while ($row = $select->fetch(\PDO::FETCH_ASSOC)) { // Sanity check. SQL may select too many records, such as records // with different cases. if ($row['path'] !== $source && 0 !== strpos($row['path'], $source.'/')) { continue; } $trailingPart = substr($row['path'], strlen($source) + 1); $newPath = $destination; if ($trailingPart) { $newPath .= '/'.$trailingPart; } $update->execute([$newPath, $row['id']]); } }
php
public function move($source, $destination) { // I don't know a way to write this all in a single sql query that's // also compatible across db engines, so we're letting PHP do all the // updates. Much slower, but it should still be pretty fast in most // cases. $select = $this->pdo->prepare('SELECT id, path FROM '.$this->tableName.' WHERE path = ? OR path LIKE ?'); $select->execute([$source, $source.'/%']); $update = $this->pdo->prepare('UPDATE '.$this->tableName.' SET path = ? WHERE id = ?'); while ($row = $select->fetch(\PDO::FETCH_ASSOC)) { // Sanity check. SQL may select too many records, such as records // with different cases. if ($row['path'] !== $source && 0 !== strpos($row['path'], $source.'/')) { continue; } $trailingPart = substr($row['path'], strlen($source) + 1); $newPath = $destination; if ($trailingPart) { $newPath .= '/'.$trailingPart; } $update->execute([$newPath, $row['id']]); } }
[ "public", "function", "move", "(", "$", "source", ",", "$", "destination", ")", "{", "// I don't know a way to write this all in a single sql query that's", "// also compatible across db engines, so we're letting PHP do all the", "// updates. Much slower, but it should still be pretty fast...
This method is called after a successful MOVE. This should be used to migrate all properties from one path to another. Note that entire collections may be moved, so ensure that all properties for children are also moved along. @param string $source @param string $destination
[ "This", "method", "is", "called", "after", "a", "successful", "MOVE", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropertyStorage/Backend/PDO.php#L203-L227
train
sabre-io/dav
lib/DAV/FSExt/Directory.php
Directory.childExists
public function childExists($name) { if ('.' == $name || '..' == $name) { throw new DAV\Exception\Forbidden('Permission denied to . and ..'); } $path = $this->path.'/'.$name; return file_exists($path); }
php
public function childExists($name) { if ('.' == $name || '..' == $name) { throw new DAV\Exception\Forbidden('Permission denied to . and ..'); } $path = $this->path.'/'.$name; return file_exists($path); }
[ "public", "function", "childExists", "(", "$", "name", ")", "{", "if", "(", "'.'", "==", "$", "name", "||", "'..'", "==", "$", "name", ")", "{", "throw", "new", "DAV", "\\", "Exception", "\\", "Forbidden", "(", "'Permission denied to . and ..'", ")", ";"...
Checks if a child exists. @param string $name @return bool
[ "Checks", "if", "a", "child", "exists", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/FSExt/Directory.php#L113-L121
train
sabre-io/dav
lib/DAV/FSExt/Directory.php
Directory.delete
public function delete() { // Deleting all children foreach ($this->getChildren() as $child) { $child->delete(); } // Removing the directory itself rmdir($this->path); return true; }
php
public function delete() { // Deleting all children foreach ($this->getChildren() as $child) { $child->delete(); } // Removing the directory itself rmdir($this->path); return true; }
[ "public", "function", "delete", "(", ")", "{", "// Deleting all children", "foreach", "(", "$", "this", "->", "getChildren", "(", ")", "as", "$", "child", ")", "{", "$", "child", "->", "delete", "(", ")", ";", "}", "// Removing the directory itself", "rmdir"...
Deletes all files in this directory, and then itself. @return bool
[ "Deletes", "all", "files", "in", "this", "directory", "and", "then", "itself", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/FSExt/Directory.php#L149-L160
train
sabre-io/dav
lib/DAV/FSExt/Directory.php
Directory.moveInto
public function moveInto($targetName, $sourcePath, DAV\INode $sourceNode) { // We only support FSExt\Directory or FSExt\File objects, so // anything else we want to quickly reject. if (!$sourceNode instanceof self && !$sourceNode instanceof File) { return false; } // PHP allows us to access protected properties from other objects, as // long as they are defined in a class that has a shared inheritance // with the current class. return rename($sourceNode->path, $this->path.'/'.$targetName); }
php
public function moveInto($targetName, $sourcePath, DAV\INode $sourceNode) { // We only support FSExt\Directory or FSExt\File objects, so // anything else we want to quickly reject. if (!$sourceNode instanceof self && !$sourceNode instanceof File) { return false; } // PHP allows us to access protected properties from other objects, as // long as they are defined in a class that has a shared inheritance // with the current class. return rename($sourceNode->path, $this->path.'/'.$targetName); }
[ "public", "function", "moveInto", "(", "$", "targetName", ",", "$", "sourcePath", ",", "DAV", "\\", "INode", "$", "sourceNode", ")", "{", "// We only support FSExt\\Directory or FSExt\\File objects, so", "// anything else we want to quickly reject.", "if", "(", "!", "$", ...
Moves a node into this collection. It is up to the implementors to: 1. Create the new resource. 2. Remove the old resource. 3. Transfer any properties or other data. Generally you should make very sure that your collection can easily move the move. If you don't, just return false, which will trigger sabre/dav to handle the move itself. If you return true from this function, the assumption is that the move was successful. @param string $targetName new local file/collection name @param string $sourcePath Full path to source node @param DAV\INode $sourceNode Source node itself @return bool
[ "Moves", "a", "node", "into", "this", "collection", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/FSExt/Directory.php#L199-L211
train
sabre-io/dav
lib/DAV/Browser/Plugin.php
Plugin.initialize
public function initialize(DAV\Server $server) { $this->server = $server; $this->server->on('method:GET', [$this, 'httpGetEarly'], 90); $this->server->on('method:GET', [$this, 'httpGet'], 200); $this->server->on('onHTMLActionsPanel', [$this, 'htmlActionsPanel'], 200); if ($this->enablePost) { $this->server->on('method:POST', [$this, 'httpPOST']); } }
php
public function initialize(DAV\Server $server) { $this->server = $server; $this->server->on('method:GET', [$this, 'httpGetEarly'], 90); $this->server->on('method:GET', [$this, 'httpGet'], 200); $this->server->on('onHTMLActionsPanel', [$this, 'htmlActionsPanel'], 200); if ($this->enablePost) { $this->server->on('method:POST', [$this, 'httpPOST']); } }
[ "public", "function", "initialize", "(", "DAV", "\\", "Server", "$", "server", ")", "{", "$", "this", "->", "server", "=", "$", "server", ";", "$", "this", "->", "server", "->", "on", "(", "'method:GET'", ",", "[", "$", "this", ",", "'httpGetEarly'", ...
Initializes the plugin and subscribes to events. @param DAV\Server $server
[ "Initializes", "the", "plugin", "and", "subscribes", "to", "events", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Browser/Plugin.php#L76-L85
train
sabre-io/dav
lib/DAV/Browser/Plugin.php
Plugin.httpGetEarly
public function httpGetEarly(RequestInterface $request, ResponseInterface $response) { $params = $request->getQueryParameters(); if (isset($params['sabreAction']) && 'info' === $params['sabreAction']) { return $this->httpGet($request, $response); } }
php
public function httpGetEarly(RequestInterface $request, ResponseInterface $response) { $params = $request->getQueryParameters(); if (isset($params['sabreAction']) && 'info' === $params['sabreAction']) { return $this->httpGet($request, $response); } }
[ "public", "function", "httpGetEarly", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "params", "=", "$", "request", "->", "getQueryParameters", "(", ")", ";", "if", "(", "isset", "(", "$", "params", "[", ...
This method intercepts GET requests that have ?sabreAction=info appended to the URL. @param RequestInterface $request @param ResponseInterface $response @return bool
[ "This", "method", "intercepts", "GET", "requests", "that", "have", "?sabreAction", "=", "info", "appended", "to", "the", "URL", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Browser/Plugin.php#L96-L102
train
sabre-io/dav
lib/DAV/Browser/Plugin.php
Plugin.httpGet
public function httpGet(RequestInterface $request, ResponseInterface $response) { // We're not using straight-up $_GET, because we want everything to be // unit testable. $getVars = $request->getQueryParameters(); // CSP headers $response->setHeader('Content-Security-Policy', "default-src 'none'; img-src 'self'; style-src 'self'; font-src 'self';"); $sabreAction = isset($getVars['sabreAction']) ? $getVars['sabreAction'] : null; switch ($sabreAction) { case 'asset': // Asset handling, such as images $this->serveAsset(isset($getVars['assetName']) ? $getVars['assetName'] : null); return false; default: case 'info': try { $this->server->tree->getNodeForPath($request->getPath()); } catch (DAV\Exception\NotFound $e) { // We're simply stopping when the file isn't found to not interfere // with other plugins. return; } $response->setStatus(200); $response->setHeader('Content-Type', 'text/html; charset=utf-8'); $response->setBody( $this->generateDirectoryIndex($request->getPath()) ); return false; case 'plugins': $response->setStatus(200); $response->setHeader('Content-Type', 'text/html; charset=utf-8'); $response->setBody( $this->generatePluginListing() ); return false; } }
php
public function httpGet(RequestInterface $request, ResponseInterface $response) { // We're not using straight-up $_GET, because we want everything to be // unit testable. $getVars = $request->getQueryParameters(); // CSP headers $response->setHeader('Content-Security-Policy', "default-src 'none'; img-src 'self'; style-src 'self'; font-src 'self';"); $sabreAction = isset($getVars['sabreAction']) ? $getVars['sabreAction'] : null; switch ($sabreAction) { case 'asset': // Asset handling, such as images $this->serveAsset(isset($getVars['assetName']) ? $getVars['assetName'] : null); return false; default: case 'info': try { $this->server->tree->getNodeForPath($request->getPath()); } catch (DAV\Exception\NotFound $e) { // We're simply stopping when the file isn't found to not interfere // with other plugins. return; } $response->setStatus(200); $response->setHeader('Content-Type', 'text/html; charset=utf-8'); $response->setBody( $this->generateDirectoryIndex($request->getPath()) ); return false; case 'plugins': $response->setStatus(200); $response->setHeader('Content-Type', 'text/html; charset=utf-8'); $response->setBody( $this->generatePluginListing() ); return false; } }
[ "public", "function", "httpGet", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "// We're not using straight-up $_GET, because we want everything to be", "// unit testable.", "$", "getVars", "=", "$", "request", "->", "getQuery...
This method intercepts GET requests to collections and returns the html. @param RequestInterface $request @param ResponseInterface $response @return bool
[ "This", "method", "intercepts", "GET", "requests", "to", "collections", "and", "returns", "the", "html", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Browser/Plugin.php#L112-L158
train
sabre-io/dav
lib/DAV/Browser/Plugin.php
Plugin.httpPOST
public function httpPOST(RequestInterface $request, ResponseInterface $response) { $contentType = $request->getHeader('Content-Type'); list($contentType) = explode(';', $contentType); if ('application/x-www-form-urlencoded' !== $contentType && 'multipart/form-data' !== $contentType) { return; } $postVars = $request->getPostData(); if (!isset($postVars['sabreAction'])) { return; } $uri = $request->getPath(); if ($this->server->emit('onBrowserPostAction', [$uri, $postVars['sabreAction'], $postVars])) { switch ($postVars['sabreAction']) { case 'mkcol': if (isset($postVars['name']) && trim($postVars['name'])) { // Using basename() because we won't allow slashes list(, $folderName) = Uri\split(trim($postVars['name'])); if (isset($postVars['resourceType'])) { $resourceType = explode(',', $postVars['resourceType']); } else { $resourceType = ['{DAV:}collection']; } $properties = []; foreach ($postVars as $varName => $varValue) { // Any _POST variable in clark notation is treated // like a property. if ('{' === $varName[0]) { // PHP will convert any dots to underscores. // This leaves us with no way to differentiate // the two. // Therefore we replace the string *DOT* with a // real dot. * is not allowed in uris so we // should be good. $varName = str_replace('*DOT*', '.', $varName); $properties[$varName] = $varValue; } } $mkCol = new MkCol( $resourceType, $properties ); $this->server->createCollection($uri.'/'.$folderName, $mkCol); } break; // @codeCoverageIgnoreStart case 'put': if ($_FILES) { $file = current($_FILES); } else { break; } list(, $newName) = Uri\split(trim($file['name'])); if (isset($postVars['name']) && trim($postVars['name'])) { $newName = trim($postVars['name']); } // Making sure we only have a 'basename' component list(, $newName) = Uri\split($newName); if (is_uploaded_file($file['tmp_name'])) { $this->server->createFile($uri.'/'.$newName, fopen($file['tmp_name'], 'r')); } break; // @codeCoverageIgnoreEnd } } $response->setHeader('Location', $request->getUrl()); $response->setStatus(302); return false; }
php
public function httpPOST(RequestInterface $request, ResponseInterface $response) { $contentType = $request->getHeader('Content-Type'); list($contentType) = explode(';', $contentType); if ('application/x-www-form-urlencoded' !== $contentType && 'multipart/form-data' !== $contentType) { return; } $postVars = $request->getPostData(); if (!isset($postVars['sabreAction'])) { return; } $uri = $request->getPath(); if ($this->server->emit('onBrowserPostAction', [$uri, $postVars['sabreAction'], $postVars])) { switch ($postVars['sabreAction']) { case 'mkcol': if (isset($postVars['name']) && trim($postVars['name'])) { // Using basename() because we won't allow slashes list(, $folderName) = Uri\split(trim($postVars['name'])); if (isset($postVars['resourceType'])) { $resourceType = explode(',', $postVars['resourceType']); } else { $resourceType = ['{DAV:}collection']; } $properties = []; foreach ($postVars as $varName => $varValue) { // Any _POST variable in clark notation is treated // like a property. if ('{' === $varName[0]) { // PHP will convert any dots to underscores. // This leaves us with no way to differentiate // the two. // Therefore we replace the string *DOT* with a // real dot. * is not allowed in uris so we // should be good. $varName = str_replace('*DOT*', '.', $varName); $properties[$varName] = $varValue; } } $mkCol = new MkCol( $resourceType, $properties ); $this->server->createCollection($uri.'/'.$folderName, $mkCol); } break; // @codeCoverageIgnoreStart case 'put': if ($_FILES) { $file = current($_FILES); } else { break; } list(, $newName) = Uri\split(trim($file['name'])); if (isset($postVars['name']) && trim($postVars['name'])) { $newName = trim($postVars['name']); } // Making sure we only have a 'basename' component list(, $newName) = Uri\split($newName); if (is_uploaded_file($file['tmp_name'])) { $this->server->createFile($uri.'/'.$newName, fopen($file['tmp_name'], 'r')); } break; // @codeCoverageIgnoreEnd } } $response->setHeader('Location', $request->getUrl()); $response->setStatus(302); return false; }
[ "public", "function", "httpPOST", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "contentType", "=", "$", "request", "->", "getHeader", "(", "'Content-Type'", ")", ";", "list", "(", "$", "contentType", ")", ...
Handles POST requests for tree operations. @param RequestInterface $request @param ResponseInterface $response @return bool
[ "Handles", "POST", "requests", "for", "tree", "operations", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Browser/Plugin.php#L168-L249
train
sabre-io/dav
lib/DAV/Browser/Plugin.php
Plugin.generatePluginListing
public function generatePluginListing() { $html = $this->generateHeader('Plugins'); $html .= '<section><h1>Plugins</h1>'; $html .= '<table class="propTable">'; foreach ($this->server->getPlugins() as $plugin) { $info = $plugin->getPluginInfo(); $html .= '<tr><th>'.$info['name'].'</th>'; $html .= '<td>'.$info['description'].'</td>'; $html .= '<td>'; if (isset($info['link']) && $info['link']) { $html .= '<a href="'.$this->escapeHTML($info['link']).'"><span class="oi" data-glyph="book"></span></a>'; } $html .= '</td></tr>'; } $html .= '</table>'; $html .= '</section>'; /* Start of generating actions */ $html .= $this->generateFooter(); return $html; }
php
public function generatePluginListing() { $html = $this->generateHeader('Plugins'); $html .= '<section><h1>Plugins</h1>'; $html .= '<table class="propTable">'; foreach ($this->server->getPlugins() as $plugin) { $info = $plugin->getPluginInfo(); $html .= '<tr><th>'.$info['name'].'</th>'; $html .= '<td>'.$info['description'].'</td>'; $html .= '<td>'; if (isset($info['link']) && $info['link']) { $html .= '<a href="'.$this->escapeHTML($info['link']).'"><span class="oi" data-glyph="book"></span></a>'; } $html .= '</td></tr>'; } $html .= '</table>'; $html .= '</section>'; /* Start of generating actions */ $html .= $this->generateFooter(); return $html; }
[ "public", "function", "generatePluginListing", "(", ")", "{", "$", "html", "=", "$", "this", "->", "generateHeader", "(", "'Plugins'", ")", ";", "$", "html", ".=", "'<section><h1>Plugins</h1>'", ";", "$", "html", ".=", "'<table class=\"propTable\">'", ";", "fore...
Generates the 'plugins' page. @return string
[ "Generates", "the", "plugins", "page", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Browser/Plugin.php#L384-L408
train
sabre-io/dav
lib/DAV/Browser/Plugin.php
Plugin.htmlActionsPanel
public function htmlActionsPanel(DAV\INode $node, &$output, $path) { if (!$node instanceof DAV\ICollection) { return; } // We also know fairly certain that if an object is a non-extended // SimpleCollection, we won't need to show the panel either. if ('Sabre\\DAV\\SimpleCollection' === get_class($node)) { return; } $output .= <<<HTML <form method="post" action=""> <h3>Create new folder</h3> <input type="hidden" name="sabreAction" value="mkcol" /> <label>Name:</label> <input type="text" name="name" /><br /> <input type="submit" value="create" /> </form> <form method="post" action="" enctype="multipart/form-data"> <h3>Upload file</h3> <input type="hidden" name="sabreAction" value="put" /> <label>Name (optional):</label> <input type="text" name="name" /><br /> <label>File:</label> <input type="file" name="file" /><br /> <input type="submit" value="upload" /> </form> HTML; }
php
public function htmlActionsPanel(DAV\INode $node, &$output, $path) { if (!$node instanceof DAV\ICollection) { return; } // We also know fairly certain that if an object is a non-extended // SimpleCollection, we won't need to show the panel either. if ('Sabre\\DAV\\SimpleCollection' === get_class($node)) { return; } $output .= <<<HTML <form method="post" action=""> <h3>Create new folder</h3> <input type="hidden" name="sabreAction" value="mkcol" /> <label>Name:</label> <input type="text" name="name" /><br /> <input type="submit" value="create" /> </form> <form method="post" action="" enctype="multipart/form-data"> <h3>Upload file</h3> <input type="hidden" name="sabreAction" value="put" /> <label>Name (optional):</label> <input type="text" name="name" /><br /> <label>File:</label> <input type="file" name="file" /><br /> <input type="submit" value="upload" /> </form> HTML; }
[ "public", "function", "htmlActionsPanel", "(", "DAV", "\\", "INode", "$", "node", ",", "&", "$", "output", ",", "$", "path", ")", "{", "if", "(", "!", "$", "node", "instanceof", "DAV", "\\", "ICollection", ")", "{", "return", ";", "}", "// We also know...
This method is used to generate the 'actions panel' output for collections. This specifically generates the interfaces for creating new files, and creating new directories. @param DAV\INode $node @param mixed $output @param string $path
[ "This", "method", "is", "used", "to", "generate", "the", "actions", "panel", "output", "for", "collections", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Browser/Plugin.php#L505-L532
train
sabre-io/dav
lib/DAV/Browser/Plugin.php
Plugin.getLocalAssetPath
protected function getLocalAssetPath($assetName) { $assetDir = __DIR__.'/assets/'; $path = $assetDir.$assetName; // Making sure people aren't trying to escape from the base path. $path = str_replace('\\', '/', $path); if (false !== strpos($path, '/../') || '/..' === strrchr($path, '/')) { throw new DAV\Exception\NotFound('Path does not exist, or escaping from the base path was detected'); } $realPath = realpath($path); if ($realPath && 0 === strpos($realPath, realpath($assetDir)) && file_exists($path)) { return $path; } throw new DAV\Exception\NotFound('Path does not exist, or escaping from the base path was detected'); }
php
protected function getLocalAssetPath($assetName) { $assetDir = __DIR__.'/assets/'; $path = $assetDir.$assetName; // Making sure people aren't trying to escape from the base path. $path = str_replace('\\', '/', $path); if (false !== strpos($path, '/../') || '/..' === strrchr($path, '/')) { throw new DAV\Exception\NotFound('Path does not exist, or escaping from the base path was detected'); } $realPath = realpath($path); if ($realPath && 0 === strpos($realPath, realpath($assetDir)) && file_exists($path)) { return $path; } throw new DAV\Exception\NotFound('Path does not exist, or escaping from the base path was detected'); }
[ "protected", "function", "getLocalAssetPath", "(", "$", "assetName", ")", "{", "$", "assetDir", "=", "__DIR__", ".", "'/assets/'", ";", "$", "path", "=", "$", "assetDir", ".", "$", "assetName", ";", "// Making sure people aren't trying to escape from the base path.", ...
This method returns a local pathname to an asset. @param string $assetName @throws DAV\Exception\NotFound @return string
[ "This", "method", "returns", "a", "local", "pathname", "to", "an", "asset", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Browser/Plugin.php#L556-L571
train
sabre-io/dav
lib/DAV/Browser/Plugin.php
Plugin.serveAsset
protected function serveAsset($assetName) { $assetPath = $this->getLocalAssetPath($assetName); // Rudimentary mime type detection $mime = 'application/octet-stream'; $map = [ 'ico' => 'image/vnd.microsoft.icon', 'png' => 'image/png', 'css' => 'text/css', ]; $ext = substr($assetName, strrpos($assetName, '.') + 1); if (isset($map[$ext])) { $mime = $map[$ext]; } $this->server->httpResponse->setHeader('Content-Type', $mime); $this->server->httpResponse->setHeader('Content-Length', filesize($assetPath)); $this->server->httpResponse->setHeader('Cache-Control', 'public, max-age=1209600'); $this->server->httpResponse->setStatus(200); $this->server->httpResponse->setBody(fopen($assetPath, 'r')); }
php
protected function serveAsset($assetName) { $assetPath = $this->getLocalAssetPath($assetName); // Rudimentary mime type detection $mime = 'application/octet-stream'; $map = [ 'ico' => 'image/vnd.microsoft.icon', 'png' => 'image/png', 'css' => 'text/css', ]; $ext = substr($assetName, strrpos($assetName, '.') + 1); if (isset($map[$ext])) { $mime = $map[$ext]; } $this->server->httpResponse->setHeader('Content-Type', $mime); $this->server->httpResponse->setHeader('Content-Length', filesize($assetPath)); $this->server->httpResponse->setHeader('Cache-Control', 'public, max-age=1209600'); $this->server->httpResponse->setStatus(200); $this->server->httpResponse->setBody(fopen($assetPath, 'r')); }
[ "protected", "function", "serveAsset", "(", "$", "assetName", ")", "{", "$", "assetPath", "=", "$", "this", "->", "getLocalAssetPath", "(", "$", "assetName", ")", ";", "// Rudimentary mime type detection", "$", "mime", "=", "'application/octet-stream'", ";", "$", ...
This method reads an asset from disk and generates a full http response. @param string $assetName
[ "This", "method", "reads", "an", "asset", "from", "disk", "and", "generates", "a", "full", "http", "response", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Browser/Plugin.php#L578-L600
train
sabre-io/dav
lib/DAV/Browser/Plugin.php
Plugin.mapResourceType
private function mapResourceType(array $resourceTypes, $node) { if (!$resourceTypes) { if ($node instanceof DAV\IFile) { return [ 'string' => 'File', 'icon' => 'file', ]; } else { return [ 'string' => 'Unknown', 'icon' => 'cog', ]; } } $types = [ '{http://calendarserver.org/ns/}calendar-proxy-write' => [ 'string' => 'Proxy-Write', 'icon' => 'people', ], '{http://calendarserver.org/ns/}calendar-proxy-read' => [ 'string' => 'Proxy-Read', 'icon' => 'people', ], '{urn:ietf:params:xml:ns:caldav}schedule-outbox' => [ 'string' => 'Outbox', 'icon' => 'inbox', ], '{urn:ietf:params:xml:ns:caldav}schedule-inbox' => [ 'string' => 'Inbox', 'icon' => 'inbox', ], '{urn:ietf:params:xml:ns:caldav}calendar' => [ 'string' => 'Calendar', 'icon' => 'calendar', ], '{http://calendarserver.org/ns/}shared-owner' => [ 'string' => 'Shared', 'icon' => 'calendar', ], '{http://calendarserver.org/ns/}subscribed' => [ 'string' => 'Subscription', 'icon' => 'calendar', ], '{urn:ietf:params:xml:ns:carddav}directory' => [ 'string' => 'Directory', 'icon' => 'globe', ], '{urn:ietf:params:xml:ns:carddav}addressbook' => [ 'string' => 'Address book', 'icon' => 'book', ], '{DAV:}principal' => [ 'string' => 'Principal', 'icon' => 'person', ], '{DAV:}collection' => [ 'string' => 'Collection', 'icon' => 'folder', ], ]; $info = [ 'string' => [], 'icon' => 'cog', ]; foreach ($resourceTypes as $k => $resourceType) { if (isset($types[$resourceType])) { $info['string'][] = $types[$resourceType]['string']; } else { $info['string'][] = $resourceType; } } foreach ($types as $key => $resourceInfo) { if (in_array($key, $resourceTypes)) { $info['icon'] = $resourceInfo['icon']; break; } } $info['string'] = implode(', ', $info['string']); return $info; }
php
private function mapResourceType(array $resourceTypes, $node) { if (!$resourceTypes) { if ($node instanceof DAV\IFile) { return [ 'string' => 'File', 'icon' => 'file', ]; } else { return [ 'string' => 'Unknown', 'icon' => 'cog', ]; } } $types = [ '{http://calendarserver.org/ns/}calendar-proxy-write' => [ 'string' => 'Proxy-Write', 'icon' => 'people', ], '{http://calendarserver.org/ns/}calendar-proxy-read' => [ 'string' => 'Proxy-Read', 'icon' => 'people', ], '{urn:ietf:params:xml:ns:caldav}schedule-outbox' => [ 'string' => 'Outbox', 'icon' => 'inbox', ], '{urn:ietf:params:xml:ns:caldav}schedule-inbox' => [ 'string' => 'Inbox', 'icon' => 'inbox', ], '{urn:ietf:params:xml:ns:caldav}calendar' => [ 'string' => 'Calendar', 'icon' => 'calendar', ], '{http://calendarserver.org/ns/}shared-owner' => [ 'string' => 'Shared', 'icon' => 'calendar', ], '{http://calendarserver.org/ns/}subscribed' => [ 'string' => 'Subscription', 'icon' => 'calendar', ], '{urn:ietf:params:xml:ns:carddav}directory' => [ 'string' => 'Directory', 'icon' => 'globe', ], '{urn:ietf:params:xml:ns:carddav}addressbook' => [ 'string' => 'Address book', 'icon' => 'book', ], '{DAV:}principal' => [ 'string' => 'Principal', 'icon' => 'person', ], '{DAV:}collection' => [ 'string' => 'Collection', 'icon' => 'folder', ], ]; $info = [ 'string' => [], 'icon' => 'cog', ]; foreach ($resourceTypes as $k => $resourceType) { if (isset($types[$resourceType])) { $info['string'][] = $types[$resourceType]['string']; } else { $info['string'][] = $resourceType; } } foreach ($types as $key => $resourceInfo) { if (in_array($key, $resourceTypes)) { $info['icon'] = $resourceInfo['icon']; break; } } $info['string'] = implode(', ', $info['string']); return $info; }
[ "private", "function", "mapResourceType", "(", "array", "$", "resourceTypes", ",", "$", "node", ")", "{", "if", "(", "!", "$", "resourceTypes", ")", "{", "if", "(", "$", "node", "instanceof", "DAV", "\\", "IFile", ")", "{", "return", "[", "'string'", "...
Maps a resource type to a human-readable string and icon. @param array $resourceTypes @param DAV\INode $node @return array
[ "Maps", "a", "resource", "type", "to", "a", "human", "-", "readable", "string", "and", "icon", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Browser/Plugin.php#L637-L720
train
sabre-io/dav
lib/DAV/Auth/Backend/File.php
File.loadFile
public function loadFile($filename) { foreach (file($filename, FILE_IGNORE_NEW_LINES) as $line) { if (2 !== substr_count($line, ':')) { throw new DAV\Exception('Malformed htdigest file. Every line should contain 2 colons'); } list($username, $realm, $A1) = explode(':', $line); if (!preg_match('/^[a-zA-Z0-9]{32}$/', $A1)) { throw new DAV\Exception('Malformed htdigest file. Invalid md5 hash'); } $this->users[$realm.':'.$username] = $A1; } }
php
public function loadFile($filename) { foreach (file($filename, FILE_IGNORE_NEW_LINES) as $line) { if (2 !== substr_count($line, ':')) { throw new DAV\Exception('Malformed htdigest file. Every line should contain 2 colons'); } list($username, $realm, $A1) = explode(':', $line); if (!preg_match('/^[a-zA-Z0-9]{32}$/', $A1)) { throw new DAV\Exception('Malformed htdigest file. Invalid md5 hash'); } $this->users[$realm.':'.$username] = $A1; } }
[ "public", "function", "loadFile", "(", "$", "filename", ")", "{", "foreach", "(", "file", "(", "$", "filename", ",", "FILE_IGNORE_NEW_LINES", ")", "as", "$", "line", ")", "{", "if", "(", "2", "!==", "substr_count", "(", "$", "line", ",", "':'", ")", ...
Loads an htdigest-formatted file. This method can be called multiple times if more than 1 file is used. @param string $filename
[ "Loads", "an", "htdigest", "-", "formatted", "file", ".", "This", "method", "can", "be", "called", "multiple", "times", "if", "more", "than", "1", "file", "is", "used", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Auth/Backend/File.php#L47-L60
train
sabre-io/dav
lib/DAV/Auth/Backend/File.php
File.getDigestHash
public function getDigestHash($realm, $username) { return isset($this->users[$realm.':'.$username]) ? $this->users[$realm.':'.$username] : false; }
php
public function getDigestHash($realm, $username) { return isset($this->users[$realm.':'.$username]) ? $this->users[$realm.':'.$username] : false; }
[ "public", "function", "getDigestHash", "(", "$", "realm", ",", "$", "username", ")", "{", "return", "isset", "(", "$", "this", "->", "users", "[", "$", "realm", ".", "':'", ".", "$", "username", "]", ")", "?", "$", "this", "->", "users", "[", "$", ...
Returns a users' information. @param string $realm @param string $username @return string
[ "Returns", "a", "users", "information", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Auth/Backend/File.php#L70-L73
train
sabre-io/dav
lib/DAVACL/Principal.php
Principal.getAlternateUriSet
public function getAlternateUriSet() { $uris = []; if (isset($this->principalProperties['{DAV:}alternate-URI-set'])) { $uris = $this->principalProperties['{DAV:}alternate-URI-set']; } if (isset($this->principalProperties['{http://sabredav.org/ns}email-address'])) { $uris[] = 'mailto:'.$this->principalProperties['{http://sabredav.org/ns}email-address']; } return array_unique($uris); }
php
public function getAlternateUriSet() { $uris = []; if (isset($this->principalProperties['{DAV:}alternate-URI-set'])) { $uris = $this->principalProperties['{DAV:}alternate-URI-set']; } if (isset($this->principalProperties['{http://sabredav.org/ns}email-address'])) { $uris[] = 'mailto:'.$this->principalProperties['{http://sabredav.org/ns}email-address']; } return array_unique($uris); }
[ "public", "function", "getAlternateUriSet", "(", ")", "{", "$", "uris", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "principalProperties", "[", "'{DAV:}alternate-URI-set'", "]", ")", ")", "{", "$", "uris", "=", "$", "this", "->", "p...
Returns a list of alternative urls for a principal. This can for example be an email address, or ldap url. @return array
[ "Returns", "a", "list", "of", "alternative", "urls", "for", "a", "principal", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Principal.php#L75-L87
train
sabre-io/dav
lib/DAVACL/Principal.php
Principal.getName
public function getName() { $uri = $this->principalProperties['uri']; list(, $name) = Uri\split($uri); return $name; }
php
public function getName() { $uri = $this->principalProperties['uri']; list(, $name) = Uri\split($uri); return $name; }
[ "public", "function", "getName", "(", ")", "{", "$", "uri", "=", "$", "this", "->", "principalProperties", "[", "'uri'", "]", ";", "list", "(", ",", "$", "name", ")", "=", "Uri", "\\", "split", "(", "$", "uri", ")", ";", "return", "$", "name", ";...
Returns this principals name. @return string
[ "Returns", "this", "principals", "name", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Principal.php#L135-L141
train
sabre-io/dav
lib/DAVACL/Principal.php
Principal.getProperties
public function getProperties($requestedProperties) { $newProperties = []; foreach ($requestedProperties as $propName) { if (isset($this->principalProperties[$propName])) { $newProperties[$propName] = $this->principalProperties[$propName]; } } return $newProperties; }
php
public function getProperties($requestedProperties) { $newProperties = []; foreach ($requestedProperties as $propName) { if (isset($this->principalProperties[$propName])) { $newProperties[$propName] = $this->principalProperties[$propName]; } } return $newProperties; }
[ "public", "function", "getProperties", "(", "$", "requestedProperties", ")", "{", "$", "newProperties", "=", "[", "]", ";", "foreach", "(", "$", "requestedProperties", "as", "$", "propName", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "principalP...
Returns a list of properties. @param array $requestedProperties @return array
[ "Returns", "a", "list", "of", "properties", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Principal.php#L164-L174
train
sabre-io/dav
lib/CalDAV/SharingPlugin.php
SharingPlugin.propFindEarly
public function propFindEarly(DAV\PropFind $propFind, DAV\INode $node) { if ($node instanceof ISharedCalendar) { $propFind->handle('{'.Plugin::NS_CALENDARSERVER.'}invite', function () use ($node) { return new Xml\Property\Invite( $node->getInvites() ); }); } }
php
public function propFindEarly(DAV\PropFind $propFind, DAV\INode $node) { if ($node instanceof ISharedCalendar) { $propFind->handle('{'.Plugin::NS_CALENDARSERVER.'}invite', function () use ($node) { return new Xml\Property\Invite( $node->getInvites() ); }); } }
[ "public", "function", "propFindEarly", "(", "DAV", "\\", "PropFind", "$", "propFind", ",", "DAV", "\\", "INode", "$", "node", ")", "{", "if", "(", "$", "node", "instanceof", "ISharedCalendar", ")", "{", "$", "propFind", "->", "handle", "(", "'{'", ".", ...
This event is triggered when properties are requested for a certain node. This allows us to inject any properties early. @param DAV\PropFind $propFind @param DAV\INode $node
[ "This", "event", "is", "triggered", "when", "properties", "are", "requested", "for", "a", "certain", "node", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/SharingPlugin.php#L106-L115
train
sabre-io/dav
lib/CalDAV/SharingPlugin.php
SharingPlugin.propPatch
public function propPatch($path, DAV\PropPatch $propPatch) { $node = $this->server->tree->getNodeForPath($path); if (!$node instanceof ISharedCalendar) { return; } if (\Sabre\DAV\Sharing\Plugin::ACCESS_SHAREDOWNER === $node->getShareAccess() || \Sabre\DAV\Sharing\Plugin::ACCESS_NOTSHARED === $node->getShareAccess()) { $propPatch->handle('{DAV:}resourcetype', function ($value) use ($node) { if ($value->is('{'.Plugin::NS_CALENDARSERVER.'}shared-owner')) { return false; } $shares = $node->getInvites(); foreach ($shares as $share) { $share->access = DAV\Sharing\Plugin::ACCESS_NOACCESS; } $node->updateInvites($shares); return true; }); } }
php
public function propPatch($path, DAV\PropPatch $propPatch) { $node = $this->server->tree->getNodeForPath($path); if (!$node instanceof ISharedCalendar) { return; } if (\Sabre\DAV\Sharing\Plugin::ACCESS_SHAREDOWNER === $node->getShareAccess() || \Sabre\DAV\Sharing\Plugin::ACCESS_NOTSHARED === $node->getShareAccess()) { $propPatch->handle('{DAV:}resourcetype', function ($value) use ($node) { if ($value->is('{'.Plugin::NS_CALENDARSERVER.'}shared-owner')) { return false; } $shares = $node->getInvites(); foreach ($shares as $share) { $share->access = DAV\Sharing\Plugin::ACCESS_NOACCESS; } $node->updateInvites($shares); return true; }); } }
[ "public", "function", "propPatch", "(", "$", "path", ",", "DAV", "\\", "PropPatch", "$", "propPatch", ")", "{", "$", "node", "=", "$", "this", "->", "server", "->", "tree", "->", "getNodeForPath", "(", "$", "path", ")", ";", "if", "(", "!", "$", "n...
This method is trigged when a user attempts to update a node's properties. A previous draft of the sharing spec stated that it was possible to use PROPPATCH to remove 'shared-owner' from the resourcetype, thus unsharing the calendar. Even though this is no longer in the current spec, we keep this around because OS X 10.7 may still make use of this feature. @param string $path @param DAV\PropPatch $propPatch
[ "This", "method", "is", "trigged", "when", "a", "user", "attempts", "to", "update", "a", "node", "s", "properties", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/SharingPlugin.php#L160-L181
train
sabre-io/dav
lib/CalDAV/ICSExportPlugin.php
ICSExportPlugin.httpGet
public function httpGet(RequestInterface $request, ResponseInterface $response) { $queryParams = $request->getQueryParameters(); if (!array_key_exists('export', $queryParams)) { return; } $path = $request->getPath(); $node = $this->server->getProperties($path, [ '{DAV:}resourcetype', '{DAV:}displayname', '{http://sabredav.org/ns}sync-token', '{DAV:}sync-token', '{http://apple.com/ns/ical/}calendar-color', ]); if (!isset($node['{DAV:}resourcetype']) || !$node['{DAV:}resourcetype']->is('{'.Plugin::NS_CALDAV.'}calendar')) { return; } // Marking the transactionType, for logging purposes. $this->server->transactionType = 'get-calendar-export'; $properties = $node; $start = null; $end = null; $expand = false; $componentType = false; if (isset($queryParams['start'])) { if (!ctype_digit($queryParams['start'])) { throw new BadRequest('The start= parameter must contain a unix timestamp'); } $start = DateTime::createFromFormat('U', $queryParams['start']); } if (isset($queryParams['end'])) { if (!ctype_digit($queryParams['end'])) { throw new BadRequest('The end= parameter must contain a unix timestamp'); } $end = DateTime::createFromFormat('U', $queryParams['end']); } if (isset($queryParams['expand']) && (bool) $queryParams['expand']) { if (!$start || !$end) { throw new BadRequest('If you\'d like to expand recurrences, you must specify both a start= and end= parameter.'); } $expand = true; $componentType = 'VEVENT'; } if (isset($queryParams['componentType'])) { if (!in_array($queryParams['componentType'], ['VEVENT', 'VTODO', 'VJOURNAL'])) { throw new BadRequest('You are not allowed to search for components of type: '.$queryParams['componentType'].' here'); } $componentType = $queryParams['componentType']; } $format = \Sabre\HTTP\negotiateContentType( $request->getHeader('Accept'), [ 'text/calendar', 'application/calendar+json', ] ); if (isset($queryParams['accept'])) { if ('application/calendar+json' === $queryParams['accept'] || 'jcal' === $queryParams['accept']) { $format = 'application/calendar+json'; } } if (!$format) { $format = 'text/calendar'; } $this->generateResponse($path, $start, $end, $expand, $componentType, $format, $properties, $response); // Returning false to break the event chain return false; }
php
public function httpGet(RequestInterface $request, ResponseInterface $response) { $queryParams = $request->getQueryParameters(); if (!array_key_exists('export', $queryParams)) { return; } $path = $request->getPath(); $node = $this->server->getProperties($path, [ '{DAV:}resourcetype', '{DAV:}displayname', '{http://sabredav.org/ns}sync-token', '{DAV:}sync-token', '{http://apple.com/ns/ical/}calendar-color', ]); if (!isset($node['{DAV:}resourcetype']) || !$node['{DAV:}resourcetype']->is('{'.Plugin::NS_CALDAV.'}calendar')) { return; } // Marking the transactionType, for logging purposes. $this->server->transactionType = 'get-calendar-export'; $properties = $node; $start = null; $end = null; $expand = false; $componentType = false; if (isset($queryParams['start'])) { if (!ctype_digit($queryParams['start'])) { throw new BadRequest('The start= parameter must contain a unix timestamp'); } $start = DateTime::createFromFormat('U', $queryParams['start']); } if (isset($queryParams['end'])) { if (!ctype_digit($queryParams['end'])) { throw new BadRequest('The end= parameter must contain a unix timestamp'); } $end = DateTime::createFromFormat('U', $queryParams['end']); } if (isset($queryParams['expand']) && (bool) $queryParams['expand']) { if (!$start || !$end) { throw new BadRequest('If you\'d like to expand recurrences, you must specify both a start= and end= parameter.'); } $expand = true; $componentType = 'VEVENT'; } if (isset($queryParams['componentType'])) { if (!in_array($queryParams['componentType'], ['VEVENT', 'VTODO', 'VJOURNAL'])) { throw new BadRequest('You are not allowed to search for components of type: '.$queryParams['componentType'].' here'); } $componentType = $queryParams['componentType']; } $format = \Sabre\HTTP\negotiateContentType( $request->getHeader('Accept'), [ 'text/calendar', 'application/calendar+json', ] ); if (isset($queryParams['accept'])) { if ('application/calendar+json' === $queryParams['accept'] || 'jcal' === $queryParams['accept']) { $format = 'application/calendar+json'; } } if (!$format) { $format = 'text/calendar'; } $this->generateResponse($path, $start, $end, $expand, $componentType, $format, $properties, $response); // Returning false to break the event chain return false; }
[ "public", "function", "httpGet", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "queryParams", "=", "$", "request", "->", "getQueryParameters", "(", ")", ";", "if", "(", "!", "array_key_exists", "(", "'export...
Intercepts GET requests on calendar urls ending with ?export. @param RequestInterface $request @param ResponseInterface $response @throws BadRequest @throws DAV\Exception\NotFound @throws VObject\InvalidDataException @return bool
[ "Intercepts", "GET", "requests", "on", "calendar", "urls", "ending", "with", "?export", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/ICSExportPlugin.php#L86-L162
train
sabre-io/dav
lib/CalDAV/ICSExportPlugin.php
ICSExportPlugin.mergeObjects
public function mergeObjects(array $properties, array $inputObjects) { $calendar = new VObject\Component\VCalendar(); $calendar->VERSION = '2.0'; if (DAV\Server::$exposeVersion) { $calendar->PRODID = '-//SabreDAV//SabreDAV '.DAV\Version::VERSION.'//EN'; } else { $calendar->PRODID = '-//SabreDAV//SabreDAV//EN'; } if (isset($properties['{DAV:}displayname'])) { $calendar->{'X-WR-CALNAME'} = $properties['{DAV:}displayname']; } if (isset($properties['{http://apple.com/ns/ical/}calendar-color'])) { $calendar->{'X-APPLE-CALENDAR-COLOR'} = $properties['{http://apple.com/ns/ical/}calendar-color']; } $collectedTimezones = []; $timezones = []; $objects = []; foreach ($inputObjects as $href => $inputObject) { $nodeComp = VObject\Reader::read($inputObject); foreach ($nodeComp->children() as $child) { switch ($child->name) { case 'VEVENT': case 'VTODO': case 'VJOURNAL': $objects[] = clone $child; break; // VTIMEZONE is special, because we need to filter out the duplicates case 'VTIMEZONE': // Naively just checking tzid. if (in_array((string) $child->TZID, $collectedTimezones)) { break; } $timezones[] = clone $child; $collectedTimezones[] = $child->TZID; break; } } // Destroy circular references to PHP will GC the object. $nodeComp->destroy(); unset($nodeComp); } foreach ($timezones as $tz) { $calendar->add($tz); } foreach ($objects as $obj) { $calendar->add($obj); } return $calendar; }
php
public function mergeObjects(array $properties, array $inputObjects) { $calendar = new VObject\Component\VCalendar(); $calendar->VERSION = '2.0'; if (DAV\Server::$exposeVersion) { $calendar->PRODID = '-//SabreDAV//SabreDAV '.DAV\Version::VERSION.'//EN'; } else { $calendar->PRODID = '-//SabreDAV//SabreDAV//EN'; } if (isset($properties['{DAV:}displayname'])) { $calendar->{'X-WR-CALNAME'} = $properties['{DAV:}displayname']; } if (isset($properties['{http://apple.com/ns/ical/}calendar-color'])) { $calendar->{'X-APPLE-CALENDAR-COLOR'} = $properties['{http://apple.com/ns/ical/}calendar-color']; } $collectedTimezones = []; $timezones = []; $objects = []; foreach ($inputObjects as $href => $inputObject) { $nodeComp = VObject\Reader::read($inputObject); foreach ($nodeComp->children() as $child) { switch ($child->name) { case 'VEVENT': case 'VTODO': case 'VJOURNAL': $objects[] = clone $child; break; // VTIMEZONE is special, because we need to filter out the duplicates case 'VTIMEZONE': // Naively just checking tzid. if (in_array((string) $child->TZID, $collectedTimezones)) { break; } $timezones[] = clone $child; $collectedTimezones[] = $child->TZID; break; } } // Destroy circular references to PHP will GC the object. $nodeComp->destroy(); unset($nodeComp); } foreach ($timezones as $tz) { $calendar->add($tz); } foreach ($objects as $obj) { $calendar->add($obj); } return $calendar; }
[ "public", "function", "mergeObjects", "(", "array", "$", "properties", ",", "array", "$", "inputObjects", ")", "{", "$", "calendar", "=", "new", "VObject", "\\", "Component", "\\", "VCalendar", "(", ")", ";", "$", "calendar", "->", "VERSION", "=", "'2.0'",...
Merges all calendar objects, and builds one big iCalendar blob. @param array $properties Some CalDAV properties @param array $inputObjects @return VObject\Component\VCalendar
[ "Merges", "all", "calendar", "objects", "and", "builds", "one", "big", "iCalendar", "blob", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/ICSExportPlugin.php#L291-L348
train
sabre-io/dav
lib/DAV/Tree.php
Tree.getNodeForPath
public function getNodeForPath($path) { $path = trim($path, '/'); if (isset($this->cache[$path])) { return $this->cache[$path]; } // Is it the root node? if (!strlen($path)) { return $this->rootNode; } // Attempting to fetch its parent list($parentName, $baseName) = Uri\split($path); // If there was no parent, we must simply ask it from the root node. if ('' === $parentName) { $node = $this->rootNode->getChild($baseName); } else { // Otherwise, we recursively grab the parent and ask him/her. $parent = $this->getNodeForPath($parentName); if (!($parent instanceof ICollection)) { throw new Exception\NotFound('Could not find node at path: '.$path); } $node = $parent->getChild($baseName); } $this->cache[$path] = $node; return $node; }
php
public function getNodeForPath($path) { $path = trim($path, '/'); if (isset($this->cache[$path])) { return $this->cache[$path]; } // Is it the root node? if (!strlen($path)) { return $this->rootNode; } // Attempting to fetch its parent list($parentName, $baseName) = Uri\split($path); // If there was no parent, we must simply ask it from the root node. if ('' === $parentName) { $node = $this->rootNode->getChild($baseName); } else { // Otherwise, we recursively grab the parent and ask him/her. $parent = $this->getNodeForPath($parentName); if (!($parent instanceof ICollection)) { throw new Exception\NotFound('Could not find node at path: '.$path); } $node = $parent->getChild($baseName); } $this->cache[$path] = $node; return $node; }
[ "public", "function", "getNodeForPath", "(", "$", "path", ")", "{", "$", "path", "=", "trim", "(", "$", "path", ",", "'/'", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "cache", "[", "$", "path", "]", ")", ")", "{", "return", "$", "thi...
Returns the INode object for the requested path. @param string $path @return INode
[ "Returns", "the", "INode", "object", "for", "the", "requested", "path", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Tree.php#L55-L86
train
sabre-io/dav
lib/DAV/Tree.php
Tree.nodeExists
public function nodeExists($path) { try { // The root always exists if ('' === $path) { return true; } list($parent, $base) = Uri\split($path); $parentNode = $this->getNodeForPath($parent); if (!$parentNode instanceof ICollection) { return false; } return $parentNode->childExists($base); } catch (Exception\NotFound $e) { return false; } }
php
public function nodeExists($path) { try { // The root always exists if ('' === $path) { return true; } list($parent, $base) = Uri\split($path); $parentNode = $this->getNodeForPath($parent); if (!$parentNode instanceof ICollection) { return false; } return $parentNode->childExists($base); } catch (Exception\NotFound $e) { return false; } }
[ "public", "function", "nodeExists", "(", "$", "path", ")", "{", "try", "{", "// The root always exists", "if", "(", "''", "===", "$", "path", ")", "{", "return", "true", ";", "}", "list", "(", "$", "parent", ",", "$", "base", ")", "=", "Uri", "\\", ...
This function allows you to check if a node exists. Implementors of this class should override this method to make it cheaper. @param string $path @return bool
[ "This", "function", "allows", "you", "to", "check", "if", "a", "node", "exists", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Tree.php#L98-L117
train
sabre-io/dav
lib/DAV/Tree.php
Tree.copy
public function copy($sourcePath, $destinationPath) { $sourceNode = $this->getNodeForPath($sourcePath); // grab the dirname and basename components list($destinationDir, $destinationName) = Uri\split($destinationPath); $destinationParent = $this->getNodeForPath($destinationDir); // Check if the target can handle the copy itself. If not, we do it ourselves. if (!$destinationParent instanceof ICopyTarget || !$destinationParent->copyInto($destinationName, $sourcePath, $sourceNode)) { $this->copyNode($sourceNode, $destinationParent, $destinationName); } $this->markDirty($destinationDir); }
php
public function copy($sourcePath, $destinationPath) { $sourceNode = $this->getNodeForPath($sourcePath); // grab the dirname and basename components list($destinationDir, $destinationName) = Uri\split($destinationPath); $destinationParent = $this->getNodeForPath($destinationDir); // Check if the target can handle the copy itself. If not, we do it ourselves. if (!$destinationParent instanceof ICopyTarget || !$destinationParent->copyInto($destinationName, $sourcePath, $sourceNode)) { $this->copyNode($sourceNode, $destinationParent, $destinationName); } $this->markDirty($destinationDir); }
[ "public", "function", "copy", "(", "$", "sourcePath", ",", "$", "destinationPath", ")", "{", "$", "sourceNode", "=", "$", "this", "->", "getNodeForPath", "(", "$", "sourcePath", ")", ";", "// grab the dirname and basename components", "list", "(", "$", "destinat...
Copies a file from path to another. @param string $sourcePath The source location @param string $destinationPath The full destination path
[ "Copies", "a", "file", "from", "path", "to", "another", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Tree.php#L125-L139
train
sabre-io/dav
lib/DAV/Tree.php
Tree.move
public function move($sourcePath, $destinationPath) { list($sourceDir) = Uri\split($sourcePath); list($destinationDir, $destinationName) = Uri\split($destinationPath); if ($sourceDir === $destinationDir) { // If this is a 'local' rename, it means we can just trigger a rename. $sourceNode = $this->getNodeForPath($sourcePath); $sourceNode->setName($destinationName); } else { $newParentNode = $this->getNodeForPath($destinationDir); $moveSuccess = false; if ($newParentNode instanceof IMoveTarget) { // The target collection may be able to handle the move $sourceNode = $this->getNodeForPath($sourcePath); $moveSuccess = $newParentNode->moveInto($destinationName, $sourcePath, $sourceNode); } if (!$moveSuccess) { $this->copy($sourcePath, $destinationPath); $this->getNodeForPath($sourcePath)->delete(); } } $this->markDirty($sourceDir); $this->markDirty($destinationDir); }
php
public function move($sourcePath, $destinationPath) { list($sourceDir) = Uri\split($sourcePath); list($destinationDir, $destinationName) = Uri\split($destinationPath); if ($sourceDir === $destinationDir) { // If this is a 'local' rename, it means we can just trigger a rename. $sourceNode = $this->getNodeForPath($sourcePath); $sourceNode->setName($destinationName); } else { $newParentNode = $this->getNodeForPath($destinationDir); $moveSuccess = false; if ($newParentNode instanceof IMoveTarget) { // The target collection may be able to handle the move $sourceNode = $this->getNodeForPath($sourcePath); $moveSuccess = $newParentNode->moveInto($destinationName, $sourcePath, $sourceNode); } if (!$moveSuccess) { $this->copy($sourcePath, $destinationPath); $this->getNodeForPath($sourcePath)->delete(); } } $this->markDirty($sourceDir); $this->markDirty($destinationDir); }
[ "public", "function", "move", "(", "$", "sourcePath", ",", "$", "destinationPath", ")", "{", "list", "(", "$", "sourceDir", ")", "=", "Uri", "\\", "split", "(", "$", "sourcePath", ")", ";", "list", "(", "$", "destinationDir", ",", "$", "destinationName",...
Moves a file from one location to another. @param string $sourcePath The path to the file which should be moved @param string $destinationPath The full destination path, so not just the destination parent node @return int
[ "Moves", "a", "file", "from", "one", "location", "to", "another", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Tree.php#L149-L173
train
sabre-io/dav
lib/DAV/Tree.php
Tree.delete
public function delete($path) { $node = $this->getNodeForPath($path); $node->delete(); list($parent) = Uri\split($path); $this->markDirty($parent); }
php
public function delete($path) { $node = $this->getNodeForPath($path); $node->delete(); list($parent) = Uri\split($path); $this->markDirty($parent); }
[ "public", "function", "delete", "(", "$", "path", ")", "{", "$", "node", "=", "$", "this", "->", "getNodeForPath", "(", "$", "path", ")", ";", "$", "node", "->", "delete", "(", ")", ";", "list", "(", "$", "parent", ")", "=", "Uri", "\\", "split",...
Deletes a node from the tree. @param string $path
[ "Deletes", "a", "node", "from", "the", "tree", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Tree.php#L180-L187
train
sabre-io/dav
lib/DAV/Tree.php
Tree.getChildren
public function getChildren($path) { $node = $this->getNodeForPath($path); $basePath = trim($path, '/'); if ('' !== $basePath) { $basePath .= '/'; } foreach ($node->getChildren() as $child) { $this->cache[$basePath.$child->getName()] = $child; yield $child; } }
php
public function getChildren($path) { $node = $this->getNodeForPath($path); $basePath = trim($path, '/'); if ('' !== $basePath) { $basePath .= '/'; } foreach ($node->getChildren() as $child) { $this->cache[$basePath.$child->getName()] = $child; yield $child; } }
[ "public", "function", "getChildren", "(", "$", "path", ")", "{", "$", "node", "=", "$", "this", "->", "getNodeForPath", "(", "$", "path", ")", ";", "$", "basePath", "=", "trim", "(", "$", "path", ",", "'/'", ")", ";", "if", "(", "''", "!==", "$",...
Returns a list of childnodes for a given path. @param string $path @return \Traversable
[ "Returns", "a", "list", "of", "childnodes", "for", "a", "given", "path", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Tree.php#L196-L208
train
sabre-io/dav
lib/DAV/Tree.php
Tree.markDirty
public function markDirty($path) { // We don't care enough about sub-paths // flushing the entire cache $path = trim($path, '/'); foreach ($this->cache as $nodePath => $node) { if ('' === $path || $nodePath == $path || 0 === strpos($nodePath, $path.'/')) { unset($this->cache[$nodePath]); } } }
php
public function markDirty($path) { // We don't care enough about sub-paths // flushing the entire cache $path = trim($path, '/'); foreach ($this->cache as $nodePath => $node) { if ('' === $path || $nodePath == $path || 0 === strpos($nodePath, $path.'/')) { unset($this->cache[$nodePath]); } } }
[ "public", "function", "markDirty", "(", "$", "path", ")", "{", "// We don't care enough about sub-paths", "// flushing the entire cache", "$", "path", "=", "trim", "(", "$", "path", ",", "'/'", ")", ";", "foreach", "(", "$", "this", "->", "cache", "as", "$", ...
This method is called with every tree update. Examples of tree updates are: * node deletions * node creations * copy * move * renaming nodes If Tree classes implement a form of caching, this will allow them to make sure caches will be expired. If a path is passed, it is assumed that the entire subtree is dirty @param string $path
[ "This", "method", "is", "called", "with", "every", "tree", "update", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Tree.php#L227-L237
train
sabre-io/dav
lib/DAV/Tree.php
Tree.getMultipleNodes
public function getMultipleNodes($paths) { // Finding common parents $parents = []; foreach ($paths as $path) { list($parent, $node) = Uri\split($path); if (!isset($parents[$parent])) { $parents[$parent] = [$node]; } else { $parents[$parent][] = $node; } } $result = []; foreach ($parents as $parent => $children) { $parentNode = $this->getNodeForPath($parent); if ($parentNode instanceof IMultiGet) { foreach ($parentNode->getMultipleChildren($children) as $childNode) { $fullPath = $parent.'/'.$childNode->getName(); $result[$fullPath] = $childNode; $this->cache[$fullPath] = $childNode; } } else { foreach ($children as $child) { $fullPath = $parent.'/'.$child; $result[$fullPath] = $this->getNodeForPath($fullPath); } } } return $result; }
php
public function getMultipleNodes($paths) { // Finding common parents $parents = []; foreach ($paths as $path) { list($parent, $node) = Uri\split($path); if (!isset($parents[$parent])) { $parents[$parent] = [$node]; } else { $parents[$parent][] = $node; } } $result = []; foreach ($parents as $parent => $children) { $parentNode = $this->getNodeForPath($parent); if ($parentNode instanceof IMultiGet) { foreach ($parentNode->getMultipleChildren($children) as $childNode) { $fullPath = $parent.'/'.$childNode->getName(); $result[$fullPath] = $childNode; $this->cache[$fullPath] = $childNode; } } else { foreach ($children as $child) { $fullPath = $parent.'/'.$child; $result[$fullPath] = $this->getNodeForPath($fullPath); } } } return $result; }
[ "public", "function", "getMultipleNodes", "(", "$", "paths", ")", "{", "// Finding common parents", "$", "parents", "=", "[", "]", ";", "foreach", "(", "$", "paths", "as", "$", "path", ")", "{", "list", "(", "$", "parent", ",", "$", "node", ")", "=", ...
This method tells the tree system to pre-fetch and cache a list of children of a single parent. There are a bunch of operations in the WebDAV stack that request many children (based on uris), and sometimes fetching many at once can optimize this. This method returns an array with the found nodes. It's keys are the original paths. The result may be out of order. @param array $paths list of nodes that must be fetched @return array
[ "This", "method", "tells", "the", "tree", "system", "to", "pre", "-", "fetch", "and", "cache", "a", "list", "of", "children", "of", "a", "single", "parent", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Tree.php#L254-L286
train
sabre-io/dav
lib/DAV/FSExt/File.php
File.put
public function put($data) { file_put_contents($this->path, $data); clearstatcache(true, $this->path); return $this->getETag(); }
php
public function put($data) { file_put_contents($this->path, $data); clearstatcache(true, $this->path); return $this->getETag(); }
[ "public", "function", "put", "(", "$", "data", ")", "{", "file_put_contents", "(", "$", "this", "->", "path", ",", "$", "data", ")", ";", "clearstatcache", "(", "true", ",", "$", "this", "->", "path", ")", ";", "return", "$", "this", "->", "getETag",...
Updates the data. Data is a readable stream resource. @param resource|string $data @return string
[ "Updates", "the", "data", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/FSExt/File.php#L28-L34
train
sabre-io/dav
lib/DAV/FSExt/File.php
File.patch
public function patch($data, $rangeType, $offset = null) { switch ($rangeType) { case 1: $f = fopen($this->path, 'a'); break; case 2: $f = fopen($this->path, 'c'); fseek($f, $offset); break; case 3: $f = fopen($this->path, 'c'); fseek($f, $offset, SEEK_END); break; } if (is_string($data)) { fwrite($f, $data); } else { stream_copy_to_stream($data, $f); } fclose($f); clearstatcache(true, $this->path); return $this->getETag(); }
php
public function patch($data, $rangeType, $offset = null) { switch ($rangeType) { case 1: $f = fopen($this->path, 'a'); break; case 2: $f = fopen($this->path, 'c'); fseek($f, $offset); break; case 3: $f = fopen($this->path, 'c'); fseek($f, $offset, SEEK_END); break; } if (is_string($data)) { fwrite($f, $data); } else { stream_copy_to_stream($data, $f); } fclose($f); clearstatcache(true, $this->path); return $this->getETag(); }
[ "public", "function", "patch", "(", "$", "data", ",", "$", "rangeType", ",", "$", "offset", "=", "null", ")", "{", "switch", "(", "$", "rangeType", ")", "{", "case", "1", ":", "$", "f", "=", "fopen", "(", "$", "this", "->", "path", ",", "'a'", ...
Updates the file based on a range specification. The first argument is the data, which is either a readable stream resource or a string. The second argument is the type of update we're doing. This is either: * 1. append * 2. update based on a start byte * 3. update based on an end byte ; The third argument is the start or end byte. After a successful put operation, you may choose to return an ETag. The ETAG must always be surrounded by double-quotes. These quotes must appear in the actual string you're returning. Clients may use the ETag from a PUT request to later on make sure that when they update the file, the contents haven't changed in the mean time. @param resource|string $data @param int $rangeType @param int $offset @return string|null
[ "Updates", "the", "file", "based", "on", "a", "range", "specification", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/FSExt/File.php#L64-L88
train
sabre-io/dav
lib/CalDAV/Plugin.php
Plugin.getCalendarHomeForPrincipal
public function getCalendarHomeForPrincipal($principalUrl) { // The default behavior for most sabre/dav servers is that there is a // principals root node, which contains users directly under it. // // This function assumes that there are two components in a principal // path. If there's more, we don't return a calendar home. This // excludes things like the calendar-proxy-read principal (which it // should). $parts = explode('/', trim($principalUrl, '/')); if (2 !== count($parts)) { return; } if ('principals' !== $parts[0]) { return; } return self::CALENDAR_ROOT.'/'.$parts[1]; }
php
public function getCalendarHomeForPrincipal($principalUrl) { // The default behavior for most sabre/dav servers is that there is a // principals root node, which contains users directly under it. // // This function assumes that there are two components in a principal // path. If there's more, we don't return a calendar home. This // excludes things like the calendar-proxy-read principal (which it // should). $parts = explode('/', trim($principalUrl, '/')); if (2 !== count($parts)) { return; } if ('principals' !== $parts[0]) { return; } return self::CALENDAR_ROOT.'/'.$parts[1]; }
[ "public", "function", "getCalendarHomeForPrincipal", "(", "$", "principalUrl", ")", "{", "// The default behavior for most sabre/dav servers is that there is a", "// principals root node, which contains users directly under it.", "//", "// This function assumes that there are two components in...
Returns the path to a principal's calendar home. The return url must not end with a slash. This function should return null in case a principal did not have a calendar home. @param string $principalUrl @return string
[ "Returns", "the", "path", "to", "a", "principal", "s", "calendar", "home", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Plugin.php#L104-L122
train
sabre-io/dav
lib/CalDAV/Plugin.php
Plugin.report
public function report($reportName, $report, $path) { switch ($reportName) { case '{'.self::NS_CALDAV.'}calendar-multiget': $this->server->transactionType = 'report-calendar-multiget'; $this->calendarMultiGetReport($report); return false; case '{'.self::NS_CALDAV.'}calendar-query': $this->server->transactionType = 'report-calendar-query'; $this->calendarQueryReport($report); return false; case '{'.self::NS_CALDAV.'}free-busy-query': $this->server->transactionType = 'report-free-busy-query'; $this->freeBusyQueryReport($report); return false; } }
php
public function report($reportName, $report, $path) { switch ($reportName) { case '{'.self::NS_CALDAV.'}calendar-multiget': $this->server->transactionType = 'report-calendar-multiget'; $this->calendarMultiGetReport($report); return false; case '{'.self::NS_CALDAV.'}calendar-query': $this->server->transactionType = 'report-calendar-query'; $this->calendarQueryReport($report); return false; case '{'.self::NS_CALDAV.'}free-busy-query': $this->server->transactionType = 'report-free-busy-query'; $this->freeBusyQueryReport($report); return false; } }
[ "public", "function", "report", "(", "$", "reportName", ",", "$", "report", ",", "$", "path", ")", "{", "switch", "(", "$", "reportName", ")", "{", "case", "'{'", ".", "self", "::", "NS_CALDAV", ".", "'}calendar-multiget'", ":", "$", "this", "->", "ser...
This functions handles REPORT requests specific to CalDAV. @param string $reportName @param mixed $report @param mixed $path @return bool
[ "This", "functions", "handles", "REPORT", "requests", "specific", "to", "CalDAV", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Plugin.php#L246-L265
train
sabre-io/dav
lib/CalDAV/Plugin.php
Plugin.httpMkCalendar
public function httpMkCalendar(RequestInterface $request, ResponseInterface $response) { $body = $request->getBodyAsString(); $path = $request->getPath(); $properties = []; if ($body) { try { $mkcalendar = $this->server->xml->expect( '{urn:ietf:params:xml:ns:caldav}mkcalendar', $body ); } catch (\Sabre\Xml\ParseException $e) { throw new BadRequest($e->getMessage(), 0, $e); } $properties = $mkcalendar->getProperties(); } // iCal abuses MKCALENDAR since iCal 10.9.2 to create server-stored // subscriptions. Before that it used MKCOL which was the correct way // to do this. // // If the body had a {DAV:}resourcetype, it means we stumbled upon this // request, and we simply use it instead of the pre-defined list. if (isset($properties['{DAV:}resourcetype'])) { $resourceType = $properties['{DAV:}resourcetype']->getValue(); } else { $resourceType = ['{DAV:}collection', '{urn:ietf:params:xml:ns:caldav}calendar']; } $this->server->createCollection($path, new MkCol($resourceType, $properties)); $response->setStatus(201); $response->setHeader('Content-Length', 0); // This breaks the method chain. return false; }
php
public function httpMkCalendar(RequestInterface $request, ResponseInterface $response) { $body = $request->getBodyAsString(); $path = $request->getPath(); $properties = []; if ($body) { try { $mkcalendar = $this->server->xml->expect( '{urn:ietf:params:xml:ns:caldav}mkcalendar', $body ); } catch (\Sabre\Xml\ParseException $e) { throw new BadRequest($e->getMessage(), 0, $e); } $properties = $mkcalendar->getProperties(); } // iCal abuses MKCALENDAR since iCal 10.9.2 to create server-stored // subscriptions. Before that it used MKCOL which was the correct way // to do this. // // If the body had a {DAV:}resourcetype, it means we stumbled upon this // request, and we simply use it instead of the pre-defined list. if (isset($properties['{DAV:}resourcetype'])) { $resourceType = $properties['{DAV:}resourcetype']->getValue(); } else { $resourceType = ['{DAV:}collection', '{urn:ietf:params:xml:ns:caldav}calendar']; } $this->server->createCollection($path, new MkCol($resourceType, $properties)); $response->setStatus(201); $response->setHeader('Content-Length', 0); // This breaks the method chain. return false; }
[ "public", "function", "httpMkCalendar", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "body", "=", "$", "request", "->", "getBodyAsString", "(", ")", ";", "$", "path", "=", "$", "request", "->", "getPath",...
This function handles the MKCALENDAR HTTP method, which creates a new calendar. @param RequestInterface $request @param ResponseInterface $response @return bool
[ "This", "function", "handles", "the", "MKCALENDAR", "HTTP", "method", "which", "creates", "a", "new", "calendar", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Plugin.php#L276-L314
train
sabre-io/dav
lib/CalDAV/Plugin.php
Plugin.calendarMultiGetReport
public function calendarMultiGetReport($report) { $needsJson = 'application/calendar+json' === $report->contentType; $timeZones = []; $propertyList = []; $paths = array_map( [$this->server, 'calculateUri'], $report->hrefs ); foreach ($this->server->getPropertiesForMultiplePaths($paths, $report->properties) as $uri => $objProps) { if (($needsJson || $report->expand) && isset($objProps[200]['{'.self::NS_CALDAV.'}calendar-data'])) { $vObject = VObject\Reader::read($objProps[200]['{'.self::NS_CALDAV.'}calendar-data']); if ($report->expand) { // We're expanding, and for that we need to figure out the // calendar's timezone. list($calendarPath) = Uri\split($uri); if (!isset($timeZones[$calendarPath])) { // Checking the calendar-timezone property. $tzProp = '{'.self::NS_CALDAV.'}calendar-timezone'; $tzResult = $this->server->getProperties($calendarPath, [$tzProp]); if (isset($tzResult[$tzProp])) { // This property contains a VCALENDAR with a single // VTIMEZONE. $vtimezoneObj = VObject\Reader::read($tzResult[$tzProp]); $timeZone = $vtimezoneObj->VTIMEZONE->getTimeZone(); } else { // Defaulting to UTC. $timeZone = new DateTimeZone('UTC'); } $timeZones[$calendarPath] = $timeZone; } $vObject = $vObject->expand($report->expand['start'], $report->expand['end'], $timeZones[$calendarPath]); } if ($needsJson) { $objProps[200]['{'.self::NS_CALDAV.'}calendar-data'] = json_encode($vObject->jsonSerialize()); } else { $objProps[200]['{'.self::NS_CALDAV.'}calendar-data'] = $vObject->serialize(); } // Destroy circular references so PHP will garbage collect the // object. $vObject->destroy(); } $propertyList[] = $objProps; } $prefer = $this->server->getHTTPPrefer(); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setHeader('Vary', 'Brief,Prefer'); $this->server->httpResponse->setBody($this->server->generateMultiStatus($propertyList, 'minimal' === $prefer['return'])); }
php
public function calendarMultiGetReport($report) { $needsJson = 'application/calendar+json' === $report->contentType; $timeZones = []; $propertyList = []; $paths = array_map( [$this->server, 'calculateUri'], $report->hrefs ); foreach ($this->server->getPropertiesForMultiplePaths($paths, $report->properties) as $uri => $objProps) { if (($needsJson || $report->expand) && isset($objProps[200]['{'.self::NS_CALDAV.'}calendar-data'])) { $vObject = VObject\Reader::read($objProps[200]['{'.self::NS_CALDAV.'}calendar-data']); if ($report->expand) { // We're expanding, and for that we need to figure out the // calendar's timezone. list($calendarPath) = Uri\split($uri); if (!isset($timeZones[$calendarPath])) { // Checking the calendar-timezone property. $tzProp = '{'.self::NS_CALDAV.'}calendar-timezone'; $tzResult = $this->server->getProperties($calendarPath, [$tzProp]); if (isset($tzResult[$tzProp])) { // This property contains a VCALENDAR with a single // VTIMEZONE. $vtimezoneObj = VObject\Reader::read($tzResult[$tzProp]); $timeZone = $vtimezoneObj->VTIMEZONE->getTimeZone(); } else { // Defaulting to UTC. $timeZone = new DateTimeZone('UTC'); } $timeZones[$calendarPath] = $timeZone; } $vObject = $vObject->expand($report->expand['start'], $report->expand['end'], $timeZones[$calendarPath]); } if ($needsJson) { $objProps[200]['{'.self::NS_CALDAV.'}calendar-data'] = json_encode($vObject->jsonSerialize()); } else { $objProps[200]['{'.self::NS_CALDAV.'}calendar-data'] = $vObject->serialize(); } // Destroy circular references so PHP will garbage collect the // object. $vObject->destroy(); } $propertyList[] = $objProps; } $prefer = $this->server->getHTTPPrefer(); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setHeader('Vary', 'Brief,Prefer'); $this->server->httpResponse->setBody($this->server->generateMultiStatus($propertyList, 'minimal' === $prefer['return'])); }
[ "public", "function", "calendarMultiGetReport", "(", "$", "report", ")", "{", "$", "needsJson", "=", "'application/calendar+json'", "===", "$", "report", "->", "contentType", ";", "$", "timeZones", "=", "[", "]", ";", "$", "propertyList", "=", "[", "]", ";",...
This function handles the calendar-multiget REPORT. This report is used by the client to fetch the content of a series of urls. Effectively avoiding a lot of redundant requests. @param CalendarMultiGetReport $report
[ "This", "function", "handles", "the", "calendar", "-", "multiget", "REPORT", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Plugin.php#L429-L486
train
sabre-io/dav
lib/CalDAV/Plugin.php
Plugin.getSupportedPrivilegeSet
public function getSupportedPrivilegeSet(INode $node, array &$supportedPrivilegeSet) { if ($node instanceof ICalendar) { $supportedPrivilegeSet['{DAV:}read']['aggregates']['{'.self::NS_CALDAV.'}read-free-busy'] = [ 'abstract' => false, 'aggregates' => [], ]; } }
php
public function getSupportedPrivilegeSet(INode $node, array &$supportedPrivilegeSet) { if ($node instanceof ICalendar) { $supportedPrivilegeSet['{DAV:}read']['aggregates']['{'.self::NS_CALDAV.'}read-free-busy'] = [ 'abstract' => false, 'aggregates' => [], ]; } }
[ "public", "function", "getSupportedPrivilegeSet", "(", "INode", "$", "node", ",", "array", "&", "$", "supportedPrivilegeSet", ")", "{", "if", "(", "$", "node", "instanceof", "ICalendar", ")", "{", "$", "supportedPrivilegeSet", "[", "'{DAV:}read'", "]", "[", "'...
This method is triggered whenever a subsystem reqeuests the privileges that are supported on a particular node. @param INode $node @param array $supportedPrivilegeSet
[ "This", "method", "is", "triggered", "whenever", "a", "subsystem", "reqeuests", "the", "privileges", "that", "are", "supported", "on", "a", "particular", "node", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Plugin.php#L930-L938
train
sabre-io/dav
lib/CalDAV/Plugin.php
Plugin.htmlActionsPanel
public function htmlActionsPanel(DAV\INode $node, &$output) { if (!$node instanceof CalendarHome) { return; } $output .= '<tr><td colspan="2"><form method="post" action=""> <h3>Create new calendar</h3> <input type="hidden" name="sabreAction" value="mkcol" /> <input type="hidden" name="resourceType" value="{DAV:}collection,{'.self::NS_CALDAV.'}calendar" /> <label>Name (uri):</label> <input type="text" name="name" /><br /> <label>Display name:</label> <input type="text" name="{DAV:}displayname" /><br /> <input type="submit" value="create" /> </form> </td></tr>'; return false; }
php
public function htmlActionsPanel(DAV\INode $node, &$output) { if (!$node instanceof CalendarHome) { return; } $output .= '<tr><td colspan="2"><form method="post" action=""> <h3>Create new calendar</h3> <input type="hidden" name="sabreAction" value="mkcol" /> <input type="hidden" name="resourceType" value="{DAV:}collection,{'.self::NS_CALDAV.'}calendar" /> <label>Name (uri):</label> <input type="text" name="name" /><br /> <label>Display name:</label> <input type="text" name="{DAV:}displayname" /><br /> <input type="submit" value="create" /> </form> </td></tr>'; return false; }
[ "public", "function", "htmlActionsPanel", "(", "DAV", "\\", "INode", "$", "node", ",", "&", "$", "output", ")", "{", "if", "(", "!", "$", "node", "instanceof", "CalendarHome", ")", "{", "return", ";", "}", "$", "output", ".=", "'<tr><td colspan=\"2\"><form...
This method is used to generate HTML output for the DAV\Browser\Plugin. This allows us to generate an interface users can use to create new calendars. @param DAV\INode $node @param string $output @return bool
[ "This", "method", "is", "used", "to", "generate", "HTML", "output", "for", "the", "DAV", "\\", "Browser", "\\", "Plugin", ".", "This", "allows", "us", "to", "generate", "an", "interface", "users", "can", "use", "to", "create", "new", "calendars", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Plugin.php#L950-L967
train
sabre-io/dav
lib/CalDAV/CalendarQueryValidator.php
CalendarQueryValidator.validate
public function validate(VObject\Component\VCalendar $vObject, array $filters) { // The top level object is always a component filter. // We'll parse it manually, as it's pretty simple. if ($vObject->name !== $filters['name']) { return false; } return $this->validateCompFilters($vObject, $filters['comp-filters']) && $this->validatePropFilters($vObject, $filters['prop-filters']); }
php
public function validate(VObject\Component\VCalendar $vObject, array $filters) { // The top level object is always a component filter. // We'll parse it manually, as it's pretty simple. if ($vObject->name !== $filters['name']) { return false; } return $this->validateCompFilters($vObject, $filters['comp-filters']) && $this->validatePropFilters($vObject, $filters['prop-filters']); }
[ "public", "function", "validate", "(", "VObject", "\\", "Component", "\\", "VCalendar", "$", "vObject", ",", "array", "$", "filters", ")", "{", "// The top level object is always a component filter.", "// We'll parse it manually, as it's pretty simple.", "if", "(", "$", "...
Verify if a list of filters applies to the calendar data object. The list of filters must be formatted as parsed by \Sabre\CalDAV\CalendarQueryParser @param VObject\Component\VCalendar $vObject @param array $filters @return bool
[ "Verify", "if", "a", "list", "of", "filters", "applies", "to", "the", "calendar", "data", "object", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/CalendarQueryValidator.php#L35-L46
train
sabre-io/dav
lib/CalDAV/CalendarQueryValidator.php
CalendarQueryValidator.validateCompFilters
protected function validateCompFilters(VObject\Component $parent, array $filters) { foreach ($filters as $filter) { $isDefined = isset($parent->{$filter['name']}); if ($filter['is-not-defined']) { if ($isDefined) { return false; } else { continue; } } if (!$isDefined) { return false; } if ($filter['time-range']) { foreach ($parent->{$filter['name']} as $subComponent) { if ($this->validateTimeRange($subComponent, $filter['time-range']['start'], $filter['time-range']['end'])) { continue 2; } } return false; } if (!$filter['comp-filters'] && !$filter['prop-filters']) { continue; } // If there are sub-filters, we need to find at least one component // for which the subfilters hold true. foreach ($parent->{$filter['name']} as $subComponent) { if ( $this->validateCompFilters($subComponent, $filter['comp-filters']) && $this->validatePropFilters($subComponent, $filter['prop-filters'])) { // We had a match, so this comp-filter succeeds continue 2; } } // If we got here it means there were sub-comp-filters or // sub-prop-filters and there was no match. This means this filter // needs to return false. return false; } // If we got here it means we got through all comp-filters alive so the // filters were all true. return true; }
php
protected function validateCompFilters(VObject\Component $parent, array $filters) { foreach ($filters as $filter) { $isDefined = isset($parent->{$filter['name']}); if ($filter['is-not-defined']) { if ($isDefined) { return false; } else { continue; } } if (!$isDefined) { return false; } if ($filter['time-range']) { foreach ($parent->{$filter['name']} as $subComponent) { if ($this->validateTimeRange($subComponent, $filter['time-range']['start'], $filter['time-range']['end'])) { continue 2; } } return false; } if (!$filter['comp-filters'] && !$filter['prop-filters']) { continue; } // If there are sub-filters, we need to find at least one component // for which the subfilters hold true. foreach ($parent->{$filter['name']} as $subComponent) { if ( $this->validateCompFilters($subComponent, $filter['comp-filters']) && $this->validatePropFilters($subComponent, $filter['prop-filters'])) { // We had a match, so this comp-filter succeeds continue 2; } } // If we got here it means there were sub-comp-filters or // sub-prop-filters and there was no match. This means this filter // needs to return false. return false; } // If we got here it means we got through all comp-filters alive so the // filters were all true. return true; }
[ "protected", "function", "validateCompFilters", "(", "VObject", "\\", "Component", "$", "parent", ",", "array", "$", "filters", ")", "{", "foreach", "(", "$", "filters", "as", "$", "filter", ")", "{", "$", "isDefined", "=", "isset", "(", "$", "parent", "...
This method checks the validity of comp-filters. A list of comp-filters needs to be specified. Also the parent of the component we're checking should be specified, not the component to check itself. @param VObject\Component $parent @param array $filters @return bool
[ "This", "method", "checks", "the", "validity", "of", "comp", "-", "filters", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/CalendarQueryValidator.php#L60-L110
train
sabre-io/dav
lib/CalDAV/CalendarQueryValidator.php
CalendarQueryValidator.validateParamFilters
protected function validateParamFilters(VObject\Property $parent, array $filters) { foreach ($filters as $filter) { $isDefined = isset($parent[$filter['name']]); if ($filter['is-not-defined']) { if ($isDefined) { return false; } else { continue; } } if (!$isDefined) { return false; } if (!$filter['text-match']) { continue; } // If there are sub-filters, we need to find at least one parameter // for which the subfilters hold true. foreach ($parent[$filter['name']]->getParts() as $paramPart) { if ($this->validateTextMatch($paramPart, $filter['text-match'])) { // We had a match, so this param-filter succeeds continue 2; } } // If we got here it means there was a text-match filter and there // were no matches. This means the filter needs to return false. return false; } // If we got here it means we got through all param-filters alive so the // filters were all true. return true; }
php
protected function validateParamFilters(VObject\Property $parent, array $filters) { foreach ($filters as $filter) { $isDefined = isset($parent[$filter['name']]); if ($filter['is-not-defined']) { if ($isDefined) { return false; } else { continue; } } if (!$isDefined) { return false; } if (!$filter['text-match']) { continue; } // If there are sub-filters, we need to find at least one parameter // for which the subfilters hold true. foreach ($parent[$filter['name']]->getParts() as $paramPart) { if ($this->validateTextMatch($paramPart, $filter['text-match'])) { // We had a match, so this param-filter succeeds continue 2; } } // If we got here it means there was a text-match filter and there // were no matches. This means the filter needs to return false. return false; } // If we got here it means we got through all param-filters alive so the // filters were all true. return true; }
[ "protected", "function", "validateParamFilters", "(", "VObject", "\\", "Property", "$", "parent", ",", "array", "$", "filters", ")", "{", "foreach", "(", "$", "filters", "as", "$", "filter", ")", "{", "$", "isDefined", "=", "isset", "(", "$", "parent", "...
This method checks the validity of param-filters. A list of param-filters needs to be specified. Also the parent of the parameter we're checking should be specified, not the parameter to check itself. @param VObject\Property $parent @param array $filters @return bool
[ "This", "method", "checks", "the", "validity", "of", "param", "-", "filters", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/CalendarQueryValidator.php#L189-L226
train
sabre-io/dav
lib/CalDAV/CalendarQueryValidator.php
CalendarQueryValidator.validateTextMatch
protected function validateTextMatch($check, array $textMatch) { if ($check instanceof VObject\Node) { $check = $check->getValue(); } $isMatching = \Sabre\DAV\StringUtil::textMatch($check, $textMatch['value'], $textMatch['collation']); return $textMatch['negate-condition'] xor $isMatching; }
php
protected function validateTextMatch($check, array $textMatch) { if ($check instanceof VObject\Node) { $check = $check->getValue(); } $isMatching = \Sabre\DAV\StringUtil::textMatch($check, $textMatch['value'], $textMatch['collation']); return $textMatch['negate-condition'] xor $isMatching; }
[ "protected", "function", "validateTextMatch", "(", "$", "check", ",", "array", "$", "textMatch", ")", "{", "if", "(", "$", "check", "instanceof", "VObject", "\\", "Node", ")", "{", "$", "check", "=", "$", "check", "->", "getValue", "(", ")", ";", "}", ...
This method checks the validity of a text-match. A single text-match should be specified as well as the specific property or parameter we need to validate. @param VObject\Node|string $check value to check against @param array $textMatch @return bool
[ "This", "method", "checks", "the", "validity", "of", "a", "text", "-", "match", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/CalendarQueryValidator.php#L239-L248
train
sabre-io/dav
lib/CalDAV/CalendarQueryValidator.php
CalendarQueryValidator.validateTimeRange
protected function validateTimeRange(VObject\Node $component, $start, $end) { if (is_null($start)) { $start = new DateTime('1900-01-01'); } if (is_null($end)) { $end = new DateTime('3000-01-01'); } switch ($component->name) { case 'VEVENT': case 'VTODO': case 'VJOURNAL': return $component->isInTimeRange($start, $end); case 'VALARM': // If the valarm is wrapped in a recurring event, we need to // expand the recursions, and validate each. // // Our datamodel doesn't easily allow us to do this straight // in the VALARM component code, so this is a hack, and an // expensive one too. if ('VEVENT' === $component->parent->name && $component->parent->RRULE) { // Fire up the iterator! $it = new VObject\Recur\EventIterator($component->parent->parent, (string) $component->parent->UID); while ($it->valid()) { $expandedEvent = $it->getEventObject(); // We need to check from these expanded alarms, which // one is the first to trigger. Based on this, we can // determine if we can 'give up' expanding events. $firstAlarm = null; if (null !== $expandedEvent->VALARM) { foreach ($expandedEvent->VALARM as $expandedAlarm) { $effectiveTrigger = $expandedAlarm->getEffectiveTriggerTime(); if ($expandedAlarm->isInTimeRange($start, $end)) { return true; } if ('DATE-TIME' === (string) $expandedAlarm->TRIGGER['VALUE']) { // This is an alarm with a non-relative trigger // time, likely created by a buggy client. The // implication is that every alarm in this // recurring event trigger at the exact same // time. It doesn't make sense to traverse // further. } else { // We store the first alarm as a means to // figure out when we can stop traversing. if (!$firstAlarm || $effectiveTrigger < $firstAlarm) { $firstAlarm = $effectiveTrigger; } } } } if (is_null($firstAlarm)) { // No alarm was found. // // Or technically: No alarm that will change for // every instance of the recurrence was found, // which means we can assume there was no match. return false; } if ($firstAlarm > $end) { return false; } $it->next(); } return false; } else { return $component->isInTimeRange($start, $end); } // no break case 'VFREEBUSY': throw new \Sabre\DAV\Exception\NotImplemented('time-range filters are currently not supported on '.$component->name.' components'); case 'COMPLETED': case 'CREATED': case 'DTEND': case 'DTSTAMP': case 'DTSTART': case 'DUE': case 'LAST-MODIFIED': return $start <= $component->getDateTime() && $end >= $component->getDateTime(); default: throw new \Sabre\DAV\Exception\BadRequest('You cannot create a time-range filter on a '.$component->name.' component'); } }
php
protected function validateTimeRange(VObject\Node $component, $start, $end) { if (is_null($start)) { $start = new DateTime('1900-01-01'); } if (is_null($end)) { $end = new DateTime('3000-01-01'); } switch ($component->name) { case 'VEVENT': case 'VTODO': case 'VJOURNAL': return $component->isInTimeRange($start, $end); case 'VALARM': // If the valarm is wrapped in a recurring event, we need to // expand the recursions, and validate each. // // Our datamodel doesn't easily allow us to do this straight // in the VALARM component code, so this is a hack, and an // expensive one too. if ('VEVENT' === $component->parent->name && $component->parent->RRULE) { // Fire up the iterator! $it = new VObject\Recur\EventIterator($component->parent->parent, (string) $component->parent->UID); while ($it->valid()) { $expandedEvent = $it->getEventObject(); // We need to check from these expanded alarms, which // one is the first to trigger. Based on this, we can // determine if we can 'give up' expanding events. $firstAlarm = null; if (null !== $expandedEvent->VALARM) { foreach ($expandedEvent->VALARM as $expandedAlarm) { $effectiveTrigger = $expandedAlarm->getEffectiveTriggerTime(); if ($expandedAlarm->isInTimeRange($start, $end)) { return true; } if ('DATE-TIME' === (string) $expandedAlarm->TRIGGER['VALUE']) { // This is an alarm with a non-relative trigger // time, likely created by a buggy client. The // implication is that every alarm in this // recurring event trigger at the exact same // time. It doesn't make sense to traverse // further. } else { // We store the first alarm as a means to // figure out when we can stop traversing. if (!$firstAlarm || $effectiveTrigger < $firstAlarm) { $firstAlarm = $effectiveTrigger; } } } } if (is_null($firstAlarm)) { // No alarm was found. // // Or technically: No alarm that will change for // every instance of the recurrence was found, // which means we can assume there was no match. return false; } if ($firstAlarm > $end) { return false; } $it->next(); } return false; } else { return $component->isInTimeRange($start, $end); } // no break case 'VFREEBUSY': throw new \Sabre\DAV\Exception\NotImplemented('time-range filters are currently not supported on '.$component->name.' components'); case 'COMPLETED': case 'CREATED': case 'DTEND': case 'DTSTAMP': case 'DTSTART': case 'DUE': case 'LAST-MODIFIED': return $start <= $component->getDateTime() && $end >= $component->getDateTime(); default: throw new \Sabre\DAV\Exception\BadRequest('You cannot create a time-range filter on a '.$component->name.' component'); } }
[ "protected", "function", "validateTimeRange", "(", "VObject", "\\", "Node", "$", "component", ",", "$", "start", ",", "$", "end", ")", "{", "if", "(", "is_null", "(", "$", "start", ")", ")", "{", "$", "start", "=", "new", "DateTime", "(", "'1900-01-01'...
Validates if a component matches the given time range. This is all based on the rules specified in rfc4791, which are quite complex. @param VObject\Node $component @param DateTime $start @param DateTime $end @return bool
[ "Validates", "if", "a", "component", "matches", "the", "given", "time", "range", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/CalendarQueryValidator.php#L262-L353
train
sabre-io/dav
lib/DAV/Browser/GuessContentType.php
GuessContentType.propFind
public function propFind(PropFind $propFind, INode $node) { $propFind->handle('{DAV:}getcontenttype', function () use ($propFind) { list(, $fileName) = Uri\split($propFind->getPath()); return $this->getContentType($fileName); }); }
php
public function propFind(PropFind $propFind, INode $node) { $propFind->handle('{DAV:}getcontenttype', function () use ($propFind) { list(, $fileName) = Uri\split($propFind->getPath()); return $this->getContentType($fileName); }); }
[ "public", "function", "propFind", "(", "PropFind", "$", "propFind", ",", "INode", "$", "node", ")", "{", "$", "propFind", "->", "handle", "(", "'{DAV:}getcontenttype'", ",", "function", "(", ")", "use", "(", "$", "propFind", ")", "{", "list", "(", ",", ...
Our PROPFIND handler. Here we set a contenttype, if the node didn't already have one. @param PropFind $propFind @param INode $node
[ "Our", "PROPFIND", "handler", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Browser/GuessContentType.php#L70-L77
train
sabre-io/dav
lib/DAV/Browser/GuessContentType.php
GuessContentType.getContentType
protected function getContentType($fileName) { // Just grabbing the extension $extension = strtolower(substr($fileName, strrpos($fileName, '.') + 1)); if (isset($this->extensionMap[$extension])) { return $this->extensionMap[$extension]; } return 'application/octet-stream'; }
php
protected function getContentType($fileName) { // Just grabbing the extension $extension = strtolower(substr($fileName, strrpos($fileName, '.') + 1)); if (isset($this->extensionMap[$extension])) { return $this->extensionMap[$extension]; } return 'application/octet-stream'; }
[ "protected", "function", "getContentType", "(", "$", "fileName", ")", "{", "// Just grabbing the extension", "$", "extension", "=", "strtolower", "(", "substr", "(", "$", "fileName", ",", "strrpos", "(", "$", "fileName", ",", "'.'", ")", "+", "1", ")", ")", ...
Simple method to return the contenttype. @param string $fileName @return string
[ "Simple", "method", "to", "return", "the", "contenttype", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Browser/GuessContentType.php#L86-L95
train
sabre-io/dav
lib/DAV/Auth/Backend/PDO.php
PDO.getDigestHash
public function getDigestHash($realm, $username) { $stmt = $this->pdo->prepare('SELECT digesta1 FROM '.$this->tableName.' WHERE username = ?'); $stmt->execute([$username]); return $stmt->fetchColumn() ?: null; }
php
public function getDigestHash($realm, $username) { $stmt = $this->pdo->prepare('SELECT digesta1 FROM '.$this->tableName.' WHERE username = ?'); $stmt->execute([$username]); return $stmt->fetchColumn() ?: null; }
[ "public", "function", "getDigestHash", "(", "$", "realm", ",", "$", "username", ")", "{", "$", "stmt", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "'SELECT digesta1 FROM '", ".", "$", "this", "->", "tableName", ".", "' WHERE username = ?'", ")", "...
Returns the digest hash for a user. @param string $realm @param string $username @return string|null
[ "Returns", "the", "digest", "hash", "for", "a", "user", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Auth/Backend/PDO.php#L50-L56
train
sabre-io/dav
lib/DAV/PropPatch.php
PropPatch.handleRemaining
public function handleRemaining(callable $callback) { $properties = $this->getRemainingMutations(); if (!$properties) { // Nothing to do, don't register callback return; } foreach ($properties as $propertyName) { // HTTP Accepted $this->result[$propertyName] = 202; $this->propertyUpdateCallbacks[] = [ $properties, $callback, ]; } }
php
public function handleRemaining(callable $callback) { $properties = $this->getRemainingMutations(); if (!$properties) { // Nothing to do, don't register callback return; } foreach ($properties as $propertyName) { // HTTP Accepted $this->result[$propertyName] = 202; $this->propertyUpdateCallbacks[] = [ $properties, $callback, ]; } }
[ "public", "function", "handleRemaining", "(", "callable", "$", "callback", ")", "{", "$", "properties", "=", "$", "this", "->", "getRemainingMutations", "(", ")", ";", "if", "(", "!", "$", "properties", ")", "{", "// Nothing to do, don't register callback", "ret...
Call this function if you wish to handle _all_ properties that haven't been handled by anything else yet. Note that you effectively claim with this that you promise to process _all_ properties that are coming in. @param callable $callback
[ "Call", "this", "function", "if", "you", "wish", "to", "handle", "_all_", "properties", "that", "haven", "t", "been", "handled", "by", "anything", "else", "yet", ".", "Note", "that", "you", "effectively", "claim", "with", "this", "that", "you", "promise", ...
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropPatch.php#L118-L135
train
sabre-io/dav
lib/DAV/PropPatch.php
PropPatch.setResultCode
public function setResultCode($properties, $resultCode) { foreach ((array) $properties as $propertyName) { $this->result[$propertyName] = $resultCode; } if ($resultCode >= 400) { $this->failed = true; } }
php
public function setResultCode($properties, $resultCode) { foreach ((array) $properties as $propertyName) { $this->result[$propertyName] = $resultCode; } if ($resultCode >= 400) { $this->failed = true; } }
[ "public", "function", "setResultCode", "(", "$", "properties", ",", "$", "resultCode", ")", "{", "foreach", "(", "(", "array", ")", "$", "properties", "as", "$", "propertyName", ")", "{", "$", "this", "->", "result", "[", "$", "propertyName", "]", "=", ...
Sets the result code for one or more properties. @param string|string[] $properties @param int $resultCode
[ "Sets", "the", "result", "code", "for", "one", "or", "more", "properties", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropPatch.php#L143-L152
train
sabre-io/dav
lib/DAV/PropPatch.php
PropPatch.getRemainingMutations
public function getRemainingMutations() { $remaining = []; foreach ($this->mutations as $propertyName => $propValue) { if (!isset($this->result[$propertyName])) { $remaining[] = $propertyName; } } return $remaining; }
php
public function getRemainingMutations() { $remaining = []; foreach ($this->mutations as $propertyName => $propValue) { if (!isset($this->result[$propertyName])) { $remaining[] = $propertyName; } } return $remaining; }
[ "public", "function", "getRemainingMutations", "(", ")", "{", "$", "remaining", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "mutations", "as", "$", "propertyName", "=>", "$", "propValue", ")", "{", "if", "(", "!", "isset", "(", "$", "this", ...
Returns the list of properties that don't have a result code yet. This method returns a list of property names, but not its values. @return string[]
[ "Returns", "the", "list", "of", "properties", "that", "don", "t", "have", "a", "result", "code", "yet", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropPatch.php#L174-L184
train
sabre-io/dav
lib/DAV/PropPatch.php
PropPatch.commit
public function commit() { // First we validate if every property has a handler foreach ($this->mutations as $propertyName => $value) { if (!isset($this->result[$propertyName])) { $this->failed = true; $this->result[$propertyName] = 403; } } foreach ($this->propertyUpdateCallbacks as $callbackInfo) { if ($this->failed) { break; } if (is_string($callbackInfo[0])) { $this->doCallbackSingleProp($callbackInfo[0], $callbackInfo[1]); } else { $this->doCallbackMultiProp($callbackInfo[0], $callbackInfo[1]); } } /* * If anywhere in this operation updating a property failed, we must * update all other properties accordingly. */ if ($this->failed) { foreach ($this->result as $propertyName => $status) { if (202 === $status) { // Failed dependency $this->result[$propertyName] = 424; } } } return !$this->failed; }
php
public function commit() { // First we validate if every property has a handler foreach ($this->mutations as $propertyName => $value) { if (!isset($this->result[$propertyName])) { $this->failed = true; $this->result[$propertyName] = 403; } } foreach ($this->propertyUpdateCallbacks as $callbackInfo) { if ($this->failed) { break; } if (is_string($callbackInfo[0])) { $this->doCallbackSingleProp($callbackInfo[0], $callbackInfo[1]); } else { $this->doCallbackMultiProp($callbackInfo[0], $callbackInfo[1]); } } /* * If anywhere in this operation updating a property failed, we must * update all other properties accordingly. */ if ($this->failed) { foreach ($this->result as $propertyName => $status) { if (202 === $status) { // Failed dependency $this->result[$propertyName] = 424; } } } return !$this->failed; }
[ "public", "function", "commit", "(", ")", "{", "// First we validate if every property has a handler", "foreach", "(", "$", "this", "->", "mutations", "as", "$", "propertyName", "=>", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "...
Performs the actual update, and calls all callbacks. This method returns true or false depending on if the operation was successful. @return bool
[ "Performs", "the", "actual", "update", "and", "calls", "all", "callbacks", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropPatch.php#L213-L248
train
sabre-io/dav
lib/DAV/PropPatch.php
PropPatch.doCallBackSingleProp
private function doCallBackSingleProp($propertyName, callable $callback) { $result = $callback($this->mutations[$propertyName]); if (is_bool($result)) { if ($result) { if (is_null($this->mutations[$propertyName])) { // Delete $result = 204; } else { // Update $result = 200; } } else { // Fail $result = 403; } } if (!is_int($result)) { throw new UnexpectedValueException('A callback sent to handle() did not return an int or a bool'); } $this->result[$propertyName] = $result; if ($result >= 400) { $this->failed = true; } }
php
private function doCallBackSingleProp($propertyName, callable $callback) { $result = $callback($this->mutations[$propertyName]); if (is_bool($result)) { if ($result) { if (is_null($this->mutations[$propertyName])) { // Delete $result = 204; } else { // Update $result = 200; } } else { // Fail $result = 403; } } if (!is_int($result)) { throw new UnexpectedValueException('A callback sent to handle() did not return an int or a bool'); } $this->result[$propertyName] = $result; if ($result >= 400) { $this->failed = true; } }
[ "private", "function", "doCallBackSingleProp", "(", "$", "propertyName", ",", "callable", "$", "callback", ")", "{", "$", "result", "=", "$", "callback", "(", "$", "this", "->", "mutations", "[", "$", "propertyName", "]", ")", ";", "if", "(", "is_bool", ...
Executes a property callback with the single-property syntax. @param string $propertyName @param callable $callback
[ "Executes", "a", "property", "callback", "with", "the", "single", "-", "property", "syntax", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropPatch.php#L256-L280
train
sabre-io/dav
lib/DAV/PropPatch.php
PropPatch.doCallBackMultiProp
private function doCallBackMultiProp(array $propertyList, callable $callback) { $argument = []; foreach ($propertyList as $propertyName) { $argument[$propertyName] = $this->mutations[$propertyName]; } $result = $callback($argument); if (is_array($result)) { foreach ($propertyList as $propertyName) { if (!isset($result[$propertyName])) { $resultCode = 500; } else { $resultCode = $result[$propertyName]; } if ($resultCode >= 400) { $this->failed = true; } $this->result[$propertyName] = $resultCode; } } elseif (true === $result) { // Success foreach ($argument as $propertyName => $propertyValue) { $this->result[$propertyName] = is_null($propertyValue) ? 204 : 200; } } elseif (false === $result) { // Fail :( $this->failed = true; foreach ($propertyList as $propertyName) { $this->result[$propertyName] = 403; } } else { throw new UnexpectedValueException('A callback sent to handle() did not return an array or a bool'); } }
php
private function doCallBackMultiProp(array $propertyList, callable $callback) { $argument = []; foreach ($propertyList as $propertyName) { $argument[$propertyName] = $this->mutations[$propertyName]; } $result = $callback($argument); if (is_array($result)) { foreach ($propertyList as $propertyName) { if (!isset($result[$propertyName])) { $resultCode = 500; } else { $resultCode = $result[$propertyName]; } if ($resultCode >= 400) { $this->failed = true; } $this->result[$propertyName] = $resultCode; } } elseif (true === $result) { // Success foreach ($argument as $propertyName => $propertyValue) { $this->result[$propertyName] = is_null($propertyValue) ? 204 : 200; } } elseif (false === $result) { // Fail :( $this->failed = true; foreach ($propertyList as $propertyName) { $this->result[$propertyName] = 403; } } else { throw new UnexpectedValueException('A callback sent to handle() did not return an array or a bool'); } }
[ "private", "function", "doCallBackMultiProp", "(", "array", "$", "propertyList", ",", "callable", "$", "callback", ")", "{", "$", "argument", "=", "[", "]", ";", "foreach", "(", "$", "propertyList", "as", "$", "propertyName", ")", "{", "$", "argument", "["...
Executes a property callback with the multi-property syntax. @param array $propertyList @param callable $callback
[ "Executes", "a", "property", "callback", "with", "the", "multi", "-", "property", "syntax", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropPatch.php#L288-L323
train
sabre-io/dav
lib/DAV/Browser/HtmlOutputHelper.php
HtmlOutputHelper.xmlName
public function xmlName($element) { list($ns, $localName) = XmlService::parseClarkNotation($element); if (isset($this->namespaceMap[$ns])) { $propName = $this->namespaceMap[$ns].':'.$localName; } else { $propName = $element; } return '<span title="'.$this->h($element).'">'.$this->h($propName).'</span>'; }
php
public function xmlName($element) { list($ns, $localName) = XmlService::parseClarkNotation($element); if (isset($this->namespaceMap[$ns])) { $propName = $this->namespaceMap[$ns].':'.$localName; } else { $propName = $element; } return '<span title="'.$this->h($element).'">'.$this->h($propName).'</span>'; }
[ "public", "function", "xmlName", "(", "$", "element", ")", "{", "list", "(", "$", "ns", ",", "$", "localName", ")", "=", "XmlService", "::", "parseClarkNotation", "(", "$", "element", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "namespaceMap"...
This method takes an xml element in clark-notation, and turns it into a shortened version with a prefix, if it was a known namespace. @param string $element @return string
[ "This", "method", "takes", "an", "xml", "element", "in", "clark", "-", "notation", "and", "turns", "it", "into", "a", "shortened", "version", "with", "a", "prefix", "if", "it", "was", "a", "known", "namespace", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Browser/HtmlOutputHelper.php#L108-L118
train
sabre-io/dav
lib/DAVACL/Xml/Property/SupportedPrivilegeSet.php
SupportedPrivilegeSet.serializePriv
private function serializePriv(Writer $writer, $privName, $privilege) { $writer->startElement('{DAV:}supported-privilege'); $writer->startElement('{DAV:}privilege'); $writer->writeElement($privName); $writer->endElement(); // privilege if (!empty($privilege['abstract'])) { $writer->writeElement('{DAV:}abstract'); } if (!empty($privilege['description'])) { $writer->writeElement('{DAV:}description', $privilege['description']); } if (isset($privilege['aggregates'])) { foreach ($privilege['aggregates'] as $subPrivName => $subPrivilege) { $this->serializePriv($writer, $subPrivName, $subPrivilege); } } $writer->endElement(); // supported-privilege }
php
private function serializePriv(Writer $writer, $privName, $privilege) { $writer->startElement('{DAV:}supported-privilege'); $writer->startElement('{DAV:}privilege'); $writer->writeElement($privName); $writer->endElement(); // privilege if (!empty($privilege['abstract'])) { $writer->writeElement('{DAV:}abstract'); } if (!empty($privilege['description'])) { $writer->writeElement('{DAV:}description', $privilege['description']); } if (isset($privilege['aggregates'])) { foreach ($privilege['aggregates'] as $subPrivName => $subPrivilege) { $this->serializePriv($writer, $subPrivName, $subPrivilege); } } $writer->endElement(); // supported-privilege }
[ "private", "function", "serializePriv", "(", "Writer", "$", "writer", ",", "$", "privName", ",", "$", "privilege", ")", "{", "$", "writer", "->", "startElement", "(", "'{DAV:}supported-privilege'", ")", ";", "$", "writer", "->", "startElement", "(", "'{DAV:}pr...
Serializes a property. This is a recursive function. @param Writer $writer @param string $privName @param array $privilege
[ "Serializes", "a", "property", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Xml/Property/SupportedPrivilegeSet.php#L131-L152
train
sabre-io/dav
lib/CardDAV/Card.php
Card.get
public function get() { // Pre-populating 'carddata' is optional. If we don't yet have it // already, we fetch it from the backend. if (!isset($this->cardData['carddata'])) { $this->cardData = $this->carddavBackend->getCard($this->addressBookInfo['id'], $this->cardData['uri']); } return $this->cardData['carddata']; }
php
public function get() { // Pre-populating 'carddata' is optional. If we don't yet have it // already, we fetch it from the backend. if (!isset($this->cardData['carddata'])) { $this->cardData = $this->carddavBackend->getCard($this->addressBookInfo['id'], $this->cardData['uri']); } return $this->cardData['carddata']; }
[ "public", "function", "get", "(", ")", "{", "// Pre-populating 'carddata' is optional. If we don't yet have it", "// already, we fetch it from the backend.", "if", "(", "!", "isset", "(", "$", "this", "->", "cardData", "[", "'carddata'", "]", ")", ")", "{", "$", "this...
Returns the VCard-formatted object. @return string
[ "Returns", "the", "VCard", "-", "formatted", "object", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Card.php#L71-L80
train
sabre-io/dav
lib/CardDAV/Card.php
Card.put
public function put($cardData) { if (is_resource($cardData)) { $cardData = stream_get_contents($cardData); } // Converting to UTF-8, if needed $cardData = DAV\StringUtil::ensureUTF8($cardData); $etag = $this->carddavBackend->updateCard($this->addressBookInfo['id'], $this->cardData['uri'], $cardData); $this->cardData['carddata'] = $cardData; $this->cardData['etag'] = $etag; return $etag; }
php
public function put($cardData) { if (is_resource($cardData)) { $cardData = stream_get_contents($cardData); } // Converting to UTF-8, if needed $cardData = DAV\StringUtil::ensureUTF8($cardData); $etag = $this->carddavBackend->updateCard($this->addressBookInfo['id'], $this->cardData['uri'], $cardData); $this->cardData['carddata'] = $cardData; $this->cardData['etag'] = $etag; return $etag; }
[ "public", "function", "put", "(", "$", "cardData", ")", "{", "if", "(", "is_resource", "(", "$", "cardData", ")", ")", "{", "$", "cardData", "=", "stream_get_contents", "(", "$", "cardData", ")", ";", "}", "// Converting to UTF-8, if needed", "$", "cardData"...
Updates the VCard-formatted object. @param string $cardData @return string|null
[ "Updates", "the", "VCard", "-", "formatted", "object", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Card.php#L89-L103
train
sabre-io/dav
lib/CardDAV/Card.php
Card.getETag
public function getETag() { if (isset($this->cardData['etag'])) { return $this->cardData['etag']; } else { $data = $this->get(); if (is_string($data)) { return '"'.md5($data).'"'; } else { // We refuse to calculate the md5 if it's a stream. return null; } } }
php
public function getETag() { if (isset($this->cardData['etag'])) { return $this->cardData['etag']; } else { $data = $this->get(); if (is_string($data)) { return '"'.md5($data).'"'; } else { // We refuse to calculate the md5 if it's a stream. return null; } } }
[ "public", "function", "getETag", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "cardData", "[", "'etag'", "]", ")", ")", "{", "return", "$", "this", "->", "cardData", "[", "'etag'", "]", ";", "}", "else", "{", "$", "data", "=", "$", ...
Returns an ETag for this object. @return string
[ "Returns", "an", "ETag", "for", "this", "object", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Card.php#L128-L141
train
sabre-io/dav
lib/DAV/Auth/Plugin.php
Plugin.beforeMethod
public function beforeMethod(RequestInterface $request, ResponseInterface $response) { if ($this->currentPrincipal) { // We already have authentication information. This means that the // event has already fired earlier, and is now likely fired for a // sub-request. // // We don't want to authenticate users twice, so we simply don't do // anything here. See Issue #700 for additional reasoning. // // This is not a perfect solution, but will be fixed once the // "currently authenticated principal" is information that's not // not associated with the plugin, but rather per-request. // // See issue #580 for more information about that. return; } $authResult = $this->check($request, $response); if ($authResult[0]) { // Auth was successful $this->currentPrincipal = $authResult[1]; $this->loginFailedReasons = null; return; } // If we got here, it means that no authentication backend was // successful in authenticating the user. $this->currentPrincipal = null; $this->loginFailedReasons = $authResult[1]; if ($this->autoRequireLogin) { $this->challenge($request, $response); throw new NotAuthenticated(implode(', ', $authResult[1])); } }
php
public function beforeMethod(RequestInterface $request, ResponseInterface $response) { if ($this->currentPrincipal) { // We already have authentication information. This means that the // event has already fired earlier, and is now likely fired for a // sub-request. // // We don't want to authenticate users twice, so we simply don't do // anything here. See Issue #700 for additional reasoning. // // This is not a perfect solution, but will be fixed once the // "currently authenticated principal" is information that's not // not associated with the plugin, but rather per-request. // // See issue #580 for more information about that. return; } $authResult = $this->check($request, $response); if ($authResult[0]) { // Auth was successful $this->currentPrincipal = $authResult[1]; $this->loginFailedReasons = null; return; } // If we got here, it means that no authentication backend was // successful in authenticating the user. $this->currentPrincipal = null; $this->loginFailedReasons = $authResult[1]; if ($this->autoRequireLogin) { $this->challenge($request, $response); throw new NotAuthenticated(implode(', ', $authResult[1])); } }
[ "public", "function", "beforeMethod", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "if", "(", "$", "this", "->", "currentPrincipal", ")", "{", "// We already have authentication information. This means that the", "// event ...
This method is called before any HTTP method and forces users to be authenticated. @param RequestInterface $request @param ResponseInterface $response @return bool
[ "This", "method", "is", "called", "before", "any", "HTTP", "method", "and", "forces", "users", "to", "be", "authenticated", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Auth/Plugin.php#L126-L163
train
sabre-io/dav
lib/DAV/Auth/Plugin.php
Plugin.check
public function check(RequestInterface $request, ResponseInterface $response) { if (!$this->backends) { throw new \Sabre\DAV\Exception('No authentication backends were configured on this server.'); } $reasons = []; foreach ($this->backends as $backend) { $result = $backend->check( $request, $response ); if (!is_array($result) || 2 !== count($result) || !is_bool($result[0]) || !is_string($result[1])) { throw new \Sabre\DAV\Exception('The authentication backend did not return a correct value from the check() method.'); } if ($result[0]) { $this->currentPrincipal = $result[1]; // Exit early return [true, $result[1]]; } $reasons[] = $result[1]; } return [false, $reasons]; }
php
public function check(RequestInterface $request, ResponseInterface $response) { if (!$this->backends) { throw new \Sabre\DAV\Exception('No authentication backends were configured on this server.'); } $reasons = []; foreach ($this->backends as $backend) { $result = $backend->check( $request, $response ); if (!is_array($result) || 2 !== count($result) || !is_bool($result[0]) || !is_string($result[1])) { throw new \Sabre\DAV\Exception('The authentication backend did not return a correct value from the check() method.'); } if ($result[0]) { $this->currentPrincipal = $result[1]; // Exit early return [true, $result[1]]; } $reasons[] = $result[1]; } return [false, $reasons]; }
[ "public", "function", "check", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "if", "(", "!", "$", "this", "->", "backends", ")", "{", "throw", "new", "\\", "Sabre", "\\", "DAV", "\\", "Exception", "(", "'No...
Checks authentication credentials, and logs the user in if possible. This method returns an array. The first item in the array is a boolean indicating if login was successful. If login was successful, the second item in the array will contain the current principal url/path of the logged in user. If login was not successful, the second item in the array will contain a an array with strings. The strings are a list of reasons why login was unsuccessful. For every auth backend there will be one reason, so usually there's just one. @param RequestInterface $request @param ResponseInterface $response @return array
[ "Checks", "authentication", "credentials", "and", "logs", "the", "user", "in", "if", "possible", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Auth/Plugin.php#L184-L209
train
sabre-io/dav
lib/DAV/Auth/Plugin.php
Plugin.challenge
public function challenge(RequestInterface $request, ResponseInterface $response) { foreach ($this->backends as $backend) { $backend->challenge($request, $response); } }
php
public function challenge(RequestInterface $request, ResponseInterface $response) { foreach ($this->backends as $backend) { $backend->challenge($request, $response); } }
[ "public", "function", "challenge", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "foreach", "(", "$", "this", "->", "backends", "as", "$", "backend", ")", "{", "$", "backend", "->", "challenge", "(", "$", "re...
This method sends authentication challenges to the user. This method will for example cause a HTTP Basic backend to set a WWW-Authorization header, indicating to the client that it should authenticate. @param RequestInterface $request @param ResponseInterface $response @return array
[ "This", "method", "sends", "authentication", "challenges", "to", "the", "user", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Auth/Plugin.php#L223-L228
train
sabre-io/dav
lib/CardDAV/AddressBookHome.php
AddressBookHome.getChild
public function getChild($name) { foreach ($this->getChildren() as $child) { if ($name == $child->getName()) { return $child; } } throw new DAV\Exception\NotFound('Addressbook with name \''.$name.'\' could not be found'); }
php
public function getChild($name) { foreach ($this->getChildren() as $child) { if ($name == $child->getName()) { return $child; } } throw new DAV\Exception\NotFound('Addressbook with name \''.$name.'\' could not be found'); }
[ "public", "function", "getChild", "(", "$", "name", ")", "{", "foreach", "(", "$", "this", "->", "getChildren", "(", ")", "as", "$", "child", ")", "{", "if", "(", "$", "name", "==", "$", "child", "->", "getName", "(", ")", ")", "{", "return", "$"...
Returns a single addressbook, by name. @param string $name @todo needs optimizing @return AddressBook
[ "Returns", "a", "single", "addressbook", "by", "name", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/AddressBookHome.php#L125-L133
train
sabre-io/dav
lib/CardDAV/AddressBookHome.php
AddressBookHome.getChildren
public function getChildren() { $addressbooks = $this->carddavBackend->getAddressBooksForUser($this->principalUri); $objs = []; foreach ($addressbooks as $addressbook) { $objs[] = new AddressBook($this->carddavBackend, $addressbook); } return $objs; }
php
public function getChildren() { $addressbooks = $this->carddavBackend->getAddressBooksForUser($this->principalUri); $objs = []; foreach ($addressbooks as $addressbook) { $objs[] = new AddressBook($this->carddavBackend, $addressbook); } return $objs; }
[ "public", "function", "getChildren", "(", ")", "{", "$", "addressbooks", "=", "$", "this", "->", "carddavBackend", "->", "getAddressBooksForUser", "(", "$", "this", "->", "principalUri", ")", ";", "$", "objs", "=", "[", "]", ";", "foreach", "(", "$", "ad...
Returns a list of addressbooks. @return array
[ "Returns", "a", "list", "of", "addressbooks", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/AddressBookHome.php#L140-L149
train
sabre-io/dav
lib/CalDAV/Notifications/Plugin.php
Plugin.httpGet
public function httpGet(RequestInterface $request, ResponseInterface $response) { $path = $request->getPath(); try { $node = $this->server->tree->getNodeForPath($path); } catch (DAV\Exception\NotFound $e) { return; } if (!$node instanceof INode) { return; } $writer = $this->server->xml->getWriter(); $writer->contextUri = $this->server->getBaseUri(); $writer->openMemory(); $writer->startDocument('1.0', 'UTF-8'); $writer->startElement('{http://calendarserver.org/ns/}notification'); $node->getNotificationType()->xmlSerializeFull($writer); $writer->endElement(); $response->setHeader('Content-Type', 'application/xml'); $response->setHeader('ETag', $node->getETag()); $response->setStatus(200); $response->setBody($writer->outputMemory()); // Return false to break the event chain. return false; }
php
public function httpGet(RequestInterface $request, ResponseInterface $response) { $path = $request->getPath(); try { $node = $this->server->tree->getNodeForPath($path); } catch (DAV\Exception\NotFound $e) { return; } if (!$node instanceof INode) { return; } $writer = $this->server->xml->getWriter(); $writer->contextUri = $this->server->getBaseUri(); $writer->openMemory(); $writer->startDocument('1.0', 'UTF-8'); $writer->startElement('{http://calendarserver.org/ns/}notification'); $node->getNotificationType()->xmlSerializeFull($writer); $writer->endElement(); $response->setHeader('Content-Type', 'application/xml'); $response->setHeader('ETag', $node->getETag()); $response->setStatus(200); $response->setBody($writer->outputMemory()); // Return false to break the event chain. return false; }
[ "public", "function", "httpGet", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "path", "=", "$", "request", "->", "getPath", "(", ")", ";", "try", "{", "$", "node", "=", "$", "this", "->", "server", ...
This event is triggered before the usual GET request handler. We use this to intercept GET calls to notification nodes, and return the proper response. @param RequestInterface $request @param ResponseInterface $response
[ "This", "event", "is", "triggered", "before", "the", "usual", "GET", "request", "handler", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Notifications/Plugin.php#L119-L148
train
sabre-io/dav
lib/CardDAV/Plugin.php
Plugin.propFindEarly
public function propFindEarly(DAV\PropFind $propFind, DAV\INode $node) { $ns = '{'.self::NS_CARDDAV.'}'; if ($node instanceof IAddressBook) { $propFind->handle($ns.'max-resource-size', $this->maxResourceSize); $propFind->handle($ns.'supported-address-data', function () { return new Xml\Property\SupportedAddressData(); }); $propFind->handle($ns.'supported-collation-set', function () { return new Xml\Property\SupportedCollationSet(); }); } if ($node instanceof DAVACL\IPrincipal) { $path = $propFind->getPath(); $propFind->handle('{'.self::NS_CARDDAV.'}addressbook-home-set', function () use ($path) { return new LocalHref($this->getAddressBookHomeForPrincipal($path).'/'); }); if ($this->directories) { $propFind->handle('{'.self::NS_CARDDAV.'}directory-gateway', function () { return new LocalHref($this->directories); }); } } if ($node instanceof ICard) { // The address-data property is not supposed to be a 'real' // property, but in large chunks of the spec it does act as such. // Therefore we simply expose it as a property. $propFind->handle('{'.self::NS_CARDDAV.'}address-data', function () use ($node) { $val = $node->get(); if (is_resource($val)) { $val = stream_get_contents($val); } return $val; }); } }
php
public function propFindEarly(DAV\PropFind $propFind, DAV\INode $node) { $ns = '{'.self::NS_CARDDAV.'}'; if ($node instanceof IAddressBook) { $propFind->handle($ns.'max-resource-size', $this->maxResourceSize); $propFind->handle($ns.'supported-address-data', function () { return new Xml\Property\SupportedAddressData(); }); $propFind->handle($ns.'supported-collation-set', function () { return new Xml\Property\SupportedCollationSet(); }); } if ($node instanceof DAVACL\IPrincipal) { $path = $propFind->getPath(); $propFind->handle('{'.self::NS_CARDDAV.'}addressbook-home-set', function () use ($path) { return new LocalHref($this->getAddressBookHomeForPrincipal($path).'/'); }); if ($this->directories) { $propFind->handle('{'.self::NS_CARDDAV.'}directory-gateway', function () { return new LocalHref($this->directories); }); } } if ($node instanceof ICard) { // The address-data property is not supposed to be a 'real' // property, but in large chunks of the spec it does act as such. // Therefore we simply expose it as a property. $propFind->handle('{'.self::NS_CARDDAV.'}address-data', function () use ($node) { $val = $node->get(); if (is_resource($val)) { $val = stream_get_contents($val); } return $val; }); } }
[ "public", "function", "propFindEarly", "(", "DAV", "\\", "PropFind", "$", "propFind", ",", "DAV", "\\", "INode", "$", "node", ")", "{", "$", "ns", "=", "'{'", ".", "self", "::", "NS_CARDDAV", ".", "'}'", ";", "if", "(", "$", "node", "instanceof", "IA...
Adds all CardDAV-specific properties. @param DAV\PropFind $propFind @param DAV\INode $node
[ "Adds", "all", "CardDAV", "-", "specific", "properties", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Plugin.php#L138-L178
train
sabre-io/dav
lib/CardDAV/Plugin.php
Plugin.report
public function report($reportName, $dom, $path) { switch ($reportName) { case '{'.self::NS_CARDDAV.'}addressbook-multiget': $this->server->transactionType = 'report-addressbook-multiget'; $this->addressbookMultiGetReport($dom); return false; case '{'.self::NS_CARDDAV.'}addressbook-query': $this->server->transactionType = 'report-addressbook-query'; $this->addressBookQueryReport($dom); return false; default: return; } }
php
public function report($reportName, $dom, $path) { switch ($reportName) { case '{'.self::NS_CARDDAV.'}addressbook-multiget': $this->server->transactionType = 'report-addressbook-multiget'; $this->addressbookMultiGetReport($dom); return false; case '{'.self::NS_CARDDAV.'}addressbook-query': $this->server->transactionType = 'report-addressbook-query'; $this->addressBookQueryReport($dom); return false; default: return; } }
[ "public", "function", "report", "(", "$", "reportName", ",", "$", "dom", ",", "$", "path", ")", "{", "switch", "(", "$", "reportName", ")", "{", "case", "'{'", ".", "self", "::", "NS_CARDDAV", ".", "'}addressbook-multiget'", ":", "$", "this", "->", "se...
This functions handles REPORT requests specific to CardDAV. @param string $reportName @param \DOMNode $dom @param mixed $path @return bool
[ "This", "functions", "handles", "REPORT", "requests", "specific", "to", "CardDAV", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Plugin.php#L189-L205
train
sabre-io/dav
lib/CardDAV/Plugin.php
Plugin.getAddressbookHomeForPrincipal
protected function getAddressbookHomeForPrincipal($principal) { list(, $principalId) = Uri\split($principal); return self::ADDRESSBOOK_ROOT.'/'.$principalId; }
php
protected function getAddressbookHomeForPrincipal($principal) { list(, $principalId) = Uri\split($principal); return self::ADDRESSBOOK_ROOT.'/'.$principalId; }
[ "protected", "function", "getAddressbookHomeForPrincipal", "(", "$", "principal", ")", "{", "list", "(", ",", "$", "principalId", ")", "=", "Uri", "\\", "split", "(", "$", "principal", ")", ";", "return", "self", "::", "ADDRESSBOOK_ROOT", ".", "'/'", ".", ...
Returns the addressbook home for a given principal. @param string $principal @return string
[ "Returns", "the", "addressbook", "home", "for", "a", "given", "principal", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Plugin.php#L214-L219
train
sabre-io/dav
lib/CardDAV/Plugin.php
Plugin.addressbookMultiGetReport
public function addressbookMultiGetReport($report) { $contentType = $report->contentType; $version = $report->version; if ($version) { $contentType .= '; version='.$version; } $vcardType = $this->negotiateVCard( $contentType ); $propertyList = []; $paths = array_map( [$this->server, 'calculateUri'], $report->hrefs ); foreach ($this->server->getPropertiesForMultiplePaths($paths, $report->properties) as $props) { if (isset($props['200']['{'.self::NS_CARDDAV.'}address-data'])) { $props['200']['{'.self::NS_CARDDAV.'}address-data'] = $this->convertVCard( $props[200]['{'.self::NS_CARDDAV.'}address-data'], $vcardType ); } $propertyList[] = $props; } $prefer = $this->server->getHTTPPrefer(); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setHeader('Vary', 'Brief,Prefer'); $this->server->httpResponse->setBody($this->server->generateMultiStatus($propertyList, 'minimal' === $prefer['return'])); }
php
public function addressbookMultiGetReport($report) { $contentType = $report->contentType; $version = $report->version; if ($version) { $contentType .= '; version='.$version; } $vcardType = $this->negotiateVCard( $contentType ); $propertyList = []; $paths = array_map( [$this->server, 'calculateUri'], $report->hrefs ); foreach ($this->server->getPropertiesForMultiplePaths($paths, $report->properties) as $props) { if (isset($props['200']['{'.self::NS_CARDDAV.'}address-data'])) { $props['200']['{'.self::NS_CARDDAV.'}address-data'] = $this->convertVCard( $props[200]['{'.self::NS_CARDDAV.'}address-data'], $vcardType ); } $propertyList[] = $props; } $prefer = $this->server->getHTTPPrefer(); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setHeader('Vary', 'Brief,Prefer'); $this->server->httpResponse->setBody($this->server->generateMultiStatus($propertyList, 'minimal' === $prefer['return'])); }
[ "public", "function", "addressbookMultiGetReport", "(", "$", "report", ")", "{", "$", "contentType", "=", "$", "report", "->", "contentType", ";", "$", "version", "=", "$", "report", "->", "version", ";", "if", "(", "$", "version", ")", "{", "$", "conten...
This function handles the addressbook-multiget REPORT. This report is used by the client to fetch the content of a series of urls. Effectively avoiding a lot of redundant requests. @param Xml\Request\AddressBookMultiGetReport $report
[ "This", "function", "handles", "the", "addressbook", "-", "multiget", "REPORT", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Plugin.php#L229-L262
train
sabre-io/dav
lib/CardDAV/Plugin.php
Plugin.addressbookQueryReport
protected function addressbookQueryReport($report) { $depth = $this->server->getHTTPDepth(0); if (0 == $depth) { $candidateNodes = [ $this->server->tree->getNodeForPath($this->server->getRequestUri()), ]; if (!$candidateNodes[0] instanceof ICard) { throw new ReportNotSupported('The addressbook-query report is not supported on this url with Depth: 0'); } } else { $candidateNodes = $this->server->tree->getChildren($this->server->getRequestUri()); } $contentType = $report->contentType; if ($report->version) { $contentType .= '; version='.$report->version; } $vcardType = $this->negotiateVCard( $contentType ); $validNodes = []; foreach ($candidateNodes as $node) { if (!$node instanceof ICard) { continue; } $blob = $node->get(); if (is_resource($blob)) { $blob = stream_get_contents($blob); } if (!$this->validateFilters($blob, $report->filters, $report->test)) { continue; } $validNodes[] = $node; if ($report->limit && $report->limit <= count($validNodes)) { // We hit the maximum number of items, we can stop now. break; } } $result = []; foreach ($validNodes as $validNode) { if (0 == $depth) { $href = $this->server->getRequestUri(); } else { $href = $this->server->getRequestUri().'/'.$validNode->getName(); } list($props) = $this->server->getPropertiesForPath($href, $report->properties, 0); if (isset($props[200]['{'.self::NS_CARDDAV.'}address-data'])) { $props[200]['{'.self::NS_CARDDAV.'}address-data'] = $this->convertVCard( $props[200]['{'.self::NS_CARDDAV.'}address-data'], $vcardType, $report->addressDataProperties ); } $result[] = $props; } $prefer = $this->server->getHTTPPrefer(); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setHeader('Vary', 'Brief,Prefer'); $this->server->httpResponse->setBody($this->server->generateMultiStatus($result, 'minimal' === $prefer['return'])); }
php
protected function addressbookQueryReport($report) { $depth = $this->server->getHTTPDepth(0); if (0 == $depth) { $candidateNodes = [ $this->server->tree->getNodeForPath($this->server->getRequestUri()), ]; if (!$candidateNodes[0] instanceof ICard) { throw new ReportNotSupported('The addressbook-query report is not supported on this url with Depth: 0'); } } else { $candidateNodes = $this->server->tree->getChildren($this->server->getRequestUri()); } $contentType = $report->contentType; if ($report->version) { $contentType .= '; version='.$report->version; } $vcardType = $this->negotiateVCard( $contentType ); $validNodes = []; foreach ($candidateNodes as $node) { if (!$node instanceof ICard) { continue; } $blob = $node->get(); if (is_resource($blob)) { $blob = stream_get_contents($blob); } if (!$this->validateFilters($blob, $report->filters, $report->test)) { continue; } $validNodes[] = $node; if ($report->limit && $report->limit <= count($validNodes)) { // We hit the maximum number of items, we can stop now. break; } } $result = []; foreach ($validNodes as $validNode) { if (0 == $depth) { $href = $this->server->getRequestUri(); } else { $href = $this->server->getRequestUri().'/'.$validNode->getName(); } list($props) = $this->server->getPropertiesForPath($href, $report->properties, 0); if (isset($props[200]['{'.self::NS_CARDDAV.'}address-data'])) { $props[200]['{'.self::NS_CARDDAV.'}address-data'] = $this->convertVCard( $props[200]['{'.self::NS_CARDDAV.'}address-data'], $vcardType, $report->addressDataProperties ); } $result[] = $props; } $prefer = $this->server->getHTTPPrefer(); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setHeader('Vary', 'Brief,Prefer'); $this->server->httpResponse->setBody($this->server->generateMultiStatus($result, 'minimal' === $prefer['return'])); }
[ "protected", "function", "addressbookQueryReport", "(", "$", "report", ")", "{", "$", "depth", "=", "$", "this", "->", "server", "->", "getHTTPDepth", "(", "0", ")", ";", "if", "(", "0", "==", "$", "depth", ")", "{", "$", "candidateNodes", "=", "[", ...
This function handles the addressbook-query REPORT. This report is used by the client to filter an addressbook based on a complex query. @param Xml\Request\AddressBookQueryReport $report
[ "This", "function", "handles", "the", "addressbook", "-", "query", "REPORT", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Plugin.php#L405-L478
train
sabre-io/dav
lib/CardDAV/Plugin.php
Plugin.validateFilters
public function validateFilters($vcardData, array $filters, $test) { if (!$filters) { return true; } $vcard = VObject\Reader::read($vcardData); foreach ($filters as $filter) { $isDefined = isset($vcard->{$filter['name']}); if ($filter['is-not-defined']) { if ($isDefined) { $success = false; } else { $success = true; } } elseif ((!$filter['param-filters'] && !$filter['text-matches']) || !$isDefined) { // We only need to check for existence $success = $isDefined; } else { $vProperties = $vcard->select($filter['name']); $results = []; if ($filter['param-filters']) { $results[] = $this->validateParamFilters($vProperties, $filter['param-filters'], $filter['test']); } if ($filter['text-matches']) { $texts = []; foreach ($vProperties as $vProperty) { $texts[] = $vProperty->getValue(); } $results[] = $this->validateTextMatches($texts, $filter['text-matches'], $filter['test']); } if (1 === count($results)) { $success = $results[0]; } else { if ('anyof' === $filter['test']) { $success = $results[0] || $results[1]; } else { $success = $results[0] && $results[1]; } } } // else // There are two conditions where we can already determine whether // or not this filter succeeds. if ('anyof' === $test && $success) { // Destroy circular references to PHP will GC the object. $vcard->destroy(); return true; } if ('allof' === $test && !$success) { // Destroy circular references to PHP will GC the object. $vcard->destroy(); return false; } } // foreach // Destroy circular references to PHP will GC the object. $vcard->destroy(); // If we got all the way here, it means we haven't been able to // determine early if the test failed or not. // // This implies for 'anyof' that the test failed, and for 'allof' that // we succeeded. Sounds weird, but makes sense. return 'allof' === $test; }
php
public function validateFilters($vcardData, array $filters, $test) { if (!$filters) { return true; } $vcard = VObject\Reader::read($vcardData); foreach ($filters as $filter) { $isDefined = isset($vcard->{$filter['name']}); if ($filter['is-not-defined']) { if ($isDefined) { $success = false; } else { $success = true; } } elseif ((!$filter['param-filters'] && !$filter['text-matches']) || !$isDefined) { // We only need to check for existence $success = $isDefined; } else { $vProperties = $vcard->select($filter['name']); $results = []; if ($filter['param-filters']) { $results[] = $this->validateParamFilters($vProperties, $filter['param-filters'], $filter['test']); } if ($filter['text-matches']) { $texts = []; foreach ($vProperties as $vProperty) { $texts[] = $vProperty->getValue(); } $results[] = $this->validateTextMatches($texts, $filter['text-matches'], $filter['test']); } if (1 === count($results)) { $success = $results[0]; } else { if ('anyof' === $filter['test']) { $success = $results[0] || $results[1]; } else { $success = $results[0] && $results[1]; } } } // else // There are two conditions where we can already determine whether // or not this filter succeeds. if ('anyof' === $test && $success) { // Destroy circular references to PHP will GC the object. $vcard->destroy(); return true; } if ('allof' === $test && !$success) { // Destroy circular references to PHP will GC the object. $vcard->destroy(); return false; } } // foreach // Destroy circular references to PHP will GC the object. $vcard->destroy(); // If we got all the way here, it means we haven't been able to // determine early if the test failed or not. // // This implies for 'anyof' that the test failed, and for 'allof' that // we succeeded. Sounds weird, but makes sense. return 'allof' === $test; }
[ "public", "function", "validateFilters", "(", "$", "vcardData", ",", "array", "$", "filters", ",", "$", "test", ")", "{", "if", "(", "!", "$", "filters", ")", "{", "return", "true", ";", "}", "$", "vcard", "=", "VObject", "\\", "Reader", "::", "read"...
Validates if a vcard makes it throught a list of filters. @param string $vcardData @param array $filters @param string $test anyof or allof (which means OR or AND) @return bool
[ "Validates", "if", "a", "vcard", "makes", "it", "throught", "a", "list", "of", "filters", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Plugin.php#L489-L559
train
sabre-io/dav
lib/CardDAV/Plugin.php
Plugin.validateParamFilters
protected function validateParamFilters(array $vProperties, array $filters, $test) { foreach ($filters as $filter) { $isDefined = false; foreach ($vProperties as $vProperty) { $isDefined = isset($vProperty[$filter['name']]); if ($isDefined) { break; } } if ($filter['is-not-defined']) { if ($isDefined) { $success = false; } else { $success = true; } // If there's no text-match, we can just check for existence } elseif (!$filter['text-match'] || !$isDefined) { $success = $isDefined; } else { $success = false; foreach ($vProperties as $vProperty) { // If we got all the way here, we'll need to validate the // text-match filter. $success = DAV\StringUtil::textMatch($vProperty[$filter['name']]->getValue(), $filter['text-match']['value'], $filter['text-match']['collation'], $filter['text-match']['match-type']); if ($success) { break; } } if ($filter['text-match']['negate-condition']) { $success = !$success; } } // else // There are two conditions where we can already determine whether // or not this filter succeeds. if ('anyof' === $test && $success) { return true; } if ('allof' === $test && !$success) { return false; } } // If we got all the way here, it means we haven't been able to // determine early if the test failed or not. // // This implies for 'anyof' that the test failed, and for 'allof' that // we succeeded. Sounds weird, but makes sense. return 'allof' === $test; }
php
protected function validateParamFilters(array $vProperties, array $filters, $test) { foreach ($filters as $filter) { $isDefined = false; foreach ($vProperties as $vProperty) { $isDefined = isset($vProperty[$filter['name']]); if ($isDefined) { break; } } if ($filter['is-not-defined']) { if ($isDefined) { $success = false; } else { $success = true; } // If there's no text-match, we can just check for existence } elseif (!$filter['text-match'] || !$isDefined) { $success = $isDefined; } else { $success = false; foreach ($vProperties as $vProperty) { // If we got all the way here, we'll need to validate the // text-match filter. $success = DAV\StringUtil::textMatch($vProperty[$filter['name']]->getValue(), $filter['text-match']['value'], $filter['text-match']['collation'], $filter['text-match']['match-type']); if ($success) { break; } } if ($filter['text-match']['negate-condition']) { $success = !$success; } } // else // There are two conditions where we can already determine whether // or not this filter succeeds. if ('anyof' === $test && $success) { return true; } if ('allof' === $test && !$success) { return false; } } // If we got all the way here, it means we haven't been able to // determine early if the test failed or not. // // This implies for 'anyof' that the test failed, and for 'allof' that // we succeeded. Sounds weird, but makes sense. return 'allof' === $test; }
[ "protected", "function", "validateParamFilters", "(", "array", "$", "vProperties", ",", "array", "$", "filters", ",", "$", "test", ")", "{", "foreach", "(", "$", "filters", "as", "$", "filter", ")", "{", "$", "isDefined", "=", "false", ";", "foreach", "(...
Validates if a param-filter can be applied to a specific property. @todo currently we're only validating the first parameter of the passed property. Any subsequence parameters with the same name are ignored. @param array $vProperties @param array $filters @param string $test @return bool
[ "Validates", "if", "a", "param", "-", "filter", "can", "be", "applied", "to", "a", "specific", "property", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Plugin.php#L574-L626
train
sabre-io/dav
lib/CardDAV/Plugin.php
Plugin.validateTextMatches
protected function validateTextMatches(array $texts, array $filters, $test) { foreach ($filters as $filter) { $success = false; foreach ($texts as $haystack) { $success = DAV\StringUtil::textMatch($haystack, $filter['value'], $filter['collation'], $filter['match-type']); // Breaking on the first match if ($success) { break; } } if ($filter['negate-condition']) { $success = !$success; } if ($success && 'anyof' === $test) { return true; } if (!$success && 'allof' == $test) { return false; } } // If we got all the way here, it means we haven't been able to // determine early if the test failed or not. // // This implies for 'anyof' that the test failed, and for 'allof' that // we succeeded. Sounds weird, but makes sense. return 'allof' === $test; }
php
protected function validateTextMatches(array $texts, array $filters, $test) { foreach ($filters as $filter) { $success = false; foreach ($texts as $haystack) { $success = DAV\StringUtil::textMatch($haystack, $filter['value'], $filter['collation'], $filter['match-type']); // Breaking on the first match if ($success) { break; } } if ($filter['negate-condition']) { $success = !$success; } if ($success && 'anyof' === $test) { return true; } if (!$success && 'allof' == $test) { return false; } } // If we got all the way here, it means we haven't been able to // determine early if the test failed or not. // // This implies for 'anyof' that the test failed, and for 'allof' that // we succeeded. Sounds weird, but makes sense. return 'allof' === $test; }
[ "protected", "function", "validateTextMatches", "(", "array", "$", "texts", ",", "array", "$", "filters", ",", "$", "test", ")", "{", "foreach", "(", "$", "filters", "as", "$", "filter", ")", "{", "$", "success", "=", "false", ";", "foreach", "(", "$",...
Validates if a text-filter can be applied to a specific property. @param array $texts @param array $filters @param string $test @return bool
[ "Validates", "if", "a", "text", "-", "filter", "can", "be", "applied", "to", "a", "specific", "property", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Plugin.php#L637-L668
train
sabre-io/dav
lib/CardDAV/Plugin.php
Plugin.propFindLate
public function propFindLate(DAV\PropFind $propFind, DAV\INode $node) { // If the request was made using the SOGO connector, we must rewrite // the content-type property. By default SabreDAV will send back // text/x-vcard; charset=utf-8, but for SOGO we must strip that last // part. if (false === strpos((string) $this->server->httpRequest->getHeader('User-Agent'), 'Thunderbird')) { return; } $contentType = $propFind->get('{DAV:}getcontenttype'); list($part) = explode(';', $contentType); if ('text/x-vcard' === $part || 'text/vcard' === $part) { $propFind->set('{DAV:}getcontenttype', 'text/x-vcard'); } }
php
public function propFindLate(DAV\PropFind $propFind, DAV\INode $node) { // If the request was made using the SOGO connector, we must rewrite // the content-type property. By default SabreDAV will send back // text/x-vcard; charset=utf-8, but for SOGO we must strip that last // part. if (false === strpos((string) $this->server->httpRequest->getHeader('User-Agent'), 'Thunderbird')) { return; } $contentType = $propFind->get('{DAV:}getcontenttype'); list($part) = explode(';', $contentType); if ('text/x-vcard' === $part || 'text/vcard' === $part) { $propFind->set('{DAV:}getcontenttype', 'text/x-vcard'); } }
[ "public", "function", "propFindLate", "(", "DAV", "\\", "PropFind", "$", "propFind", ",", "DAV", "\\", "INode", "$", "node", ")", "{", "// If the request was made using the SOGO connector, we must rewrite", "// the content-type property. By default SabreDAV will send back", "//...
This event is triggered when fetching properties. This event is scheduled late in the process, after most work for propfind has been done. @param DAV\PropFind $propFind @param DAV\INode $node
[ "This", "event", "is", "triggered", "when", "fetching", "properties", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Plugin.php#L679-L693
train
sabre-io/dav
lib/CardDAV/Plugin.php
Plugin.htmlActionsPanel
public function htmlActionsPanel(DAV\INode $node, &$output) { if (!$node instanceof AddressBookHome) { return; } $output .= '<tr><td colspan="2"><form method="post" action=""> <h3>Create new address book</h3> <input type="hidden" name="sabreAction" value="mkcol" /> <input type="hidden" name="resourceType" value="{DAV:}collection,{'.self::NS_CARDDAV.'}addressbook" /> <label>Name (uri):</label> <input type="text" name="name" /><br /> <label>Display name:</label> <input type="text" name="{DAV:}displayname" /><br /> <input type="submit" value="create" /> </form> </td></tr>'; return false; }
php
public function htmlActionsPanel(DAV\INode $node, &$output) { if (!$node instanceof AddressBookHome) { return; } $output .= '<tr><td colspan="2"><form method="post" action=""> <h3>Create new address book</h3> <input type="hidden" name="sabreAction" value="mkcol" /> <input type="hidden" name="resourceType" value="{DAV:}collection,{'.self::NS_CARDDAV.'}addressbook" /> <label>Name (uri):</label> <input type="text" name="name" /><br /> <label>Display name:</label> <input type="text" name="{DAV:}displayname" /><br /> <input type="submit" value="create" /> </form> </td></tr>'; return false; }
[ "public", "function", "htmlActionsPanel", "(", "DAV", "\\", "INode", "$", "node", ",", "&", "$", "output", ")", "{", "if", "(", "!", "$", "node", "instanceof", "AddressBookHome", ")", "{", "return", ";", "}", "$", "output", ".=", "'<tr><td colspan=\"2\"><f...
This method is used to generate HTML output for the Sabre\DAV\Browser\Plugin. This allows us to generate an interface users can use to create new addressbooks. @param DAV\INode $node @param string $output @return bool
[ "This", "method", "is", "used", "to", "generate", "HTML", "output", "for", "the", "Sabre", "\\", "DAV", "\\", "Browser", "\\", "Plugin", ".", "This", "allows", "us", "to", "generate", "an", "interface", "users", "can", "use", "to", "create", "new", "addr...
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Plugin.php#L705-L722
train
sabre-io/dav
lib/CardDAV/Plugin.php
Plugin.negotiateVCard
protected function negotiateVCard($input, &$mimeType = null) { $result = HTTP\negotiateContentType( $input, [ // Most often used mime-type. Version 3 'text/x-vcard', // The correct standard mime-type. Defaults to version 3 as // well. 'text/vcard', // vCard 4 'text/vcard; version=4.0', // vCard 3 'text/vcard; version=3.0', // jCard 'application/vcard+json', ] ); $mimeType = $result; switch ($result) { default: case 'text/x-vcard': case 'text/vcard': case 'text/vcard; version=3.0': $mimeType = 'text/vcard'; return 'vcard3'; case 'text/vcard; version=4.0': return 'vcard4'; case 'application/vcard+json': return 'jcard'; // @codeCoverageIgnoreStart } // @codeCoverageIgnoreEnd }
php
protected function negotiateVCard($input, &$mimeType = null) { $result = HTTP\negotiateContentType( $input, [ // Most often used mime-type. Version 3 'text/x-vcard', // The correct standard mime-type. Defaults to version 3 as // well. 'text/vcard', // vCard 4 'text/vcard; version=4.0', // vCard 3 'text/vcard; version=3.0', // jCard 'application/vcard+json', ] ); $mimeType = $result; switch ($result) { default: case 'text/x-vcard': case 'text/vcard': case 'text/vcard; version=3.0': $mimeType = 'text/vcard'; return 'vcard3'; case 'text/vcard; version=4.0': return 'vcard4'; case 'application/vcard+json': return 'jcard'; // @codeCoverageIgnoreStart } // @codeCoverageIgnoreEnd }
[ "protected", "function", "negotiateVCard", "(", "$", "input", ",", "&", "$", "mimeType", "=", "null", ")", "{", "$", "result", "=", "HTTP", "\\", "negotiateContentType", "(", "$", "input", ",", "[", "// Most often used mime-type. Version 3", "'text/x-vcard'", ",...
This helper function performs the content-type negotiation for vcards. It will return one of the following strings: 1. vcard3 2. vcard4 3. jcard It defaults to vcard3. @param string $input @param string $mimeType @return string
[ "This", "helper", "function", "performs", "the", "content", "-", "type", "negotiation", "for", "vcards", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Plugin.php#L766-L802
train
sabre-io/dav
lib/CardDAV/Plugin.php
Plugin.convertVCard
protected function convertVCard($data, $target, array $propertiesFilter = null) { if (is_resource($data)) { $data = stream_get_contents($data); } $input = VObject\Reader::read($data); if (!empty($propertiesFilter)) { $propertiesFilter = array_merge(['UID', 'VERSION', 'FN'], $propertiesFilter); $keys = array_unique(array_map(function ($child) { return $child->name; }, $input->children())); $keys = array_diff($keys, $propertiesFilter); foreach ($keys as $key) { unset($input->$key); } $data = $input->serialize(); } $output = null; try { switch ($target) { default: case 'vcard3': if (VObject\Document::VCARD30 === $input->getDocumentType()) { // Do nothing return $data; } $output = $input->convert(VObject\Document::VCARD30); return $output->serialize(); case 'vcard4': if (VObject\Document::VCARD40 === $input->getDocumentType()) { // Do nothing return $data; } $output = $input->convert(VObject\Document::VCARD40); return $output->serialize(); case 'jcard': $output = $input->convert(VObject\Document::VCARD40); return json_encode($output); } } finally { // Destroy circular references to PHP will GC the object. $input->destroy(); if (!is_null($output)) { $output->destroy(); } } }
php
protected function convertVCard($data, $target, array $propertiesFilter = null) { if (is_resource($data)) { $data = stream_get_contents($data); } $input = VObject\Reader::read($data); if (!empty($propertiesFilter)) { $propertiesFilter = array_merge(['UID', 'VERSION', 'FN'], $propertiesFilter); $keys = array_unique(array_map(function ($child) { return $child->name; }, $input->children())); $keys = array_diff($keys, $propertiesFilter); foreach ($keys as $key) { unset($input->$key); } $data = $input->serialize(); } $output = null; try { switch ($target) { default: case 'vcard3': if (VObject\Document::VCARD30 === $input->getDocumentType()) { // Do nothing return $data; } $output = $input->convert(VObject\Document::VCARD30); return $output->serialize(); case 'vcard4': if (VObject\Document::VCARD40 === $input->getDocumentType()) { // Do nothing return $data; } $output = $input->convert(VObject\Document::VCARD40); return $output->serialize(); case 'jcard': $output = $input->convert(VObject\Document::VCARD40); return json_encode($output); } } finally { // Destroy circular references to PHP will GC the object. $input->destroy(); if (!is_null($output)) { $output->destroy(); } } }
[ "protected", "function", "convertVCard", "(", "$", "data", ",", "$", "target", ",", "array", "$", "propertiesFilter", "=", "null", ")", "{", "if", "(", "is_resource", "(", "$", "data", ")", ")", "{", "$", "data", "=", "stream_get_contents", "(", "$", "...
Converts a vcard blob to a different version, or jcard. @param string|resource $data @param string $target @param array $propertiesFilter @return string
[ "Converts", "a", "vcard", "blob", "to", "a", "different", "version", "or", "jcard", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/Plugin.php#L813-L862
train