Merge remote branch 'friendica/master'

This commit is contained in:
fabrixxm 2012-12-28 10:25:57 -05:00
commit 6728d714cb
235 changed files with 7821 additions and 2106 deletions

18
INSTALL.txt Normal file
View file

@ -0,0 +1,18 @@
*********************
* Install Using Git *
*********************
To install all addons using git, cd into your top level Friendica directory and
git clone https://github.com/friendica/friendica-addons.git addon
This will clone the entire repository in a directory called addon. They can now be activated in the plugins section of your admin panel.
********************
* Install Manually *
********************
1. Download the archive (AddonName.tgz) containing the addon you want to install.
2. Unzip the contents of the archive to your harddrive.
3. Upload the extracted directory and all it's contents to /path/to/friendica/addon. You will need to create the addon directory if this is the first addon you have installed.
4. Activate the addon in the plugins section of your admin panel.

BIN
altpager.tgz Normal file

Binary file not shown.

View file

@ -61,6 +61,10 @@ function altpager_settings(&$a,&$s) {
if(! local_user())
return;
$global = get_config("alt_pager", "global");
if($global == 1)
return;
/* Add our stylesheet to the page so we can make our settings look nice */
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/altpager/altpager.css' . '" media="all" />' . "\r\n";
@ -87,3 +91,19 @@ function altpager_settings(&$a,&$s) {
$s .= '<div class="settings-submit-wrapper" ><input type="submit" name="altpager-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
}
function altpager_plugin_admin(&$a, &$o){
$t = get_markup_template( "admin.tpl", "addon/altpager/" );
$o = replace_macros($t, array(
'$submit' => t('Submit'),
'$global' => array('altpagerchoice', t('Global'), 1, t('Force global use of the alternate pager'), get_config('alt_pager', 'global') == 1),
'$individual' => array('altpagerchoice', t('Individual'), 2, t('Each user chooses whether to use the alternate pager'), get_config('alt_pager', 'global') == 0)
));
}
function altpager_plugin_admin_post(&$a){
$choice = ((x($_POST,'altpagerchoice')) ? notags(trim($_POST['altpagerchoice'])) : '');
set_config('alt_pager','global',($choice == 1 ? 1 : 0));
info( t('Settings updated.'). EOL );
}

3
altpager/view/admin.tpl Normal file
View file

@ -0,0 +1,3 @@
{{ inc field_radio.tpl with $field=$global }}{{ endinc }}
{{ inc field_radio.tpl with $field=$individual }}{{ endinc }}
<div class="submit"><input type="submit" name="page_site" value="$submit" /></div>

3
altpager/view/admin.tpl.old Executable file
View file

@ -0,0 +1,3 @@
{{ inc field_radio.tpl with $field=$global }}{{ endinc }}
{{ inc field_radio.tpl with $field=$individual }}{{ endinc }}
<div class="submit"><input type="submit" name="page_site" value="$submit" /></div>

View file

@ -0,0 +1,3 @@
{{include file="field_radio.tpl" field=$global}}
{{include file="field_radio.tpl" field=$individual}}
<div class="submit"><input type="submit" name="page_site" value="{{$submit}}" /></div>

Binary file not shown.

View file

@ -93,8 +93,9 @@ function blackout_plugin_admin(&$a, &$o) {
if (! is_string($myend)) { $myend = "YYYY-MM-DD:hhmm"; }
$myurl = get_config('blackout','url');
if (! is_string($myurl)) { $myurl = "http://www.example.com"; }
$t = file_get_contents( dirname(__file__)."/admin.tpl" );
$o = replace_macros($t, array(
$t = get_markup_template( "admin.tpl", "addon/blackout/" );
$o = replace_macros($t, array(
'$submit' => t('Submit'),
'$rurl' => array("rurl", "Redirect URL", $myurl, "all your visitors from the web will be redirected to this URL"),
'$startdate' => array("startdate", "Begin of the Blackout<br />(YYYY-MM-DD hh:mm)", $mystart, "format is <em>YYYY</em> year, <em>MM</em> month, <em>DD</em> day, <em>hh</em> hour and <em>mm</em> minute"),

View file

@ -0,0 +1,11 @@
{{include file="field_input.tpl" field=$startdate}}
{{include file="field_input.tpl" field=$enddate}}
{{include file="field_input.tpl" field=$rurl}}
<div style="border: 2px solid #f00; padding: 10px; margin:
10px;font-size: 1.2em;"><strong>Note</strong>: The redirect will be active from the moment you
press the submit button. Users currently logged in will <strong>not</strong> be
thrown out but can't login again after logging out should the blackout is
still in place.</div>
<div class="submit"><input type="submit" name="page_site" value="{{$submit}}" /></div>

Binary file not shown.

View file

@ -157,9 +157,9 @@ function blockem_item_photo_menu(&$a,&$b) {
}
}
if($blocked)
$b['menu'][ t('Unblock Author')] = 'javascript:blockemUnblock("' . $author . '");';
$b['menu'][ t('Unblock Author')] = 'javascript:blockemUnblock(\'' . $author . '\');';
else
$b['menu'][ t('Block Author')] = 'javascript:blockemBlock("' . $author . '");';
$b['menu'][ t('Block Author')] = 'javascript:blockemBlock(\'' . $author . '\');';
}
function blockem_module() {}

Binary file not shown.

View file

@ -12,4 +12,4 @@ function buglink_install() { register_hook('page_end', 'addon/buglink/buglink.ph
function buglink_uninstall() { unregister_hook('page_end', 'addon/buglink/buglink.php', 'buglink_active'); }
function buglink_active(&$a,&$b) { $b .= '<div style="position: fixed; bottom: 5px; left: 5px;"><a href="http://bugs.friendica.com" title="' . t('Report Bug') . '"><img src="addon/buglink/bug-x.gif" alt="' . t('Report Bug') . '" /></a></div>'; }
function buglink_active(&$a,&$b) { $b .= '<div style="position: fixed; bottom: 5px; left: 5px;"><a href="http://bugs.friendica.com" target="_blank" title="' . t('Report Bug') . '"><img src="addon/buglink/bug-x.gif" alt="' . t('Report Bug') . '" /></a></div>'; }

Binary file not shown.

View file

@ -47,7 +47,8 @@ function communityhome_home(&$a, &$o){
0,
12
);
$tpl = file_get_contents( dirname(__file__).'/directory_item.tpl');
# $tpl = file_get_contents( dirname(__file__).'/directory_item.tpl');
$tpl = get_markup_template( 'directory_item.tpl', 'addon/communityhome/' );
if(count($r)) {
$photo = 'thumb';
foreach($r as $rr) {
@ -105,6 +106,7 @@ function communityhome_home(&$a, &$o){
`user`
WHERE `user`.`uid` = `photo`.`uid`
AND `user`.`blockwall`=0
AND `user`.`hidewall` = 0
ORDER BY `photo`.`edited` DESC
LIMIT 0, 12",
dbesc(t('Contact Photos')),
@ -113,7 +115,8 @@ function communityhome_home(&$a, &$o){
if(count($r)) {
$tpl = file_get_contents( dirname(__file__).'/directory_item.tpl');
# $tpl = file_get_contents( dirname(__file__).'/directory_item.tpl');
$tpl = get_markup_template( 'directory_item.tpl', 'addon/communityhome/' );
foreach($r as $rr) {
$photo_page = $a->get_baseurl() . '/photos/' . $rr['nickname'] . '/image/' . $rr['resource-id'];
$photo_url = $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] .'.jpg';
@ -173,7 +176,8 @@ function communityhome_home(&$a, &$o){
}
$tpl = file_get_contents(dirname(__file__).'/communityhome.tpl');
# $tpl = file_get_contents(dirname(__file__).'/communityhome.tpl');
$tpl = get_markup_template('communityhome.tpl', 'addon/communityhome/');
$a->page['aside'] = replace_macros($tpl, $aside);
$o = '<h1>' . ((x($a->config,'sitename')) ? sprintf( t("Welcome to %s") ,$a->config['sitename']) : "" ) . '</h1>';

View file

@ -0,0 +1,70 @@
<script>
$(function(){
$("#tab_1 a").click(function(e){
$("#login_standard").show();
$("#login_openid").hide();
$("#tab_1").addClass("active");
$("#tab_2").removeClass("active");
e.preventDefault();
return false;
});
$("#tab_2 a").click(function(e){
$("#login_openid").show();
$("#login_standard").hide();
$("#tab_2").addClass("active");
$("#tab_1").removeClass("active");
e.preventDefault();
return false;
});
});
</script>
{{if $noOid}}
<h3>{{$login_title}}</h3>
{{else}}
<ul class="tabs">
<li id="tab_1" class="tab button active"><a href="#">{{$tab_1}}</a></li>
<li id="tab_2" class="tab button"><a href="#">{{$tab_2}}</a></li>
</ul>
{{/if}}
{{$login_form}}
{{if $lastusers_title}}
<h3>{{$lastusers_title}}</h3>
<div class='items-wrapper'>
{{foreach $lastusers_items as $i}}
{{$i}}
{{/foreach}}
</div>
{{/if}}
{{if $activeusers_title}}
<h3>{{$activeusers_title}}</h3>
<div class='items-wrapper'>
{{foreach $activeusers_items as $i}}
{{$i}}
{{/foreach}}
</div>
{{/if}}
{{if $photos_title}}
<h3>{{$photos_title}}</h3>
<div class='items-wrapper'>
{{foreach $photos_items as $i}}
{{$i}}
{{/foreach}}
</div>
{{/if}}
{{if $like_title}}
<h3>{{$like_title}}</h3>
<ul id='likes'>
{{foreach $like_items as $i}}
<li>{{$i}}</li>
{{/foreach}}
</ul>
{{/if}}

View file

@ -0,0 +1,10 @@
<div class="directory-item" id="directory-item-{{$id}}" >
<div class="directory-photo-wrapper" id="directory-photo-wrapper-{{$id}}" >
<div class="directory-photo" id="directory-photo-{{$id}}" >
<a href="{{$profile}}-link" class="directory-profile-link" id="directory-profile-link-{{$id}}" >
<img class="directory-photo-img" src="{{$photo}}" alt="{{$alt}}-text" title="{{$alt}}-text" />
</a>
</div>
</div>
</div>

Binary file not shown.

BIN
dav.tgz Normal file

Binary file not shown.

View file

@ -1,3 +1,8 @@
v0.3
[REFACTOR] The new version of the VObject Library is used
[REFACTOR] The addressbook part has beed heavily refactored
[REFACTOR] Remove some Friendica-specific code out of the "common"-folder
v0.2.0
======
[FEATURE] Multiple private Calendars can be created. Each calendar can have its own default color; single events of a calendar can override this setting.

View file

@ -14,6 +14,7 @@
only used for informational purposes.
* BC Break: The DAV: namespace is no longer converted to urn:DAV. This was
a workaround for a bug in older PHP versions (pre-5.3).
* Changed: The Sabre_VObject library now spawned into it's own project!
* New feature: Support for caldav notifications!
* Changed: Responsibility for dealing with the calendar-query is now
moved from the CalDAV plugin to the CalDAV backends. This allows for
@ -33,13 +34,14 @@
* Fixed: Uploaded VCards without a UID are now rejected. (thanks Dominik!)
* Fixed: Rejecting calendar objects if they are not in the
supported-calendar-component list. (thanks Armin!)
* Fixed: Workaround for 10.8 Mountain Lion vCards, as it needs \r line
endings to parse them correctly.
* Fixed: Issue 219: serialize() now reorders correctly.
* Fixed: Sabre_DAV_XMLUtil no longer returns empty $dom->childNodes
if there is whitespace in $dom.
1.6.4-stable (2012-??-??)
1.6.5-stable (2012-??-??)
* Fixed: Workaround for line-ending bug OS X 10.8 addressbook has.
1.6.4-stable (2012-08-02)
* Fixed: Issue 220: Calendar-query filters may fail when filtering on
alarms, if an overridden event has it's alarm removed.
* Fixed: Compatibility for OS/X 10.8 iCal in the IMipHandler.
@ -56,6 +58,8 @@
exactly on the start of a time-range.
* Fixed: HTTP basic auth did not correctly deal with passwords containing
colons on some servers.
* Fixed: Issue 228: DTEND is now non-inclusive for all-day events in the
calendar-query REPORT and free-busy calculations.
1.6.3-stable (2012-06-12)
* Added: It's now possible to specify in Sabre_DAV_Client which type of

View file

@ -1,21 +1,30 @@
{
"name": "evert/sabredav",
"name": "sabre/dav",
"type": "library",
"description": "WebDAV Framework for PHP",
"keywords": ["Framework", "WebDAV", "CalDAV", "CardDAV", "iCalendar"],
"homepage": "http://code.google.com/p/sabredav/",
"license": "New BSD License",
"license" : "BSD-3-Clause",
"authors": [
{
"name": "Evert Pot",
"email": "evert@rooftopsolutions.nl",
"homepage" : "http://www.rooftopsolutions.nl/"
"homepage" : "http://www.rooftopsolutions.nl/",
"role" : "Developer"
}
],
"require": {
"php": ">=5.3.1"
"php": ">=5.3.1",
"sabre/vobject" : "master-dev"
},
"provide" : {
"evert/sabredav" : "2.0.0"
},
"autoload": {
"psr-0": { "Sabre": "lib/" }
},
"support" : {
"forum" : "https://groups.google.com/group/sabredav-discuss",
"source" : "https://github.com/evert/sabredav"
}
}

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* Abstract Calendaring backend. Extend this class to create your own backends.
*
@ -140,7 +142,7 @@ abstract class Sabre_CalDAV_Backend_Abstract implements Sabre_CalDAV_Backend_Bac
$object = $this->getCalendarObject($object['calendarid'], $object['uri']);
}
$vObject = Sabre_VObject_Reader::read($object['calendardata']);
$vObject = VObject\Reader::read($object['calendardata']);
$validator = new Sabre_CalDAV_CalendarQueryValidator();
return $validator->validate($vObject, $filters);

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* PDO CalDAV backend
*
@ -462,7 +464,7 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract {
*/
protected function getDenormalizedData($calendarData) {
$vObject = Sabre_VObject_Reader::read($calendarData);
$vObject = VObject\Reader::read($calendarData);
$componentType = null;
$component = null;
$firstOccurence = null;
@ -484,9 +486,9 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract {
$lastOccurence = $component->DTEND->getDateTime()->getTimeStamp();
} elseif (isset($component->DURATION)) {
$endDate = clone $component->DTSTART->getDateTime();
$endDate->add(Sabre_VObject_DateTimeParser::parse($component->DURATION->value));
$endDate->add(VObject\DateTimeParser::parse($component->DURATION->value));
$lastOccurence = $endDate->getTimeStamp();
} elseif ($component->DTSTART->getDateType()===Sabre_VObject_Property_DateTime::DATE) {
} elseif ($component->DTSTART->getDateType()===VObject\Property\DateTime::DATE) {
$endDate = clone $component->DTSTART->getDateTime();
$endDate->modify('+1 day');
$lastOccurence = $endDate->getTimeStamp();
@ -494,7 +496,7 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract {
$lastOccurence = $firstOccurence;
}
} else {
$it = new Sabre_VObject_RecurrenceIterator($vObject, (string)$component->UID);
$it = new VObject\RecurrenceIterator($vObject, (string)$component->UID);
$maxDate = new DateTime(self::MAX_DATE);
if ($it->isInfinite()) {
$lastOccurence = $maxDate->getTimeStamp();

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* Parses the calendar-query report request body.
*
@ -241,12 +243,12 @@ class Sabre_CalDAV_CalendarQueryParser {
$timeRangeNode = $timeRangeNodes->item(0);
if ($start = $timeRangeNode->getAttribute('start')) {
$start = Sabre_VObject_DateTimeParser::parseDateTime($start);
$start = VObject\DateTimeParser::parseDateTime($start);
} else {
$start = null;
}
if ($end = $timeRangeNode->getAttribute('end')) {
$end = Sabre_VObject_DateTimeParser::parseDateTime($end);
$end = VObject\DateTimeParser::parseDateTime($end);
} else {
$end = null;
}
@ -274,13 +276,13 @@ class Sabre_CalDAV_CalendarQueryParser {
if(!$start) {
throw new Sabre_DAV_Exception_BadRequest('The "start" attribute is required for the CALDAV:expand element');
}
$start = Sabre_VObject_DateTimeParser::parseDateTime($start);
$start = VObject\DateTimeParser::parseDateTime($start);
$end = $parentNode->getAttribute('end');
if(!$end) {
throw new Sabre_DAV_Exception_BadRequest('The "end" attribute is required for the CALDAV:expand element');
}
$end = Sabre_VObject_DateTimeParser::parseDateTime($end);
$end = VObject\DateTimeParser::parseDateTime($end);
if ($end <= $start) {
throw new Sabre_DAV_Exception_BadRequest('The end-date must be larger than the start-date in the expand element.');

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* CalendarQuery Validator
*
@ -22,11 +24,11 @@ class Sabre_CalDAV_CalendarQueryValidator {
*
* The list of filters must be formatted as parsed by Sabre_CalDAV_CalendarQueryParser
*
* @param Sabre_VObject_Component $vObject
* @param VObject\Component $vObject
* @param array $filters
* @return bool
*/
public function validate(Sabre_VObject_Component $vObject,array $filters) {
public function validate(VObject\Component $vObject,array $filters) {
// The top level object is always a component filter.
// We'll parse it manually, as it's pretty simple.
@ -48,11 +50,11 @@ class Sabre_CalDAV_CalendarQueryValidator {
* component we're checking should be specified, not the component to check
* itself.
*
* @param Sabre_VObject_Component $parent
* @param VObject\Component $parent
* @param array $filters
* @return bool
*/
protected function validateCompFilters(Sabre_VObject_Component $parent, array $filters) {
protected function validateCompFilters(VObject\Component $parent, array $filters) {
foreach($filters as $filter) {
@ -117,11 +119,11 @@ class Sabre_CalDAV_CalendarQueryValidator {
* property we're checking should be specified, not the property to check
* itself.
*
* @param Sabre_VObject_Component $parent
* @param VObject\Component $parent
* @param array $filters
* @return bool
*/
protected function validatePropFilters(Sabre_VObject_Component $parent, array $filters) {
protected function validatePropFilters(VObject\Component $parent, array $filters) {
foreach($filters as $filter) {
@ -187,11 +189,11 @@ class Sabre_CalDAV_CalendarQueryValidator {
* parameter we're checking should be specified, not the parameter to check
* itself.
*
* @param Sabre_VObject_Property $parent
* @param VObject\Property $parent
* @param array $filters
* @return bool
*/
protected function validateParamFilters(Sabre_VObject_Property $parent, array $filters) {
protected function validateParamFilters(VObject\Property $parent, array $filters) {
foreach($filters as $filter) {
@ -243,11 +245,11 @@ class Sabre_CalDAV_CalendarQueryValidator {
* A single text-match should be specified as well as the specific property
* or parameter we need to validate.
*
* @param Sabre_VObject_Node $parent
* @param VObject\Node $parent
* @param array $textMatch
* @return bool
*/
protected function validateTextMatch(Sabre_VObject_Node $parent, array $textMatch) {
protected function validateTextMatch(VObject\Node $parent, array $textMatch) {
$value = (string)$parent;
@ -263,12 +265,12 @@ class Sabre_CalDAV_CalendarQueryValidator {
* This is all based on the rules specified in rfc4791, which are quite
* complex.
*
* @param Sabre_VObject_Node $component
* @param VObject\Node $component
* @param DateTime $start
* @param DateTime $end
* @return bool
*/
protected function validateTimeRange(Sabre_VObject_Node $component, $start, $end) {
protected function validateTimeRange(VObject\Node $component, $start, $end) {
if (is_null($start)) {
$start = new DateTime('1900-01-01');
@ -296,7 +298,7 @@ class Sabre_CalDAV_CalendarQueryValidator {
if ($component->parent->name === 'VEVENT' && $component->parent->RRULE) {
// Fire up the iterator!
$it = new Sabre_VObject_RecurrenceIterator($component->parent->parent, (string)$component->parent->UID);
$it = new VObject\RecurrenceIterator($component->parent->parent, (string)$component->parent->UID);
while($it->valid()) {
$expandedEvent = $it->getEventObject();

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* ICS Exporter
*
@ -82,7 +84,7 @@ class Sabre_CalDAV_ICSExportPlugin extends Sabre_DAV_ServerPlugin {
*/
public function generateICS(array $nodes) {
$calendar = new Sabre_VObject_Component('vcalendar');
$calendar = new VObject\Component('vcalendar');
$calendar->version = '2.0';
if (Sabre_DAV_Server::$exposeVersion) {
$calendar->prodid = '-//SabreDAV//SabreDAV ' . Sabre_DAV_Version::VERSION . '//EN';
@ -103,7 +105,7 @@ class Sabre_CalDAV_ICSExportPlugin extends Sabre_DAV_ServerPlugin {
}
$nodeData = $node[200]['{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}calendar-data'];
$nodeComp = Sabre_VObject_Reader::read($nodeData);
$nodeComp = VObject\Reader::read($nodeData);
foreach($nodeComp->children() as $child) {

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* CalDAV plugin
*
@ -456,8 +458,8 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin {
if(!$start || !$end) {
throw new Sabre_DAV_Exception_BadRequest('The "start" and "end" attributes are required for the CALDAV:expand element');
}
$start = Sabre_VObject_DateTimeParser::parseDateTime($start);
$end = Sabre_VObject_DateTimeParser::parseDateTime($end);
$start = VObject\DateTimeParser::parseDateTime($start);
$end = VObject\DateTimeParser::parseDateTime($end);
if ($end <= $start) {
throw new Sabre_DAV_Exception_BadRequest('The end-date must be larger than the start-date in the expand element.');
@ -476,7 +478,7 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin {
list($objProps) = $this->server->getPropertiesForPath($uri,$properties);
if ($expand && isset($objProps[200]['{' . self::NS_CALDAV . '}calendar-data'])) {
$vObject = Sabre_VObject_Reader::read($objProps[200]['{' . self::NS_CALDAV . '}calendar-data']);
$vObject = VObject\Reader::read($objProps[200]['{' . self::NS_CALDAV . '}calendar-data']);
$vObject->expand($start, $end);
$objProps[200]['{' . self::NS_CALDAV . '}calendar-data'] = $vObject->serialize();
}
@ -543,7 +545,7 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin {
if (isset($properties[200]['{urn:ietf:params:xml:ns:caldav}calendar-data'])) {
$validator = new Sabre_CalDAV_CalendarQueryValidator();
$vObject = Sabre_VObject_Reader::read($properties[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']);
$vObject = VObject\Reader::read($properties[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']);
if ($validator->validate($vObject,$parser->filters)) {
// If the client didn't require the calendar-data property,
@ -577,7 +579,7 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin {
if ($parser->expand) {
// We need to do some post-processing
$vObject = Sabre_VObject_Reader::read($properties[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']);
$vObject = VObject\Reader::read($properties[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']);
$vObject->expand($parser->expand['start'], $parser->expand['end']);
$properties[200]['{' . self::NS_CALDAV . '}calendar-data'] = $vObject->serialize();
}
@ -617,10 +619,10 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin {
}
if ($start) {
$start = Sabre_VObject_DateTimeParser::parseDateTime($start);
$start = VObject\DateTimeParser::parseDateTime($start);
}
if ($end) {
$end = Sabre_VObject_DateTimeParser::parseDateTime($end);
$end = VObject\DateTimeParser::parseDateTime($end);
}
if (!$start && !$end) {
@ -647,7 +649,7 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin {
return $obj;
}, $calendar->getChildren());
$generator = new Sabre_VObject_FreeBusyGenerator();
$generator = new VObject\FreeBusyGenerator();
$generator->setObjects($objects);
$generator->setTimeRange($start, $end);
$result = $generator->getResult();
@ -763,9 +765,9 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin {
try {
$vobj = Sabre_VObject_Reader::read($data);
$vobj = VObject\Reader::read($data);
} catch (Sabre_VObject_ParseException $e) {
} catch (VObject\ParseException $e) {
throw new Sabre_DAV_Exception_UnsupportedMediaType('This resource only supports valid iCalendar 2.0 data. Parse error: ' . $e->getMessage());
@ -868,8 +870,8 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin {
}
try {
$vObject = Sabre_VObject_Reader::read($this->server->httpRequest->getBody(true));
} catch (Sabre_VObject_ParseException $e) {
$vObject = VObject\Reader::read($this->server->httpRequest->getBody(true));
} catch (VObject\ParseException $e) {
throw new Sabre_DAV_Exception_BadRequest('The request body must be a valid iCalendar object. Parse error: ' . $e->getMessage());
}
@ -920,10 +922,10 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin {
*
* @param string $originator
* @param array $recipients
* @param Sabre_VObject_Component $vObject
* @param Sabre\VObject\Component $vObject
* @return array
*/
protected function iMIPMessage($originator, array $recipients, Sabre_VObject_Component $vObject, $principal) {
protected function iMIPMessage($originator, array $recipients, VObject\Component $vObject, $principal) {
if (!$this->imipHandler) {
$resultStatus = '5.2;This server does not support this operation';

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* iMIP handler.
*
@ -44,11 +46,11 @@ class Sabre_CalDAV_Schedule_IMip {
*
* @param string $originator Originator Email
* @param array $recipients Array of email addresses
* @param Sabre_VObject_Component $vObject
* @param Sabre\VObject\Component $vObject
* @param string $principal Principal Url of the originator
* @return void
*/
public function sendMessage($originator, array $recipients, Sabre_VObject_Component $vObject, $principal) {
public function sendMessage($originator, array $recipients, VObject\Component $vObject, $principal) {
foreach($recipients as $recipient) {

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* CardDAV plugin
*
@ -345,9 +347,9 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin {
try {
$vobj = Sabre_VObject_Reader::read($data);
$vobj = VObject\Reader::read($data);
} catch (Sabre_VObject_ParseException $e) {
} catch (VObject\ParseException $e) {
throw new Sabre_DAV_Exception_UnsupportedMediaType('This resource only supports valid vcard data. Parse error: ' . $e->getMessage());
@ -441,7 +443,7 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin {
*/
public function validateFilters($vcardData, array $filters, $test) {
$vcard = Sabre_VObject_Reader::read($vcardData);
$vcard = VObject\Reader::read($vcardData);
if (!$filters) return true;

View file

@ -1,39 +0,0 @@
<?php
/**
* Sabre_VObject includes file
*
* Including this file will automatically include all files from the VObject
* package.
*
* This often allows faster loadtimes, as autoload-speed is often quite slow.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
// Begin includes
include __DIR__ . '/DateTimeParser.php';
include __DIR__ . '/ElementList.php';
include __DIR__ . '/FreeBusyGenerator.php';
include __DIR__ . '/Node.php';
include __DIR__ . '/Parameter.php';
include __DIR__ . '/ParseException.php';
include __DIR__ . '/Reader.php';
include __DIR__ . '/RecurrenceIterator.php';
include __DIR__ . '/TimeZoneUtil.php';
include __DIR__ . '/Version.php';
include __DIR__ . '/Element.php';
include __DIR__ . '/Property.php';
include __DIR__ . '/Component.php';
include __DIR__ . '/Property/DateTime.php';
include __DIR__ . '/Property/MultiDateTime.php';
include __DIR__ . '/Component/VAlarm.php';
include __DIR__ . '/Component/VCalendar.php';
include __DIR__ . '/Component/VEvent.php';
include __DIR__ . '/Component/VJournal.php';
include __DIR__ . '/Component/VTodo.php';
// End includes

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
class Sabre_CalDAV_CalendarQueryVAlarmTest extends PHPUnit_Framework_TestCase {
/**
@ -8,16 +10,16 @@ class Sabre_CalDAV_CalendarQueryVAlarmTest extends PHPUnit_Framework_TestCase {
*/
function testValarm() {
$vevent = Sabre_VObject_Component::create('VEVENT');
$vevent = VObject\Component::create('VEVENT');
$vevent->RRULE = 'FREQ=MONTHLY';
$vevent->DTSTART = '20120101T120000Z';
$vevent->UID = 'bla';
$valarm = Sabre_VObject_Component::create('VALARM');
$valarm = VObject\Component::create('VALARM');
$valarm->TRIGGER = '-P15D';
$vevent->add($valarm);
$vcalendar = Sabre_VObject_Component::create('VCALENDAR');
$vcalendar = VObject\Component::create('VCALENDAR');
$vcalendar->add($vevent);
$filter = array(
@ -52,16 +54,16 @@ class Sabre_CalDAV_CalendarQueryVAlarmTest extends PHPUnit_Framework_TestCase {
// A limited recurrence rule, should return false
$vevent = Sabre_VObject_Component::create('VEVENT');
$vevent = VObject\Component::create('VEVENT');
$vevent->RRULE = 'FREQ=MONTHLY;COUNT=1';
$vevent->DTSTART = '20120101T120000Z';
$vevent->UID = 'bla';
$valarm = Sabre_VObject_Component::create('VALARM');
$valarm = VObject\Component::create('VALARM');
$valarm->TRIGGER = '-P15D';
$vevent->add($valarm);
$vcalendar = Sabre_VObject_Component::create('VCALENDAR');
$vcalendar = VObject\Component::create('VCALENDAR');
$vcalendar->add($vevent);
$this->assertFalse($validator->validate($vcalendar, $filter));
@ -69,15 +71,15 @@ class Sabre_CalDAV_CalendarQueryVAlarmTest extends PHPUnit_Framework_TestCase {
function testAlarmWayBefore() {
$vevent = Sabre_VObject_Component::create('VEVENT');
$vevent = VObject\Component::create('VEVENT');
$vevent->DTSTART = '20120101T120000Z';
$vevent->UID = 'bla';
$valarm = Sabre_VObject_Component::create('VALARM');
$valarm = VObject\Component::create('VALARM');
$valarm->TRIGGER = '-P2W1D';
$vevent->add($valarm);
$vcalendar = Sabre_VObject_Component::create('VCALENDAR');
$vcalendar = VObject\Component::create('VCALENDAR');
$vcalendar->add($vevent);
$filter = array(

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
class Sabre_CalDAV_CalendarQueryValidatorTest extends PHPUnit_Framework_TestCase {
/**
@ -19,7 +21,7 @@ class Sabre_CalDAV_CalendarQueryValidatorTest extends PHPUnit_Framework_TestCase
'time-range' => null,
);
$vObject = Sabre_VObject_Reader::read($icalObject);
$vObject = VObject\Reader::read($icalObject);
switch($outcome) {
case 0 :
@ -31,7 +33,7 @@ class Sabre_CalDAV_CalendarQueryValidatorTest extends PHPUnit_Framework_TestCase
case -1 :
try {
$validator->validate($vObject, $filters);
} catch (Sabre_DAV_Exception $e) {
} catch (Exception $e) {
// Success
}
break;

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* This unittests is created to find out why recurring events have wrong DTSTART value
*
@ -83,13 +85,13 @@ END:VCALENDAR
);
$body = str_replace('&#13;','',$body);
$vObject = Sabre_VObject_Reader::read($body);
$vObject = VObject\Reader::read($body);
// check if DTSTARTs and DTENDs are correct
foreach ($vObject->VEVENT as $vevent) {
/** @var $vevent Sabre_VObject_Component_VEvent */
/** @var $vevent Sabre\VObject\Component_VEvent */
foreach ($vevent->children as $child) {
/** @var $child Sabre_VObject_Property */
/** @var $child Sabre\VObject\Property */
if ($child->name == 'DTSTART') {
// DTSTART has to be one of three valid values

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* This unittests is created to find out why recurring events have wrong DTSTART value
*
@ -75,15 +77,15 @@ END:VCALENDAR
);
$body = str_replace('&#13;','',$body);
$vObject = Sabre_VObject_Reader::read($body);
$vObject = VObject\Reader::read($body);
$this->assertEquals(2, count($vObject->VEVENT));
// check if DTSTARTs and DTENDs are correct
foreach ($vObject->VEVENT as $vevent) {
/** @var $vevent Sabre_VObject_Component_VEvent */
/** @var $vevent Sabre\VObject\Component\VEvent */
foreach ($vevent->children as $child) {
/** @var $child Sabre_VObject_Property */
/** @var $child Sabre\VObject\Property */
if ($child->name == 'DTSTART') {
// DTSTART has to be one of two valid values

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* This unittests is created to find out why certain events show up twice.
*
@ -85,7 +87,7 @@ END:VCALENDAR
);
$body = str_replace('&#13;','',$body);
$vObject = Sabre_VObject_Reader::read($body);
$vObject = VObject\Reader::read($body);
// We only expect 3 events
$this->assertEquals(3, count($vObject->VEVENT),'We got 6 events instead of 3. Output: ' . $body);

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* This unittest is created to check if queries for time-range include the start timestamp or not
*
@ -82,7 +84,7 @@ END:VCALENDAR
);
$body = str_replace('&#13;','',$body);
$vObject = Sabre_VObject_Reader::read($body);
$vObject = VObject\Reader::read($body);
// We expect 1 event
$this->assertEquals(1, count($vObject->VEVENT), 'We got 0 events instead of 1. Output: ' . $body);

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
require_once 'Sabre/CalDAV/TestUtil.php';
require_once 'Sabre/DAV/Auth/MockBackend.php';
require_once 'Sabre/HTTP/ResponseMock.php';
@ -49,7 +51,7 @@ class Sabre_CalDAV_ICSExportPluginTest extends PHPUnit_Framework_TestCase {
'Content-Type' => 'text/calendar',
), $s->httpResponse->headers);
$obj = Sabre_VObject_Reader::read($s->httpResponse->body);
$obj = VObject\Reader::read($s->httpResponse->body);
$this->assertEquals(5,count($obj->children()));
$this->assertEquals(1,count($obj->VERSION));
@ -98,7 +100,7 @@ class Sabre_CalDAV_ICSExportPluginTest extends PHPUnit_Framework_TestCase {
'Content-Type' => 'text/calendar',
), $s->httpResponse->headers);
$obj = Sabre_VObject_Reader::read($s->httpResponse->body);
$obj = VObject\Reader::read($s->httpResponse->body);
$this->assertEquals(5,count($obj->children()));
$this->assertEquals(1,count($obj->VERSION));
@ -211,7 +213,7 @@ class Sabre_CalDAV_ICSExportPluginTest extends PHPUnit_Framework_TestCase {
'Content-Type' => 'text/calendar',
), $s->httpResponse->headers);
$obj = Sabre_VObject_Reader::read($s->httpResponse->body);
$obj = VObject\Reader::read($s->httpResponse->body);
$this->assertEquals(5,count($obj->children()));
$this->assertEquals(1,count($obj->VERSION));

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
class Sabre_CalDAV_Issue166Test extends PHPUnit_Framework_TestCase {
function testFlaw() {
@ -51,7 +53,7 @@ HI;
'is-not-defined' => false,
'time-range' => null,
);
$input = Sabre_VObject_Reader::read($input);
$input = VObject\Reader::read($input);
$this->assertTrue($validator->validate($input,$filters));
}

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
class Sabre_CalDAV_Issue172Test extends PHPUnit_Framework_TestCase {
// DateTimeZone() native name: America/Los_Angeles (GMT-8 in January)
@ -30,7 +32,7 @@ HI;
),
'prop-filters' => array(),
);
$input = Sabre_VObject_Reader::read($input);
$input = VObject\Reader::read($input);
$this->assertTrue($validator->validate($input,$filters));
}
@ -77,7 +79,7 @@ HI;
),
'prop-filters' => array(),
);
$input = Sabre_VObject_Reader::read($input);
$input = VObject\Reader::read($input);
$this->assertTrue($validator->validate($input,$filters));
}
@ -125,7 +127,7 @@ HI;
),
'prop-filters' => array(),
);
$input = Sabre_VObject_Reader::read($input);
$input = VObject\Reader::read($input);
$this->assertTrue($validator->validate($input,$filters));
}
}

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* This unittest is created to find out why an overwritten DAILY event has wrong DTSTART, DTEND, SUMMARY and RECURRENCEID
*
@ -88,7 +90,7 @@ END:VCALENDAR
);
$body = str_replace('&#13;','',$body);
$vObject = Sabre_VObject_Reader::read($body);
$vObject = VObject\Reader::read($body);
$this->assertEquals(2, count($vObject->VEVENT));
@ -113,10 +115,10 @@ END:VCALENDAR
$matching = false;
foreach ($vObject->VEVENT as $vevent) {
/** @var $vevent Sabre_VObject_Component_VEvent */
/** @var $vevent Sabre\VObject\Component\VEvent */
foreach ($vevent->children as $child) {
/** @var $child Sabre_VObject_Property */
/** @var $child Sabre\VObject\Property */
if (isset($expectedEvent[$child->name])) {
if ($expectedEvent[$child->name] != $child->value) {

View file

@ -1,5 +1,7 @@
<?php
use Sabre\VObject;
/**
* This unittest is created to check if a VALARM TRIGGER of PT0S is supported
*
@ -86,7 +88,7 @@ END:VCALENDAR
);
$body = str_replace('&#13;','',$body);
$vObject = Sabre_VObject_Reader::read($body);
$vObject = VObject\Reader::read($body);
$this->assertEquals(1, count($vObject->VEVENT));

View file

@ -0,0 +1,75 @@
<?php
/**
* This unittest is created to check if the time-range filter is working correctly with all-day-events
*
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_CalDAV_Issue228Test extends Sabre_DAVServerTest {
protected $setupCalDAV = true;
protected $caldavCalendars = array(
array(
'id' => 1,
'name' => 'Calendar',
'principaluri' => 'principals/user1',
'uri' => 'calendar1',
)
);
protected $caldavCalendarObjects = array(
1 => array(
'event.ics' => array(
'calendardata' => 'BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:20120730T113415CEST-6804EGphkd@xxxxxx.de
DTSTAMP:20120730T093415Z
DTSTART;VALUE=DATE:20120729
DTEND;VALUE=DATE:20120730
SUMMARY:sunday event
TRANSP:TRANSPARENT
END:VEVENT
END:VCALENDAR
',
),
),
);
function testIssue228() {
$request = new Sabre_HTTP_Request(array(
'REQUEST_METHOD' => 'REPORT',
'HTTP_CONTENT_TYPE' => 'application/xml',
'REQUEST_URI' => '/calendars/user1/calendar1',
'HTTP_DEPTH' => '1',
));
$request->setBody('<?xml version="1.0" encoding="utf-8" ?>
<C:calendar-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
<D:prop>
<C:calendar-data>
<C:expand start="20120730T095609Z"
end="20120813T095609Z"/>
</C:calendar-data>
<D:getetag/>
</D:prop>
<C:filter>
<C:comp-filter name="VCALENDAR">
<C:comp-filter name="VEVENT">
<C:time-range start="20120730T095609Z" end="20120813T095609Z"/>
</C:comp-filter>
</C:comp-filter>
</C:filter>
</C:calendar-query>');
$response = $this->request($request);
// We must check if absolutely nothing was returned from this query.
$this->assertFalse(strpos($response->body, 'BEGIN:VCALENDAR'));
}
}

View file

@ -1,69 +0,0 @@
<?php
class Sabre_VObject_Component_VEventTest extends PHPUnit_Framework_TestCase {
/**
* @dataProvider timeRangeTestData
*/
public function testInTimeRange(Sabre_VObject_Component_VEvent $vevent,$start,$end,$outcome) {
$this->assertEquals($outcome, $vevent->isInTimeRange($start, $end));
}
public function timeRangeTestData() {
$tests = array();
$vevent = new Sabre_VObject_Component_VEvent('VEVENT');
$vevent->DTSTART = '20111223T120000Z';
$tests[] = array($vevent, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vevent, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$vevent2 = clone $vevent;
$vevent2->DTEND = '20111225T120000Z';
$tests[] = array($vevent2, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vevent2, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$vevent3 = clone $vevent;
$vevent3->DURATION = 'P1D';
$tests[] = array($vevent3, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vevent3, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$vevent4 = clone $vevent;
$vevent4->DTSTART = '20111225';
$vevent4->DTSTART['VALUE'] = 'DATE';
$tests[] = array($vevent4, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vevent4, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
// Event with no end date should be treated as lasting the entire day.
$tests[] = array($vevent4, new DateTime('2011-12-25 16:00:00'), new DateTime('2011-12-25 17:00:00'), true);
$vevent5 = clone $vevent;
$vevent5->DURATION = 'P1D';
$vevent5->RRULE = 'FREQ=YEARLY';
$tests[] = array($vevent5, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vevent5, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$tests[] = array($vevent5, new DateTime('2013-12-01'), new DateTime('2013-12-31'), true);
$vevent6 = clone $vevent;
$vevent6->DTSTART = '20111225';
$vevent6->DTSTART['VALUE'] = 'DATE';
$vevent6->DTEND = '20111225';
$vevent6->DTEND['VALUE'] = 'DATE';
$tests[] = array($vevent6, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vevent6, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
// Added this test to ensure that recurrence rules with no DTEND also
// get checked for the entire day.
$vevent7 = clone $vevent;
$vevent7->DTSTART = '20120101';
$vevent7->DTSTART['VALUE'] = 'DATE';
$vevent7->RRULE = 'FREQ=MONTHLY';
$tests[] = array($vevent7, new DateTime('2012-02-01 15:00:00'), new DateTime('2012-02-02'), true);
return $tests;
}
}

View file

@ -1,37 +0,0 @@
<?php
class Sabre_VObject_Component_VJournalTest extends PHPUnit_Framework_TestCase {
/**
* @dataProvider timeRangeTestData
*/
public function testInTimeRange(Sabre_VObject_Component_VJournal $vtodo,$start,$end,$outcome) {
$this->assertEquals($outcome, $vtodo->isInTimeRange($start, $end));
}
public function timeRangeTestData() {
$tests = array();
$vjournal = Sabre_VObject_Component::create('VJOURNAL');
$vjournal->DTSTART = '20111223T120000Z';
$tests[] = array($vjournal, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vjournal, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$vjournal2 = Sabre_VObject_Component::create('VJOURNAL');
$vjournal2->DTSTART = '20111223';
$vjournal2->DTSTART['VALUE'] = 'DATE';
$tests[] = array($vjournal2, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vjournal2, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$vjournal3 = Sabre_VObject_Component::create('VJOURNAL');
$tests[] = array($vjournal3, new DateTime('2011-01-01'), new DateTime('2012-01-01'), false);
$tests[] = array($vjournal3, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
return $tests;
}
}

View file

@ -1,63 +0,0 @@
<?php
class Sabre_VObject_Component_VTodoTest extends PHPUnit_Framework_TestCase {
/**
* @dataProvider timeRangeTestData
*/
public function testInTimeRange(Sabre_VObject_Component_VTodo $vtodo,$start,$end,$outcome) {
$this->assertEquals($outcome, $vtodo->isInTimeRange($start, $end));
}
public function timeRangeTestData() {
$tests = array();
$vtodo = Sabre_VObject_Component::create('VTODO');
$vtodo->DTSTART = '20111223T120000Z';
$tests[] = array($vtodo, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vtodo, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$vtodo2 = clone $vtodo;
$vtodo2->DURATION = 'P1D';
$tests[] = array($vtodo2, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vtodo2, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$vtodo3 = clone $vtodo;
$vtodo3->DUE = '20111225';
$tests[] = array($vtodo3, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vtodo3, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$vtodo4 = Sabre_VObject_Component::create('VTODO');
$vtodo4->DUE = '20111225';
$tests[] = array($vtodo4, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vtodo4, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$vtodo5 = Sabre_VObject_Component::create('VTODO');
$vtodo5->COMPLETED = '20111225';
$tests[] = array($vtodo5, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vtodo5, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$vtodo6 = Sabre_VObject_Component::create('VTODO');
$vtodo6->CREATED = '20111225';
$tests[] = array($vtodo6, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vtodo6, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$vtodo7 = Sabre_VObject_Component::create('VTODO');
$vtodo7->CREATED = '20111225';
$vtodo7->COMPLETED = '20111226';
$tests[] = array($vtodo7, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vtodo7, new DateTime('2011-01-01'), new DateTime('2011-11-01'), false);
$vtodo7 = Sabre_VObject_Component::create('VTODO');
$tests[] = array($vtodo7, new DateTime('2011-01-01'), new DateTime('2012-01-01'), true);
$tests[] = array($vtodo7, new DateTime('2011-01-01'), new DateTime('2011-11-01'), true);
return $tests;
}
}

View file

@ -1,117 +0,0 @@
<?php
require_once 'Sabre/CalDAV/TestUtil.php';
class Sabre_VObject_DateTimeParserTest extends PHPUnit_Framework_TestCase {
function testParseICalendarDuration() {
$this->assertEquals('+1 weeks', Sabre_VObject_DateTimeParser::parseDuration('P1W',true));
$this->assertEquals('+5 days', Sabre_VObject_DateTimeParser::parseDuration('P5D',true));
$this->assertEquals('+5 days 3 hours 50 minutes 12 seconds', Sabre_VObject_DateTimeParser::parseDuration('P5DT3H50M12S',true));
$this->assertEquals('-1 weeks 50 minutes', Sabre_VObject_DateTimeParser::parseDuration('-P1WT50M',true));
$this->assertEquals('+50 days 3 hours 2 seconds', Sabre_VObject_DateTimeParser::parseDuration('+P50DT3H2S',true));
$this->assertEquals(new DateInterval('PT0S'), Sabre_VObject_DateTimeParser::parseDuration('PT0S'));
}
function testParseICalendarDurationDateInterval() {
$expected = new DateInterval('P7D');
$this->assertEquals($expected, Sabre_VObject_DateTimeParser::parseDuration('P1W'));
$this->assertEquals($expected, Sabre_VObject_DateTimeParser::parse('P1W'));
$expected = new DateInterval('PT3M');
$expected->invert = true;
$this->assertEquals($expected, Sabre_VObject_DateTimeParser::parseDuration('-PT3M'));
}
/**
* @expectedException Sabre_DAV_Exception_BadRequest
*/
function testParseICalendarDurationFail() {
Sabre_VObject_DateTimeParser::parseDuration('P1X',true);
}
function testParseICalendarDateTime() {
$dateTime = Sabre_VObject_DateTimeParser::parseDateTime('20100316T141405');
$compare = new DateTime('2010-03-16 14:14:05',new DateTimeZone('UTC'));
$this->assertEquals($compare, $dateTime);
}
/**
* @depends testParseICalendarDateTime
* @expectedException Sabre_DAV_Exception_BadRequest
*/
function testParseICalendarDateTimeBadFormat() {
$dateTime = Sabre_VObject_DateTimeParser::parseDateTime('20100316T141405 ');
}
/**
* @depends testParseICalendarDateTime
*/
function testParseICalendarDateTimeUTC() {
$dateTime = Sabre_VObject_DateTimeParser::parseDateTime('20100316T141405Z');
$compare = new DateTime('2010-03-16 14:14:05',new DateTimeZone('UTC'));
$this->assertEquals($compare, $dateTime);
}
/**
* @depends testParseICalendarDateTime
*/
function testParseICalendarDateTimeUTC2() {
$dateTime = Sabre_VObject_DateTimeParser::parseDateTime('20101211T160000Z');
$compare = new DateTime('2010-12-11 16:00:00',new DateTimeZone('UTC'));
$this->assertEquals($compare, $dateTime);
}
/**
* @depends testParseICalendarDateTime
*/
function testParseICalendarDateTimeCustomTimeZone() {
$dateTime = Sabre_VObject_DateTimeParser::parseDateTime('20100316T141405', new DateTimeZone('Europe/Amsterdam'));
$compare = new DateTime('2010-03-16 13:14:05',new DateTimeZone('UTC'));
$this->assertEquals($compare, $dateTime);
}
function testParseICalendarDate() {
$dateTime = Sabre_VObject_DateTimeParser::parseDate('20100316');
$expected = new DateTime('2010-03-16 00:00:00',new DateTimeZone('UTC'));
$this->assertEquals($expected, $dateTime);
$dateTime = Sabre_VObject_DateTimeParser::parse('20100316');
$this->assertEquals($expected, $dateTime);
}
/**
* @depends testParseICalendarDate
* @expectedException Sabre_DAV_Exception_BadRequest
*/
function testParseICalendarDateBadFormat() {
$dateTime = Sabre_VObject_DateTimeParser::parseDate('20100316T141405');
}
}

View file

@ -1,12 +0,0 @@
<?php
class Sabre_VObject_Issue153Test extends PHPUnit_Framework_TestCase {
function testRead() {
$obj = Sabre_VObject_Reader::read(file_get_contents(dirname(__FILE__) . '/issue153.vcf'));
$this->assertEquals('Test Benutzer', (string)$obj->fn);
}
}

View file

@ -4,9 +4,9 @@ define('SABRE_MYSQLDSN','mysql:host=127.0.0.1;dbname=sabredav');
define('SABRE_MYSQLUSER','root');
define('SABRE_MYSQLPASS','');
set_include_path(dirname(__FILE__) . PATH_SEPARATOR . dirname(__FILE__) . '/../lib/' . PATH_SEPARATOR . get_include_path());
set_include_path(__DIR__ . '/../lib/' . PATH_SEPARATOR . __DIR__ . PATH_SEPARATOR . get_include_path());
include 'Sabre/autoload.php';
include __DIR__ . '/../vendor/autoload.php';
include 'Sabre/DAVServerTest.php';
date_default_timezone_set('GMT');

View file

@ -7,7 +7,9 @@ define("DAV_DISPLAYNAME", "{DAV:}displayname");
define("DAV_CALENDARCOLOR", "{http://apple.com/ns/ical/}calendar-color");
class DAVVersionMismatchException extends Exception {}
class DAVVersionMismatchException extends Exception
{
}
class vcard_source_data_email
@ -99,9 +101,6 @@ class vcard_source_data
public $photo;
}
;
/**
* @param vcard_source_data $vcardsource
* @return string
@ -196,13 +195,9 @@ function icalendar_sanitize_string($str = "")
*/
function dav_createRootCalendarNode()
{
$caldavBackend_std = Sabre_CalDAV_Backend_Private::getInstance();
$caldavBackend_community = Sabre_CalDAV_Backend_Friendica::getInstance();
return new Sabre_CalDAV_AnimexxCalendarRootNode(Sabre_DAVACL_PrincipalBackend_Std::getInstance(), array(
$caldavBackend_std,
$caldavBackend_community,
));
$backends = array(Sabre_CalDAV_Backend_Private::getInstance());
foreach ($GLOBALS["CALDAV_PRIVATE_SYSTEM_BACKENDS"] as $backendclass) $backends[] = $backendclass::getInstance();
return new Sabre_CalDAV_AnimexxCalendarRootNode(Sabre_DAVACL_PrincipalBackend_Std::getInstance(), $backends);
}
/**
@ -210,13 +205,10 @@ function dav_createRootCalendarNode()
*/
function dav_createRootContactsNode()
{
$carddavBackend_std = Sabre_CardDAV_Backend_Std::getInstance();
$carddavBackend_community = Sabre_CardDAV_Backend_FriendicaCommunity::getInstance();
$backends = array(Sabre_CardDAV_Backend_Std::getInstance());
foreach ($GLOBALS["CARDDAV_PRIVATE_SYSTEM_BACKENDS"] as $backendclass) $backends[] = $backendclass::getInstance();
return new Sabre_CardDAV_AddressBookRootFriendica(Sabre_DAVACL_PrincipalBackend_Std::getInstance(), array(
$carddavBackend_std,
$carddavBackend_community,
));
return new Sabre_CardDAV_AddressBookRootFriendica(Sabre_DAVACL_PrincipalBackend_Std::getInstance(), $backends);
}
@ -242,15 +234,11 @@ function dav_create_server($force_authentication = false, $needs_caldav = true,
// The object tree needs in turn to be passed to the server class
$server = new Sabre_DAV_Server($tree);
$server->setBaseUri(CALDAV_URL_PREFIX);
if (CALDAV_URL_PREFIX != "") $server->setBaseUri(CALDAV_URL_PREFIX);
$authPlugin = new Sabre_DAV_Auth_Plugin(Sabre_DAV_Auth_Backend_Std::getInstance(), 'SabreDAV');
$authPlugin = new Sabre_DAV_Auth_Plugin(Sabre_DAV_Auth_Backend_Std::getInstance(), DAV_APPNAME);
$server->addPlugin($authPlugin);
$aclPlugin = new Sabre_DAVACL_Plugin_Friendica();
$aclPlugin->defaultUsernamePath = "principals/users";
$server->addPlugin($aclPlugin);
if ($needs_caldav) {
$caldavPlugin = new Sabre_CalDAV_Plugin();
$server->addPlugin($caldavPlugin);
@ -260,6 +248,16 @@ function dav_create_server($force_authentication = false, $needs_caldav = true,
$server->addPlugin($carddavPlugin);
}
if ($GLOBALS["CALDAV_ACL_PLUGIN_CLASS"] != "") {
$aclPlugin = new $GLOBALS["CALDAV_ACL_PLUGIN_CLASS"]();
$aclPlugin->defaultUsernamePath = "principals/users";
$server->addPlugin($aclPlugin);
} else {
$aclPlugin = new Sabre_DAVACL_Plugin();
$aclPlugin->defaultUsernamePath = "principals/users";
$server->addPlugin($aclPlugin);
}
if ($force_authentication) $server->broadcastEvent('beforeMethod', array("GET", "/")); // Make it authenticate
return $server;
@ -286,7 +284,7 @@ function dav_get_current_user_calendars(&$server, $with_privilege = "")
$calendars = array();
/** @var Sabre_DAVACL_Plugin $aclplugin */
$aclplugin = $server->getPlugin("acl");
foreach ($children as $child) if (is_a($child, "Sabre_CalDAV_Calendar")) {
foreach ($children as $child) if (is_a($child, "Sabre_CalDAV_Calendar") || is_subclass_of($child, "Sabre_CalDAV_Calendar")) {
if ($with_privilege != "") {
$caluri = $calendar_path . $child->getName();
if ($aclplugin->checkPrivileges($caluri, $with_privilege, Sabre_DAVACL_Plugin::R_PARENT, false)) $calendars[] = $child;
@ -303,7 +301,7 @@ function dav_get_current_user_calendars(&$server, $with_privilege = "")
* @param Sabre_CalDAV_Calendar $calendar
* @param string $calendarobject_uri
* @param string $with_privilege
* @return null|Sabre_VObject_Component_VCalendar
* @return null|Sabre\VObject\Component\VCalendar
*/
function dav_get_current_user_calendarobject(&$server, &$calendar, $calendarobject_uri, $with_privilege = "")
{
@ -319,7 +317,7 @@ function dav_get_current_user_calendarobject(&$server, &$calendar, $calendarobje
if (!$aclplugin->checkPrivileges($uri, $with_privilege, Sabre_DAVACL_Plugin::R_PARENT, false)) return null;
$data = $obj->get();
$vObject = Sabre_VObject_Reader::read($data);
$vObject = Sabre\VObject\Reader::read($data);
return $vObject;
}
@ -347,20 +345,19 @@ function dav_get_current_user_calendar_by_id(&$server, $id, $with_privilege = ""
/**
* @param string $uid
* @return Sabre_VObject_Component_VCalendar $vObject
* @return Sabre\VObject\Component\VCalendar $vObject
*/
function dav_create_empty_vevent($uid = "")
{
$a = get_app();
if ($uid == "") $uid = uniqid();
return Sabre_VObject_Reader::read("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Friendica//DAV-Plugin//EN\r\nBEGIN:VEVENT\r\nUID:" . $uid . "@" . $a->get_hostname() .
return Sabre\VObject\Reader::read("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//" . DAV_APPNAME . "//DAV-Plugin//EN\r\nBEGIN:VEVENT\r\nUID:" . $uid . "@" . dav_compat_get_hostname() .
"\r\nDTSTAMP:" . date("Ymd") . "T" . date("His") . "Z\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n");
}
/**
* @param Sabre_VObject_Component_VCalendar $vObject
* @return Sabre_VObject_Component_VEvent|null
* @param Sabre\VObject\Component\VCalendar $vObject
* @return Sabre\VObject\Component\VEvent|null
*/
function dav_get_eventComponent(&$vObject)
{

View file

@ -3,8 +3,8 @@
/**
* @param Sabre_VObject_Component_VAlarm $alarm
* @param Sabre_VObject_Component_VEvent|Sabre_VObject_Component_VTodo $parent
* @param Sabre\VObject\Component\VAlarm $alarm
* @param Sabre\VObject\Component\VEvent|Sabre\VObject\Component\VTodo $parent
* @return DateTime|null
* @throws Sabre_DAV_Exception
*/
@ -12,12 +12,12 @@ function renderCalDavEntry_calcalarm(&$alarm, &$parent)
{
$trigger = $alarm->__get("TRIGGER");
if (!isset($trigger['VALUE']) || strtoupper($trigger['VALUE']) === 'DURATION') {
$triggerDuration = Sabre_VObject_DateTimeParser::parseDuration($trigger->value);
$triggerDuration = Sabre\VObject\DateTimeParser::parseDuration($trigger->value);
$related = (isset($trigger['RELATED']) && strtoupper($trigger['RELATED']) == 'END') ? 'END' : 'START';
if ($related === 'START') {
/** @var Sabre_VObject_Property_DateTime $dtstart */
/** @var Sabre\VObject\Property\DateTime $dtstart */
$dtstart = $parent->__get("DTSTART");
$effectiveTrigger = $dtstart->getDateTime();
$effectiveTrigger->add($triggerDuration);
@ -28,14 +28,14 @@ function renderCalDavEntry_calcalarm(&$alarm, &$parent)
$endProp = 'DTEND';
}
/** @var Sabre_VObject_Property_DateTime $dtstart */
/** @var Sabre\VObject\Property\DateTime $dtstart */
$dtstart = $parent->__get("DTSTART");
if (isset($parent->$endProp)) {
$effectiveTrigger = clone $parent->$endProp->getDateTime();
$effectiveTrigger->add($triggerDuration);
} elseif ($parent->__get("DURATION") != "") {
$effectiveTrigger = clone $dtstart->getDateTime();
$duration = Sabre_VObject_DateTimeParser::parseDuration($parent->__get("DURATION"));
$duration = Sabre\VObject\DateTimeParser::parseDuration($parent->__get("DURATION"));
$effectiveTrigger->add($duration);
$effectiveTrigger->add($triggerDuration);
} else {
@ -58,10 +58,10 @@ function renderCalDavEntry_calcalarm(&$alarm, &$parent)
*/
function renderCalDavEntry_data(&$calendar, &$calendarobject)
{
/** @var Sabre_VObject_Component_VCalendar $vObject */
$vObject = Sabre_VObject_Reader::read($calendarobject["calendardata"]);
/** @var Sabre\VObject\Component\VCalendar $vObject */
$vObject = Sabre\VObject\Reader::read($calendarobject["calendardata"]);
$componentType = null;
/** @var Sabre_VObject_Component_VEvent $component */
/** @var Sabre\VObject\Component\VEvent $component */
$component = null;
foreach ($vObject->getComponents() as $component) {
if ($component->name !== 'VTIMEZONE') {
@ -86,18 +86,18 @@ function renderCalDavEntry_data(&$calendar, &$calendarobject)
);
$recurring = ($component->__get("RRULE") ? 1 : 0);
/** @var Sabre_VObject_Property_DateTime $dtstart */
/** @var Sabre\VObject\Property\DateTime $dtstart */
$dtstart = $component->__get("DTSTART");
$allday = ($dtstart->getDateType() == Sabre_VObject_Property_DateTime::DATE ? 1 : 0);
$allday = ($dtstart->getDateType() == Sabre\VObject\Property\DateTime::DATE ? 1 : 0);
/** @var array|Sabre_VObject_Component_VAlarm[] $alarms */
/** @var array|Sabre\VObject\Component\VAlarm[] $alarms */
$alarms = array();
foreach ($component->getComponents() as $a_component) if ($a_component->name == "VALARM") {
/** var Sabre_VObject_Component_VAlarm $component */
/** var Sabre\VObject\Component\VAlarm $component */
$alarms[] = $a_component;
}
$it = new Sabre_VObject_RecurrenceIterator($vObject, (string)$component->__get("UID"));
$it = new Sabre\VObject\RecurrenceIterator($vObject, (string)$component->__get("UID"));
$last_end = 0;
$max_ts = mktime(0, 0, 0, 1, 1, CALDAV_MAX_YEAR * 1);
$first = true;

View file

@ -81,22 +81,22 @@ abstract class Sabre_CalDAV_Backend_Common extends Sabre_CalDAV_Backend_Abstract
/**
* @static
* @param Sabre_VObject_Component_VEvent $component
* @param Sabre\VObject\Component\VEvent $component
* @return int
*/
public static function getDtEndTimeStamp(&$component)
{
/** @var Sabre_VObject_Property_DateTime $dtstart */
/** @var Sabre\VObject\Property\DateTime $dtstart */
$dtstart = $component->__get("DTSTART");
if ($component->__get("DTEND")) {
/** @var Sabre_VObject_Property_DateTime $dtend */
/** @var Sabre\VObject\Property\DateTime $dtend */
$dtend = $component->__get("DTEND");
return $dtend->getDateTime()->getTimeStamp();
} elseif ($component->__get("DURATION")) {
$endDate = clone $dtstart->getDateTime();
$endDate->add(Sabre_VObject_DateTimeParser::parse($component->__get("DURATION")->value));
$endDate->add(Sabre\VObject\DateTimeParser::parse($component->__get("DURATION")->value));
return $endDate->getTimeStamp();
} elseif ($dtstart->getDateType() === Sabre_VObject_Property_DateTime::DATE) {
} elseif ($dtstart->getDateType() === Sabre\VObject\Property\DateTime::DATE) {
$endDate = clone $dtstart->getDateTime();
$endDate->modify('+1 day');
return $endDate->getTimeStamp();
@ -124,8 +124,8 @@ abstract class Sabre_CalDAV_Backend_Common extends Sabre_CalDAV_Backend_Abstract
*/
protected function getDenormalizedData($calendarData)
{
/** @var Sabre_VObject_Component_VEvent $vObject */
$vObject = Sabre_VObject_Reader::read($calendarData);
/** @var Sabre\VObject\Component\VEvent $vObject */
$vObject = Sabre\VObject\Reader::read($calendarData);
$componentType = null;
$component = null;
$firstOccurence = null;
@ -141,15 +141,15 @@ abstract class Sabre_CalDAV_Backend_Common extends Sabre_CalDAV_Backend_Abstract
throw new Sabre_DAV_Exception_BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
}
if ($componentType === 'VEVENT') {
/** @var Sabre_VObject_Component_VEvent $component */
/** @var Sabre_VObject_Property_DateTime $dtstart */
/** @var Sabre\VObject\Component\VEvent $component */
/** @var Sabre\VObject\Property\DateTime $dtstart */
$dtstart = $component->__get("DTSTART");
$firstOccurence = $dtstart->getDateTime()->getTimeStamp();
// Finding the last occurence is a bit harder
if (!$component->__get("RRULE")) {
$lastOccurence = self::getDtEndTimeStamp($component);
} else {
$it = new Sabre_VObject_RecurrenceIterator($vObject, (string)$component->__get("UID"));
$it = new Sabre\VObject\RecurrenceIterator($vObject, (string)$component->__get("UID"));
$maxDate = new DateTime(CALDAV_MAX_YEAR . "-01-01");
if ($it->isInfinite()) {
$lastOccurence = $maxDate->getTimeStamp();

View file

@ -177,7 +177,7 @@ class Sabre_CalDAV_Backend_Private extends Sabre_CalDAV_Backend_Common
"principaluri" => $principalUri,
'{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $cal['ctag'] ? $cal['ctag'] : '0',
'{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components),
"calendar_class" => "Sabre_CalDAV_Calendar",
"calendar_class" => "Sabre_CalDAV_Calendar_Private",
);
foreach ($this->propertyMap as $key=> $field) $dat[$key] = $cal[$field];

View file

@ -0,0 +1,50 @@
<?php
class Sabre_CalDAV_Calendar_Private extends Sabre_CalDAV_Calendar
{
public function getACL()
{
return array(
array(
'privilege' => '{DAV:}read',
'principal' => $this->calendarInfo['principaluri'],
'protected' => true,
),
array(
'privilege' => '{DAV:}write',
'principal' => $this->calendarInfo['principaluri'],
'protected' => true,
),
/*
array(
'privilege' => '{DAV:}read',
'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write',
'protected' => true,
),
array(
'privilege' => '{DAV:}write',
'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write',
'protected' => true,
),
array(
'privilege' => '{DAV:}read',
'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read',
'protected' => true,
),
array(
'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}read-free-busy',
'principal' => '{DAV:}authenticated',
'protected' => true,
),
*/
);
}
}

View file

@ -0,0 +1,116 @@
<?php
abstract class Sabre_CardDAV_Backend_Common extends Sabre_CardDAV_Backend_Abstract
{
/**
* @abstract
* @return int
*/
abstract public function getNamespace();
/**
* @static
* @abstract
* @return string
*/
abstract public static function getBackendTypeName();
/**
* @var array
*/
static private $addressbookCache = array();
/**
* @var array
*/
static private $addressbookObjectCache = array();
/**
* @static
* @param int $addressbookId
* @return array
*/
static public function loadCalendarById($addressbookId)
{
if (!isset(self::$addressbookCache[$addressbookId])) {
$c = q("SELECT * FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId));
self::$addressbookCache[$addressbookId] = $c[0];
}
return self::$addressbookCache[$addressbookId];
}
/**
* @static
* @param int $obj_id
* @return array
*/
static public function loadAddressbookobjectById($obj_id)
{
if (!isset(self::$addressbookObjectCache[$obj_id])) {
$o = q("SELECT * FROM %s%saddressbookobjects WHERE `id` = %d",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($obj_id)
);
self::$addressbookObjectCache[$obj_id] = $o[0];
}
return self::$addressbookObjectCache[$obj_id];
}
/**
* Updates an addressbook's properties
*
* See Sabre_DAV_IProperties for a description of the mutations array, as
* well as the return value.
*
* @param mixed $addressBookId
* @param array $mutations
* @throws Sabre_DAV_Exception_Forbidden
* @see Sabre_DAV_IProperties::updateProperties
* @return bool|array
*/
public function updateAddressBook($addressBookId, array $mutations)
{
$updates = array();
foreach ($mutations as $property=> $newValue) {
switch ($property) {
case '{DAV:}displayname' :
$updates['displayname'] = $newValue;
break;
case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' :
$updates['description'] = $newValue;
break;
default :
// If any unsupported values were being updated, we must
// let the entire request fail.
return false;
}
}
// No values are being updated?
if (!$updates) {
return false;
}
$query = 'UPDATE ' . CALDAV_SQL_DB . CALDAV_SQL_PREFIX . 'addressbooks SET ctag = ctag + 1 ';
foreach ($updates as $key=> $value) {
$query .= ', `' . dbesc($key) . '` = ' . dbesc($key) . ' ';
}
$query .= ' WHERE id = ' . IntVal($addressBookId);
q($query);
return true;
}
/**
* @param int $addressbookId
*/
protected function increaseAddressbookCtag($addressbookId)
{
q("UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = '%d'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId));
self::$addressbookCache = array();
}
}

View file

@ -1,17 +1,6 @@
<?php
/**
* PDO CardDAV backend
*
* This CardDAV backend uses PDO to store addressbooks
*
* @package Sabre
* @subpackage CardDAV
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Common
{
/**
@ -39,6 +28,24 @@ class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
}
/**
* @return int
*/
public function getNamespace()
{
return CARDDAV_NAMESPACE_PRIVATE;
}
/**
* @static
* @return string
*/
public static function getBackendTypeName()
{
return t("Private Addressbooks");
}
/**
* Returns the list of addressbooks for a specific user.
*
@ -47,22 +54,19 @@ class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
*/
public function getAddressBooksForUser($principalUri)
{
$uid = dav_compat_principal2uid($principalUri);
$n = dav_compat_principal2namespace($principalUri);
if ($n["namespace"] != $this->getNamespace()) return array();
$addressBooks = array();
$books = q("SELECT id, uri, displayname, principaluri, description, ctag FROM %s%saddressbooks_phone WHERE principaluri = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($principalUri));
if (count($books) == 0) {
q("INSERT INTO %s%saddressbooks_phone (uid, principaluri, displayname, uri, description, ctag) VALUES (%d, '%s', '%s', '%s', '%s', 1)",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $uid, dbesc($principalUri), 'Other', 'phone', 'Manually added contacts'
);
$books = q("SELECT id, uri, displayname, principaluri, description, ctag FROM %s%saddressbooks_phone WHERE principaluri = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($principalUri));
}
$books = q("SELECT * FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($n["namespace"]), IntVal($n["namespace_id"]));
foreach ($books as $row) {
if (in_array($row["uri"], $GLOBALS["CARDDAV_PRIVATE_SYSTEM_ADDRESSBOOKS"])) continue;
$addressBooks[] = array(
'id' => CARDDAV_NAMESPACE_PHONECONTACTS . "-" . $row['id'],
'id' => $row['id'],
'uri' => $row['uri'],
'principaluri' => $row['principaluri'],
'principaluri' => $principalUri,
'{DAV:}displayname' => $row['displayname'],
'{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
'{http://calendarserver.org/ns/}getctag' => $row['ctag'],
@ -76,57 +80,6 @@ class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
}
/**
* Updates an addressbook's properties
*
* See Sabre_DAV_IProperties for a description of the mutations array, as
* well as the return value.
*
* @param mixed $addressBookId
* @param array $mutations
* @throws Sabre_DAV_Exception_Forbidden
* @see Sabre_DAV_IProperties::updateProperties
* @return bool|array
*/
public function updateAddressBook($addressBookId, array $mutations)
{
$x = explode("-", $addressBookId);
$updates = array();
foreach ($mutations as $property=> $newValue) {
switch ($property) {
case '{DAV:}displayname' :
$updates['displayname'] = $newValue;
break;
case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' :
$updates['description'] = $newValue;
break;
default :
// If any unsupported values were being updated, we must
// let the entire request fail.
return false;
}
}
// No values are being updated?
if (!$updates) {
return false;
}
$query = 'UPDATE ' . CALDAV_SQL_DB . CALDAV_SQL_PREFIX . 'addressbooks_phone SET ctag = ctag + 1 ';
foreach ($updates as $key=> $value) {
$query .= ', `' . dbesc($key) . '` = ' . dbesc($key) . ' ';
}
$query .= ' WHERE id = ' . IntVal($x[1]);
q($query);
return true;
}
/**
* Creates a new address book
*
@ -138,6 +91,8 @@ class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
*/
public function createAddressBook($principalUri, $url, array $properties)
{
$uid = dav_compat_principal2uid($principalUri);
$values = array(
'displayname' => null,
'description' => null,
@ -160,8 +115,8 @@ class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
}
q("INSERT INTO %s%saddressbooks_phone (uri, displayname, description, principaluri, ctag) VALUES ('%s', '%s', '%s', '%s', 1)",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($values["uri"]), dbesc($values["displayname"]), dbesc($values["description"]), dbesc($values["principaluri"])
q("INSERT INTO %s%saddressbooks (`uri`, `displayname`, `description`, `namespace`, `namespace_id`, `ctag`) VALUES ('%s', '%s', '%s', %d, %d, 1)",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($values["uri"]), dbesc($values["displayname"]), dbesc($values["description"]), CARDDAV_NAMESPACE_PRIVATE, IntVal($uid)
);
}
@ -174,9 +129,8 @@ class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
*/
public function deleteAddressBook($addressBookId)
{
$x = explode("-", $addressBookId);
q("DELETE FROM %s%scards WHERE namespace = %d AND namespace_id = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1]));
q("DELETE FROM %s%saddressbooks_phone WHERE id = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
q("DELETE FROM %s%saddressbookobjects WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId));
q("DELETE FROM %s%saddressbooks WHERE `addressbook_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId));
}
/**
@ -200,10 +154,8 @@ class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
*/
public function getCards($addressbookId)
{
$x = explode("-", $addressbookId);
$r = q('SELECT id, carddata, uri, lastmodified, etag, size, contact FROM %s%scards WHERE namespace = %d AND namespace_id = %d AND manually_deleted = 0',
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1])
$r = q('SELECT `id`, `carddata`, `uri`, `lastmodified`, `etag`, `size`, `contact` FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `manually_deleted` = 0',
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId)
);
if ($r) return $r;
return array();
@ -222,9 +174,8 @@ class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
*/
public function getCard($addressBookId, $cardUri)
{
$x = explode("-", $addressBookId);
$x = q("SELECT id, carddata, uri, lastmodified, etag, size FROM %s%scards WHERE namespace = %d AND namespace_id = %d AND uri = '%s'",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1]), dbesc($cardUri));
$x = q("SELECT `id`, `carddata`, `uri`, `lastmodified`, `etag`, `size` FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `uri` = '%s'",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId), dbesc($cardUri));
if (count($x) == 0) throw new Sabre_DAV_Exception_NotFound();
return $x[0];
}
@ -257,14 +208,12 @@ class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
*/
public function createCard($addressBookId, $cardUri, $cardData)
{
$x = explode("-", $addressBookId);
$etag = md5($cardData);
q("INSERT INTO %s%scards (carddata, uri, lastmodified, namespace, namespace_id, etag, size) VALUES ('%s', '%s', %d, %d, '%s', %d)",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), dbesc($cardUri), time(), IntVal($x[0]), IntVal($x[1]), $etag, strlen($cardData)
q("INSERT INTO %s%saddressbookobjects (`carddata`, `uri`, `lastmodified`, `addressbook_id`, `etag`, `size`) VALUES ('%s', '%s', NOW(), %d, '%s', %d)",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), dbesc($cardUri), IntVal($addressBookId), dbesc($etag), strlen($cardData)
);
q('UPDATE %s%saddressbooks_phone SET ctag = ctag + 1 WHERE id = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
q('UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId));
return '"' . $etag . '"';
@ -298,14 +247,12 @@ class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
*/
public function updateCard($addressBookId, $cardUri, $cardData)
{
$x = explode("-", $addressBookId);
$etag = md5($cardData);
q("UPDATE %s%scards SET carddata = '%s', lastmodified = %d, etag = '%s', size = %d, manually_edited = 1 WHERE uri = '%s' AND namespace = %d AND namespace_id =%d",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), time(), $etag, strlen($cardData), dbesc($cardUri), IntVal($x[10]), IntVal($x[1])
q("UPDATE %s%saddressbookobjects SET `carddata` = '%s', `lastmodified` = NOW(), `etag` = '%s', `size` = %d, `manually_edited` = 1 WHERE `uri` = '%s' AND `addressbook_id` = %d",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), dbesc($etag), strlen($cardData), dbesc($cardUri), IntVal($addressBookId)
);
q('UPDATE %s%saddressbooks_phone SET ctag = ctag + 1 WHERE id = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
q('UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId));
return '"' . $etag . '"';
}
@ -320,10 +267,8 @@ class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Abstract
*/
public function deleteCard($addressBookId, $cardUri)
{
$x = explode("-", $addressBookId);
q("DELETE FROM %s%scards WHERE namespace = %d AND namespace_id = %d AND uri = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1]), dbesc($cardUri));
q('UPDATE %s%saddressbooks_phone SET ctag = ctag + 1 WHERE id = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
q("DELETE FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId), dbesc($cardUri));
q('UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId));
return true;
}

View file

@ -0,0 +1,269 @@
<?php
abstract class Sabre_CardDAV_Backend_Virtual extends Sabre_CardDAV_Backend_Common
{
/**
* @static
* @abstract
* @param int $addressbookId
* @param string $uri
* @return array
*/
/*
abstract public function getItemsByUri($addressbookId, $uri);
*/
/**
* @static
* @param int $addressbookId
*/
static public function invalidateCache($addressbookId) {
q("UPDATE %s%saddressbooks SET `needs_rebuild` = 1 WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId));
}
/**
* @static
* @abstract
* @param int $addressbookId
* @param bool $force
*/
static abstract protected function createCache_internal($addressbookId, $force = false);
/**
* @param int $addressbookId
* @param null|array $addressbook
* @param bool $force
*/
public function createCache($addressbookId, $addressbook = null, $force = false) {
$addressbookId = IntVal($addressbookId);
if (!$addressbook) {
$add = q("SELECT `needs_rebuild`, `uri` FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId);
$addressbook = $add[0];
}
if ($addressbook["needs_rebuild"] == 1 || $force) {
static::createCache_internal($addressbookId, $force);
q("UPDATE %s%saddressbooks SET `needs_rebuild` = 0, `ctag` = `ctag` + 1 WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId);
}
}
/**
* @static
* @abstract
* @param int $addressbookId
* @param int $contactId
* @param bool $force
*/
static abstract protected function createCardCache($addressbookId, $contactId, $force = false);
/**
* @param int $addressbookId
* @return array
*/
public function getCards($addressbookId)
{
$addressbookId = IntVal($addressbookId);
$add = q("SELECT * FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId);
if ($add[0]["needs_rebuild"]) {
static::createCache_internal($addressbookId);
q("UPDATE %s%saddressbooks SET `needs_rebuild` = 0, `ctag` = `ctag` + 1 WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId);
$add[0]["needs_rebuild"] = 0;
$add[0]["ctag"]++;
}
$ret = array();
$x = q("SELECT * FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `manually_deleted` = 0", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId);
foreach ($x as $y) $ret[] = self::getCard($addressbookId, $add[0]["uri"], $add[0], $y);
return $ret;
}
/**
* Replaces the x-prop_name value. Replaces the prop_name value IF the old value is the same as the old value of x-prop_name (meaning: the user has not manually changed it)
*
* @param Sabre\VObject\Component $component
* @param string $prop_name
* @param string $prop_value
* @param array $parameters
* @return void
*/
static public function card_set_automatic_value(&$component, $prop_name, $prop_value, $parameters = array()) {
$automatic = $component->select("X-" . $prop_name);
$curr = $component->select($prop_name);
if (count($automatic) == 0) {
$prop = new Sabre\VObject\Property('X-' . $prop_name, $prop_value);
foreach ($parameters as $key=>$val) $prop->add($key, $val);
$component->children[] = $prop;
if (count($curr) == 0) {
$prop = new Sabre\VObject\Property($prop_name, $prop_value);
foreach ($parameters as $key=>$val) $prop->add($key, $val);
$component->children[] = $prop;
}
} else foreach ($automatic as $auto_prop) {
/** @var Sabre\VObject\Property $auto_prop */
/** @var Sabre\VObject\Property $actual_prop */
foreach ($curr as $actual_prop) {
if ($auto_prop->value == $actual_prop->value) $actual_prop->setValue($prop_value);
}
$auto_prop->setValue($prop_value);
}
}
/**
* Deletes the x-prop_name value. Deletes the prop_name value IF the old value is the same as the old value of x-prop_name (meaning: the user has not manually changed it)
*
* @param Sabre\VObject\Component $component
* @param string $prop_name
* @param array $parameters
*/
static public function card_del_automatic_value(&$component, $prop_name, $parameters = array()) {
// @TODO
}
/**
* @param int $addressbookId
* @param string $objectUri
* @param array $book
* @param array $obj
* @throws Sabre_DAV_Exception_NotFound
* @return array
*/
public function getCard($addressbookId, $objectUri, $book = null, $obj = null)
{
$addressbookId = IntVal($addressbookId);
if ($book == null) {
$add = q("SELECT `needs_rebuild`, `uri` FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId);
$book = $add[0];
}
if ($book["needs_rebuild"] == 1) {
static::createCache_internal($addressbookId);
q("UPDATE %s%saddressbooks SET `needs_rebuild` = 0, `ctag` = `ctag` + 1 WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId);
$add[0]["needs_rebuild"] = 0;
}
if ($obj == null) {
$r = q("SELECT * FROM %s%saddressbookobjects WHERE `uri` = '%s' AND `addressbook_id` = %d AND `manually_deleted` = 0",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($objectUri), IntVal($addressbookId));
if (count($r) == 0) throw new Sabre_DAV_Exception_NotFound();
$obj = $r[0];
if ($obj["needs_rebuild"] == 1) $obj = static::createCardCache($addressbookId, $obj["contact"]);
}
$ret = array(
"id" => IntVal($obj["uri"]),
"carddata" => $obj["carddata"],
"uri" => $obj["uri"],
"lastmodified" => $obj["lastmodified"],
"addressbookid" => $addressbookId,
"etag" => $obj["etag"],
"size" => IntVal($obj["size"]),
);
return $ret;
}
/**
* @param string $principalUri
* @param string $addressbookUri
* @param array $properties
* @throws Sabre_DAV_Exception_Forbidden
* @return void
*/
public function createAddressBook($principalUri, $addressbookUri, array $properties)
{
throw new Sabre_DAV_Exception_Forbidden();
}
/**
* @param string $addressbookId
* @throws Sabre_DAV_Exception_Forbidden
* @return void
*/
public function deleteAddressBook($addressbookId)
{
throw new Sabre_DAV_Exception_Forbidden();
}
/**
* @param string $addressbookId
* @param string $objectUri
* @param string $cardData
* @throws Sabre_DAV_Exception_Forbidden
* @return null|string|void
*/
function createCard($addressbookId, $objectUri, $cardData)
{
throw new Sabre_DAV_Exception_Forbidden();
}
/**
* Updates a card.
*
* The addressbook id will be passed as the first argument. This is the
* same id as it is returned from the getAddressbooksForUser method.
*
* The cardUri is a base uri, and doesn't include the full path. The
* cardData argument is the vcard body, and is passed as a string.
*
* It is possible to return an ETag from this method. This ETag should
* match that of the updated resource, and must be enclosed with double
* quotes (that is: the string itself must contain the actual quotes).
*
* You should only return the ETag if you store the carddata as-is. If a
* subsequent GET request on the same card does not have the same body,
* byte-by-byte and you did return an ETag here, clients tend to get
* confused.
*
* If you don't return an ETag, you can just return null.
*
* @param string $addressBookId
* @param string $cardUri
* @param string $cardData
* @throws Sabre_DAV_Exception_Forbidden
* @return string|null
*/
public function updateCard($addressBookId, $cardUri, $cardData)
{
echo "Die!"; die(); // @TODO
$x = explode("-", $addressBookId);
$etag = md5($cardData);
q("UPDATE %s%scards SET carddata = '%s', lastmodified = %d, etag = '%s', size = %d, manually_edited = 1 WHERE uri = '%s' AND namespace = %d AND namespace_id =%d",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), time(), $etag, strlen($cardData), dbesc($cardUri), IntVal($x[10]), IntVal($x[1])
);
q('UPDATE %s%saddressbooks_community SET ctag = ctag + 1 WHERE uid = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
return '"' . $etag . '"';
}
/**
* Deletes a card
*
* @param string $addressBookId
* @param string $cardUri
* @throws Sabre_DAV_Exception_Forbidden
* @return bool
*/
public function deleteCard($addressBookId, $cardUri)
{
q("UPDATE %s%scards SET `manually_deleted` = 1 WHERE `addressbook_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId), dbesc($cardUri));
q('UPDATE %s%saddressbooks SET ctag = ctag + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId));
return true;
}
}

View file

@ -169,7 +169,6 @@ class Sabre_CalDAV_AnimexxUserCalendars implements Sabre_DAV_IExtendedCollection
$objs[] = new $calendar["calendar_class"]($this->principalBackend, $backend, $calendar);
}
}
//$objs[] = new Sabre_CalDAV_AnimexxUserZirkelCalendars($this->principalBackend, $this->caldavBackend, $this->username);
return $objs;
}

View file

@ -97,12 +97,12 @@ function wdcal_print_feed($base_path = "")
$component = dav_get_eventComponent($item);
$component->add("SUMMARY", icalendar_sanitize_string(dav_compat_parse_text_serverside("CalendarTitle")));
if (isset($_REQUEST["allday"])) $type = Sabre_VObject_Property_DateTime::DATE;
else $type = Sabre_VObject_Property_DateTime::LOCALTZ;
if (isset($_REQUEST["allday"])) $type = Sabre\VObject\Property\DateTime::DATE;
else $type = Sabre\VObject\Property\DateTime::LOCALTZ;
$datetime_start = new Sabre_VObject_Property_DateTime("DTSTART");
$datetime_start = new Sabre\VObject\Property\DateTime("DTSTART");
$datetime_start->setDateTime(new DateTime(date("Y-m-d H:i:s", IntVal($_REQUEST["CalendarStartTime"]))), $type);
$datetime_end = new Sabre_VObject_Property_DateTime("DTEND");
$datetime_end = new Sabre\VObject\Property\DateTime("DTEND");
$datetime_end->setDateTime(new DateTime(date("Y-m-d H:i:s", IntVal($_REQUEST["CalendarEndTime"]))), $type);
$component->add($datetime_start);
@ -179,12 +179,12 @@ function wdcal_print_feed($base_path = "")
killme();
}
if (isset($_REQUEST["allday"])) $type = Sabre_VObject_Property_DateTime::DATE;
else $type = Sabre_VObject_Property_DateTime::LOCALTZ;
if (isset($_REQUEST["allday"])) $type = Sabre\VObject\Property\DateTime::DATE;
else $type = Sabre\VObject\Property\DateTime::LOCALTZ;
$datetime_start = new Sabre_VObject_Property_DateTime("DTSTART");
$datetime_start = new Sabre\VObject\Property\DateTime("DTSTART");
$datetime_start->setDateTime(new DateTime(date("Y-m-d H:i:s", IntVal($_REQUEST["CalendarStartTime"]))), $type);
$datetime_end = new Sabre_VObject_Property_DateTime("DTEND");
$datetime_end = new Sabre\VObject\Property\DateTime("DTEND");
$datetime_end->setDateTime(new DateTime(date("Y-m-d H:i:s", IntVal($_REQUEST["CalendarEndTime"]))), $type);
$component->__unset("DTSTART");

View file

@ -29,7 +29,7 @@ function wdcal_getEditPage_str(&$localization, $baseurl, $calendar_id, $uri)
if ($component == null) return t('Could not open component for editing');
/** @var Sabre_VObject_Property_DateTime $dtstart */
/** @var Sabre\VObject\Property\DateTime $dtstart */
$dtstart = $component->__get("DTSTART");
$event = array(
"id" => IntVal($uri),
@ -44,7 +44,7 @@ function wdcal_getEditPage_str(&$localization, $baseurl, $calendar_id, $uri)
$exdates = $component->select("EXDATE");
$recurrentce_exdates = array();
/** @var Sabre_VObject_Property_MultiDateTime $x */
/** @var Sabre\VObject\Property\MultiDateTime $x */
foreach ($exdates as $x) {
/** @var DateTime $y */
$z = $x->getDateTimes();
@ -511,15 +511,15 @@ function wdcal_set_component_date(&$component, &$localization)
if (isset($_REQUEST["allday"])) {
$ts_start = $localization->date_local2timestamp($_REQUEST["start_date"] . " 00:00");
$ts_end = $localization->date_local2timestamp($_REQUEST["end_date"] . " 00:00");
$type = Sabre_VObject_Property_DateTime::DATE;
$type = Sabre\VObject\Property\DateTime::DATE;
} else {
$ts_start = $localization->date_local2timestamp($_REQUEST["start_date"] . " " . $_REQUEST["start_time"]);
$ts_end = $localization->date_local2timestamp($_REQUEST["end_date"] . " " . $_REQUEST["end_time"]);
$type = Sabre_VObject_Property_DateTime::LOCALTZ;
$type = Sabre\VObject\Property\DateTime::LOCALTZ;
}
$datetime_start = new Sabre_VObject_Property_DateTime("DTSTART");
$datetime_start = new Sabre\VObject\Property\DateTime("DTSTART");
$datetime_start->setDateTime(new DateTime(date("Y-m-d H:i:s", $ts_start)), $type);
$datetime_end = new Sabre_VObject_Property_DateTime("DTEND");
$datetime_end = new Sabre\VObject\Property\DateTime("DTEND");
$datetime_end->setDateTime(new DateTime(date("Y-m-d H:i:s", $ts_end)), $type);
$component->__unset("DTSTART");
@ -539,7 +539,7 @@ function wdcal_set_component_date(&$component, &$localization)
function wdcal_set_component_recurrence_special(&$component, $str) {
$ret = "";
/** @var Sabre_VObject_Property_DateTime $start */
/** @var Sabre\VObject\Property\DateTime $start */
$start = $component->__get("DTSTART");
$dayMap = array(
0 => 'SU',
@ -595,8 +595,8 @@ function wdcal_set_component_recurrence(&$component, &$localization)
case "date":
$date = $localization->date_local2timestamp($_REQUEST["rec_until_date"]);
$part_until = ";UNTIL=" . date("Ymd", $date);
$datetime_until = new Sabre_VObject_Property_DateTime("UNTIL");
$datetime_until->setDateTime(new DateTime(date("Y-m-d H:i:s", $date)), Sabre_VObject_Property_DateTime::DATE);
$datetime_until = new Sabre\VObject\Property\DateTime("UNTIL");
$datetime_until->setDateTime(new DateTime(date("Y-m-d H:i:s", $date)), Sabre\VObject\Property\DateTime::DATE);
break;
case "count":
$part_until = ";COUNT=" . IntVal($_REQUEST["rec_until_count"]);
@ -626,7 +626,7 @@ function wdcal_set_component_recurrence(&$component, &$localization)
$part_freq .= wdcal_set_component_recurrence_special($component, $_REQUEST["rec_monthly_day"]);
break;
case "yearly":
/** @var Sabre_VObject_Property_DateTime $start */
/** @var Sabre\VObject\Property\DateTime $start */
$start = $component->__get("DTSTART");
$part_freq = "FREQ=YEARLY";
$part_freq .= ";BYMONTH=" . $start->getDateTime()->format("n");
@ -645,20 +645,20 @@ function wdcal_set_component_recurrence(&$component, &$localization)
foreach ($_REQUEST["rec_exceptions"] as $except) {
$arr[] = new DateTime(date("Y-m-d H:i:s", $except));
}
/** @var Sabre_VObject_Property_MultiDateTime $prop */
$prop = Sabre_VObject_Property::create("EXDATE");
/** @var Sabre\VObject\Property\MultiDateTime $prop */
$prop = Sabre\VObject\Property::create("EXDATE");
$prop->setDateTimes($arr);
$component->add($prop);
}
$rrule = $part_freq . $part_until;
$component->add(new Sabre_VObject_Property("RRULE", $rrule));
$component->add(new Sabre\VObject\Property("RRULE", $rrule));
}
/**
* @param Sabre_VObject_Component_VEvent $component
* @param Sabre\VObject\Component\VEvent $component
* @param wdcal_local $localization
* @param string $summary
* @param int $dtstart
@ -671,12 +671,12 @@ function wdcal_set_component_alerts(&$component, &$localization, $summary, $dtst
$component->__unset("VALARM");
foreach ($prev_alarms as $al) {
/** @var Sabre_VObject_Component_VAlarm $al */
/** @var Sabre\VObject\Component\VAlarm $al */
// @TODO Parse notifications that have been there before; e.g. from Lightning
}
foreach (array_keys($_REQUEST["noti_type"]) as $key) if (is_numeric($key) || ($key == "new" && $_REQUEST["new_alarm"] == 1)) {
$alarm = new Sabre_VObject_Component_VAlarm("VALARM");
$alarm = new Sabre\VObject\Component\VAlarm("VALARM");
switch ($_REQUEST["noti_type"][$key]) {
case "email":
@ -686,15 +686,15 @@ function wdcal_set_component_alerts(&$component, &$localization, $summary, $dtst
$localization->date_timestamp2local($dtstart), $summary,
), t("The event #name# will start at #date"));
$alarm->add(new Sabre_VObject_Property("ACTION", "EMAIL"));
$alarm->add(new Sabre_VObject_Property("SUMMARY", $summary));
$alarm->add(new Sabre_VObject_Property("DESCRIPTION", $mailtext));
$alarm->add(new Sabre_VObject_Property("ATTENDEE", "MAILTO:" . $a->user["email"]));
$alarm->add(new Sabre\VObject\Property("ACTION", "EMAIL"));
$alarm->add(new Sabre\VObject\Property("SUMMARY", $summary));
$alarm->add(new Sabre\VObject\Property("DESCRIPTION", $mailtext));
$alarm->add(new Sabre\VObject\Property("ATTENDEE", "MAILTO:" . $a->user["email"]));
break;
case "display":
$alarm->add(new Sabre_VObject_Property("ACTION", "DISPLAY"));
$alarm->add(new Sabre\VObject\Property("ACTION", "DISPLAY"));
$text = str_replace("#name#", $summary, t("#name# is about to begin."));
$alarm->add(new Sabre_VObject_Property("DESCRIPTION", $text));
$alarm->add(new Sabre\VObject\Property("DESCRIPTION", $text));
break;
default:
continue;
@ -706,7 +706,7 @@ function wdcal_set_component_alerts(&$component, &$localization, $summary, $dtst
$trigger_val .= "-P";
if (in_array($_REQUEST["noti_unit"][$key], array("H", "M", "S"))) $trigger_val .= "T";
$trigger_val .= IntVal($_REQUEST["noti_value"][$key]) . $_REQUEST["noti_unit"][$key];
$alarm->add(new Sabre_VObject_Property($trigger_name, $trigger_val));
$alarm->add(new Sabre\VObject\Property($trigger_name, $trigger_val));
$component->add($alarm);
}
@ -785,12 +785,12 @@ function wdcal_getEditPage_exception_selector()
foreach ($vObject->getComponents() as $component) {
if ($component->name !== 'VTIMEZONE') break;
}
/** @var Sabre_VObject_Component_VEvent $component */
/** @var Sabre\VObject\Component\VEvent $component */
wdcal_set_component_date($component, $localization);
wdcal_set_component_recurrence($component, $localization);
$it = new Sabre_VObject_RecurrenceIterator($vObject, (string)$component->__get("UID"));
$it = new Sabre\VObject\RecurrenceIterator($vObject, (string)$component->__get("UID"));
$max_ts = mktime(0, 0, 0, 1, 1, CALDAV_MAX_YEAR + 1);
$last_start = 0;

View file

@ -2,11 +2,11 @@
/**
* Name: Calendar with CalDAV Support
* Description: A web-based calendar system with CalDAV-support. Also brings your Friendica-Contacts to your CardDAV-capable mobile phone. Requires PHP >= 5.3.
* Version: 0.2.0
* Version: 0.3.0
* Author: Tobias Hößl <https://github.com/CatoTH/>
*/
$_v = explode(".", phpversion());
if ($_v[0] > 5 || ($_v[0] == 5 && $_v[1] >= 3)) {
require(__DIR__ . "/main.php");
require(__DIR__ . "/friendica/main.php");
}

View file

@ -1,336 +0,0 @@
<?php
class Sabre_CardDAV_Backend_FriendicaCommunity extends Sabre_CardDAV_Backend_Abstract
{
/**
* @var null|Sabre_CardDAV_Backend_FriendicaCommunity
*/
private static $instance = null;
/**
* @static
* @return Sabre_CardDAV_Backend_FriendicaCommunity
*/
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new Sabre_CardDAV_Backend_FriendicaCommunity();
}
return self::$instance;
}
/**
* Sets up the object
*/
public function __construct()
{
}
/**
* Returns the list of addressbooks for a specific user.
*
* @param string $principalUri
* @return array
*/
public function getAddressBooksForUser($principalUri)
{
$uid = dav_compat_principal2uid($principalUri);
$addressBooks = array();
$books = q("SELECT ctag FROM %s%saddressbooks_community WHERE uid = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($uid));
if (count($books) == 0) {
q("INSERT INTO %s%saddressbooks_community (uid, ctag) VALUES (%d, 1)", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($uid));
$ctag = 1;
} else {
$ctag = $books[0]["ctag"];
}
$addressBooks[] = array(
'id' => CARDDAV_NAMESPACE_COMMUNITYCONTACTS . "-" . $uid,
'uri' => "friendica",
'principaluri' => $principalUri,
'{DAV:}displayname' => t("Friendica-Contacts"),
'{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => t("Your Friendica-Contacts"),
'{http://calendarserver.org/ns/}getctag' => $ctag,
'{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' =>
new Sabre_CardDAV_Property_SupportedAddressData(),
);
return $addressBooks;
}
/**
* Updates an addressbook's properties
*
* See Sabre_DAV_IProperties for a description of the mutations array, as
* well as the return value.
*
* @param string $addressBookId
* @param array $mutations
* @throws Sabre_DAV_Exception_Forbidden
* @see Sabre_DAV_IProperties::updateProperties
* @return bool|array
*/
public function updateAddressBook($addressBookId, array $mutations)
{
throw new Sabre_DAV_Exception_Forbidden();
}
/**
* Creates a new address book
*
* @param string $principalUri
* @param string $url Just the 'basename' of the url.
* @param array $properties
* @throws Sabre_DAV_Exception_Forbidden
* @return void
*/
public function createAddressBook($principalUri, $url, array $properties)
{
throw new Sabre_DAV_Exception_Forbidden();
}
/**
* Deletes an entire addressbook and all its contents
*
* @param int $addressBookId
* @throws Sabre_DAV_Exception_Forbidden
* @return void
*/
public function deleteAddressBook($addressBookId)
{
throw new Sabre_DAV_Exception_Forbidden();
}
/**
* @param array $contact
* @return array
*/
private function dav_contactarr2vcardsource($contact)
{
$name = explode(" ", $contact["name"]);
$first_name = $last_name = "";
$middle_name = array();
$num = count($name);
for ($i = 0; $i < $num && $first_name == ""; $i++) if ($name[$i] != "") {
$first_name = $name[$i];
unset($name[$i]);
}
for ($i = $num - 1; $i >= 0 && $last_name == ""; $i--) if (isset($name[$i]) && $name[$i] != "") {
$last_name = $name[$i];
unset($name[$i]);
}
foreach ($name as $n) if ($n != "") $middle_name[] = $n;
$vcarddata = new vcard_source_data($first_name, implode(" ", $middle_name), $last_name);
$vcarddata->homepages[] = new vcard_source_data_homepage("pref", $contact["url"]);
$vcarddata->last_update = ($contact["last-update"] > 0 ? $contact["last-update"] : $contact["created"]);
$photo = q("SELECT * FROM photo WHERE `contact-id` = %d ORDER BY scale DESC", $contact["id"]); //prefer size 80x80
if ($photo && count($photo) > 0) {
$photodata = new vcard_source_data_photo();
$photodata->width = $photo[0]["width"];
$photodata->height = $photo[0]["height"];
$photodata->type = "JPEG";
$photodata->binarydata = $photo[0]["data"];
$vcarddata->photo = $photodata;
}
switch ($contact["network"]) {
case "face":
$vcarddata->socialnetworks[] = new vcard_source_data_socialnetwork("facebook", $contact["notify"], "http://www.facebook.com/" . $contact["notify"]);
break;
case "dfrn":
$vcarddata->socialnetworks[] = new vcard_source_data_socialnetwork("dfrn", $contact["nick"], $contact["url"]);
break;
case "twitter":
$vcarddata->socialnetworks[] = new vcard_source_data_socialnetwork("twitter", $contact["nick"], "http://twitter.com/" . $contact["nick"]); // @TODO Stimmt das?
break;
}
$vcard = vcard_source_compile($vcarddata);
return array(
"id" => $contact["id"],
"carddata" => $vcard,
"uri" => $contact["id"] . ".vcf",
"lastmodified" => wdcal_mySql2PhpTime($vcarddata->last_update),
"etag" => md5($vcard),
"size" => strlen($vcard),
);
}
/**
* @param int $uid
* @param array|int[] $exclude_ids
* @return array
*/
private function dav_getCommunityContactsVCards($uid = 0, $exclude_ids = array())
{
$notin = (count($exclude_ids) > 0 ? " AND id NOT IN (" . implode(", ", $exclude_ids) . ") " : "");
$uid = IntVal($uid);
$contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0 $notin ORDER BY `name` ASC", $uid);
$retdata = array();
foreach ($contacts as $contact) {
$x = $this->dav_contactarr2vcardsource($contact);
$x["contact"] = $contact["id"];
$retdata[] = $x;
}
return $retdata;
}
/**
* Returns all cards for a specific addressbook id.
*
* This method should return the following properties for each card:
* * carddata - raw vcard data
* * uri - Some unique url
* * lastmodified - A unix timestamp
*
* It's recommended to also return the following properties:
* * etag - A unique etag. This must change every time the card changes.
* * size - The size of the card in bytes.
*
* If these last two properties are provided, less time will be spent
* calculating them. If they are specified, you can also ommit carddata.
* This may speed up certain requests, especially with large cards.
*
* @param string $addressbookId
* @return array
*/
public function getCards($addressbookId)
{
$add = explode("-", $addressbookId);
$indb = q('SELECT id, carddata, uri, lastmodified, etag, size, contact, manually_deleted FROM %s%scards WHERE namespace = %d AND namespace_id = %d',
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($add[0]), IntVal($add[1])
);
$found_contacts = array();
$contacts = array();
foreach ($indb as $x) {
if ($x["manually_deleted"] == 0) $contacts[] = $x;
$found_contacts[] = IntVal($x["contact"]);
}
$new_found = $this->dav_getCommunityContactsVCards($add[1], $found_contacts);
foreach ($new_found as $new) {
q("INSERT INTO %s%scards (namespace, namespace_id, contact, carddata, uri, lastmodified, manually_edited, manually_deleted, etag, size)
VALUES (%d, %d, %d, '%s', '%s', %d, 0, 0, '%s', %d)", CALDAV_SQL_DB, CALDAV_SQL_PREFIX,
IntVal($add[0]), IntVal($add[1]), IntVal($new["contact"]), dbesc($new["carddata"]), dbesc($new["uri"]), time(), md5($new["carddata"]), strlen($new["carddata"])
);
}
return array_merge($contacts, $new_found);
}
/**
* Returns a specfic card.
*
* The same set of properties must be returned as with getCards. The only
* exception is that 'carddata' is absolutely required.
*
* @param mixed $addressBookId
* @param string $cardUri
* @throws Sabre_DAV_Exception_NotFound
* @return array
*/
public function getCard($addressBookId, $cardUri)
{
$x = explode("-", $addressBookId);
$x = q("SELECT id, carddata, uri, lastmodified, etag, size FROM %s%scards WHERE namespace = %d AND namespace_id = %d AND uri = '%s'",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1]), dbesc($cardUri));
if (count($x) == 0) throw new Sabre_DAV_Exception_NotFound();
return $x[0];
}
/**
* Creates a new card.
*
* The addressbook id will be passed as the first argument. This is the
* same id as it is returned from the getAddressbooksForUser method.
*
* The cardUri is a base uri, and doesn't include the full path. The
* cardData argument is the vcard body, and is passed as a string.
*
* It is possible to return an ETag from this method. This ETag is for the
* newly created resource, and must be enclosed with double quotes (that
* is, the string itself must contain the double quotes).
*
* You should only return the ETag if you store the carddata as-is. If a
* subsequent GET request on the same card does not have the same body,
* byte-by-byte and you did return an ETag here, clients tend to get
* confused.
*
* If you don't return an ETag, you can just return null.
*
* @param string $addressBookId
* @param string $cardUri
* @param string $cardData
* @throws Sabre_DAV_Exception_Forbidden
* @return string
*/
public function createCard($addressBookId, $cardUri, $cardData)
{
throw new Sabre_DAV_Exception_Forbidden();
}
/**
* Updates a card.
*
* The addressbook id will be passed as the first argument. This is the
* same id as it is returned from the getAddressbooksForUser method.
*
* The cardUri is a base uri, and doesn't include the full path. The
* cardData argument is the vcard body, and is passed as a string.
*
* It is possible to return an ETag from this method. This ETag should
* match that of the updated resource, and must be enclosed with double
* quotes (that is: the string itself must contain the actual quotes).
*
* You should only return the ETag if you store the carddata as-is. If a
* subsequent GET request on the same card does not have the same body,
* byte-by-byte and you did return an ETag here, clients tend to get
* confused.
*
* If you don't return an ETag, you can just return null.
*
* @param string $addressBookId
* @param string $cardUri
* @param string $cardData
* @throws Sabre_DAV_Exception_Forbidden
* @return string|null
*/
public function updateCard($addressBookId, $cardUri, $cardData)
{
$x = explode("-", $addressBookId);
$etag = md5($cardData);
q("UPDATE %s%scards SET carddata = '%s', lastmodified = %d, etag = '%s', size = %d, manually_edited = 1 WHERE uri = '%s' AND namespace = %d AND namespace_id =%d",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), time(), $etag, strlen($cardData), dbesc($cardUri), IntVal($x[10]), IntVal($x[1])
);
q('UPDATE %s%saddressbooks_community SET ctag = ctag + 1 WHERE uid = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
return '"' . $etag . '"';
}
/**
* Deletes a card
*
* @param string $addressBookId
* @param string $cardUri
* @throws Sabre_DAV_Exception_Forbidden
* @return bool
*/
public function deleteCard($addressBookId, $cardUri)
{
$x = explode("-", $addressBookId);
q("UPDATE %s%scards SET manually_deleted = 1 WHERE namespace = %d AND namespace_id = %d AND uri = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1]), dbesc($cardUri));
q('UPDATE %s%saddressbooks_community SET ctag = ctag + 1 WHERE uid = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
return true;
}
}

View file

@ -10,16 +10,21 @@ if (isset($uri["path"]) && strlen($uri["path"]) > 1) {
define("CALDAV_SQL_DB", "");
define("CALDAV_SQL_PREFIX", "dav_");
define("CALDAV_URL_PREFIX", $path . "dav/");
define("DAV_APPNAME", "Friendica");
define("CALDAV_NAMESPACE_PRIVATE", 1);
define("CALDAV_FRIENDICA_MINE", "friendica-mine");
define("CALDAV_FRIENDICA_CONTACTS", "friendica-contacts");
$GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"] = array(CALDAV_FRIENDICA_MINE, CALDAV_FRIENDICA_CONTACTS);
$GLOBALS["CALDAV_PRIVATE_SYSTEM_BACKENDS"] = array("Sabre_CalDAV_Backend_Friendica");
define("CARDDAV_NAMESPACE_COMMUNITYCONTACTS", 1);
define("CARDDAV_NAMESPACE_PHONECONTACTS", 2);
define("CARDDAV_NAMESPACE_PRIVATE", 1);
define("CARDDAV_FRIENDICA_CONTACT", "friendica");
$GLOBALS["CARDDAV_PRIVATE_SYSTEM_ADDRESSBOOKS"] = array(CARDDAV_FRIENDICA_CONTACT);
$GLOBALS["CARDDAV_PRIVATE_SYSTEM_BACKENDS"] = array("Sabre_CardDAV_Backend_Friendica");
$GLOBALS["CALDAV_ACL_PLUGIN_CLASS"] = "Sabre_DAVACL_Plugin_Friendica";
define("CALDAV_MAX_YEAR", date("Y") + 5);
@ -151,6 +156,14 @@ function dav_compat_get_max_private_calendars()
return null;
}
/**
* @return string
*/
function dav_compat_get_hostname() {
$a = get_app();
return $a->get_hostname();
}
/**
* @param int $namespace
* @param int $namespace_id
@ -218,3 +231,44 @@ function wdcal_create_std_calendars()
$stms = wdcal_create_std_calendars_get_statements($a->user["uid"]);
foreach ($stms as $stmt) q($stmt);
}
/**
* @param int $user_id
* @param bool $withcheck
* @return array
*/
function wdcal_create_std_addressbooks_get_statements($user_id, $withcheck = true)
{
$stms = array();
$a = get_app();
$uris = array(
'private' => t("Private Addresses"),
CARDDAV_FRIENDICA_CONTACT => t("Friendica Contacts"),
);
foreach ($uris as $uri => $name) {
$cals = q("SELECT * FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, IntVal($user_id), dbesc($uri));
if (count($cals) == 0 || !$withcheck) $stms[] =
sprintf("INSERT INTO %s%saddressbooks (`namespace`, `namespace_id`, `displayname`, `ctag`, `uri`)
VALUES (%d, %d, '%s', 1, '%s')",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CARDDAV_NAMESPACE_PRIVATE, IntVal($user_id), dbesc($name), dbesc($uri));
}
return $stms;
}
/**
*/
function wdcal_create_std_addressbooks()
{
$a = get_app();
if (!local_user()) return;
$privates = q("SELECT COUNT(*) num FROM %s%addressbooks WHERE `namespace` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CARDDAV_NAMESPACE_PRIVATE, IntVal($a->user["uid"]));
if ($privates[0]["num"] > 0) return;
$stms = wdcal_create_std_addressbooks_get_statements($a->user["uid"]);
foreach ($stms as $stmt) q($stmt);
}

View file

@ -43,6 +43,36 @@ function dav_get_update_statements($from_version)
}
if (in_array($from_version, array(1, 2))) {
$stms[] = "CREATE TABLE IF NOT EXISTS `dav_addressbooks` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`namespace` mediumint(9) NOT NULL,
`namespace_id` int(11) unsigned NOT NULL,
`displayname` varchar(200) NOT NULL,
`description` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`needs_rebuild` TINYINT NOT NULL DEFAULT '1',
`uri` varchar(50) NOT NULL,
`ctag` int(11) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
$stms[] = "CREATE TABLE IF NOT EXISTS `dav_addressbookobjects` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`addressbook_id` int(11) unsigned NOT NULL,
`contact` int(11) DEFAULT NULL,
`carddata` mediumtext CHARACTER SET utf8 COLLATE utf8_unicode_ci,
`uri` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`lastmodified` timestamp NULL DEFAULT NULL,
`needs_rebuild` tinyint(4) NOT NULL DEFAULT '0',
`manually_deleted` tinyint(4) NOT NULL DEFAULT '0',
`etag` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`size` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `namespace` (`addressbook_id`,`contact`),
KEY `contact` (`contact`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
}
return $stms;
}
@ -54,24 +84,6 @@ function dav_get_create_statements($except = array())
{
$arr = array();
if (!in_array("dav_addressbooks_community", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_addressbooks_community` (
`uid` int(11) NOT NULL,
`ctag` int(11) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
if (!in_array("dav_addressbooks_phone", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_addressbooks_phone` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL,
`principaluri` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`displayname` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`uri` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`description` text CHARACTER SET utf8 COLLATE utf8_unicode_ci,
`ctag` int(11) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
UNIQUE KEY `principaluri` (`principaluri`,`uri`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
if (!in_array("dav_caldav_log", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_caldav_log` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uid` mediumint(9) NOT NULL,
@ -82,7 +94,7 @@ function dav_get_create_statements($except = array())
`url` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
KEY `mitglied` (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
if (!in_array("dav_calendarobjects", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_calendarobjects` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
@ -98,7 +110,7 @@ function dav_get_create_statements($except = array())
PRIMARY KEY (`id`),
UNIQUE KEY `uri` (`uri`),
KEY `calendar_id` (`calendar_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
if (!in_array("dav_calendars", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_calendars` (
`id` int(11) NOT NULL AUTO_INCREMENT,
@ -116,7 +128,7 @@ function dav_get_create_statements($except = array())
PRIMARY KEY (`id`),
UNIQUE KEY (`namespace` , `namespace_id` , `uri`),
KEY `uri` (`uri`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
if (!in_array("dav_cal_virtual_object_cache", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_cal_virtual_object_cache` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
@ -135,7 +147,7 @@ function dav_get_create_statements($except = array())
PRIMARY KEY (`id`),
KEY `data_uri` (`data_uri`),
KEY `ref_type` (`calendar_id`,`data_end`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
if (!in_array("dav_cal_virtual_object_sync", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_cal_virtual_object_sync` (
`calendar_id` int(10) unsigned NOT NULL,
@ -143,23 +155,6 @@ function dav_get_create_statements($except = array())
PRIMARY KEY (`calendar_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
if (!in_array("dav_cards", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_cards` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`namespace` tinyint(3) unsigned NOT NULL,
`namespace_id` int(11) unsigned NOT NULL,
`contact` int(11) DEFAULT NULL,
`carddata` mediumtext CHARACTER SET utf8 COLLATE utf8_unicode_ci,
`uri` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`lastmodified` int(11) unsigned DEFAULT NULL,
`manually_edited` tinyint(4) NOT NULL DEFAULT '0',
`manually_deleted` tinyint(4) NOT NULL DEFAULT '0',
`etag` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`size` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `namespace` (`namespace`,`namespace_id`,`contact`),
KEY `contact` (`contact`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
if (!in_array("dav_jqcalendar", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_jqcalendar` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`ical_recurr_uri` varchar(100) DEFAULT NULL,
@ -190,6 +185,34 @@ function dav_get_create_statements($except = array())
KEY `calendar_id` (`calendar_id`,`calendarobject_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8";
if (!in_array("dav_addressbooks", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_addressbooks` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`namespace` mediumint(9) NOT NULL,
`namespace_id` int(11) unsigned NOT NULL,
`displayname` varchar(200) NOT NULL,
`description` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`needs_rebuild` TINYINT NOT NULL DEFAULT '1',
`uri` varchar(50) NOT NULL,
`ctag` int(11) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
if (!in_array("dav_addressbookobjects", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_addressbookobjects` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`addressbook_id` int(11) unsigned NOT NULL,
`contact` int(11) DEFAULT NULL,
`carddata` mediumtext CHARACTER SET utf8 COLLATE utf8_unicode_ci,
`uri` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`lastmodified` timestamp NULL DEFAULT NULL,
`needs_rebuild` tinyint(4) NOT NULL DEFAULT '0',
`manually_deleted` tinyint(4) NOT NULL DEFAULT '0',
`etag` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`size` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `namespace` (`addressbook_id`,`contact`),
KEY `contact` (`contact`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
return $arr;
}
@ -201,7 +224,12 @@ function dav_check_tables()
$x = q("DESCRIBE %s%scalendars", CALDAV_SQL_DB, CALDAV_SQL_PREFIX);
if (!$x) return -1;
if (count($x) == 9) return 1; // Version 0.1
$x2 = q("show tables like '%s%saddressbooks'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX);
if (!$x2 || count($x2) == 0) return 2; // Version 0.2
if (count($x) == 12) return 0; // Correct
return -2; // Unknown version
}
@ -215,7 +243,7 @@ function dav_create_tables()
$errors = array();
global $db;
foreach ($stms as $st) {
foreach ($stms as $st) { // @TODO Friendica-dependent
$db->q($st);
if ($db->error) $errors[] = $db->error;
}
@ -229,16 +257,15 @@ function dav_create_tables()
function dav_upgrade_tables()
{
$ver = dav_check_tables();
if (!in_array($ver, array(1) )) return array("Unknown error");
if (!in_array($ver, array(1, 2))) return array("Unknown error");
$stms = dav_get_update_statements($ver);
$errors = array();
$errors = array();
global $db;
foreach ($stms as $st) {
foreach ($stms as $st) { // @TODO Friendica-dependent
$db->q($st);
if ($db->error) $errors[] = $db->error;
}
return $errors;
}
}

View file

@ -33,7 +33,7 @@ class Sabre_CalDAV_Backend_Friendica extends Sabre_CalDAV_Backend_Virtual
* @return string
*/
public static function getBackendTypeName() {
return t("Friendicy-Native events");
return t("Friendica-Native events");
}
/**
@ -82,11 +82,11 @@ class Sabre_CalDAV_Backend_Friendica extends Sabre_CalDAV_Backend_Virtual
$ts_end = wdcal_mySql2PhpTime($start);
$allday = (strpos($start, "00:00:00") !== false && strpos($finish, "00:00:00") !== false);
$type = ($allday ? Sabre_VObject_Property_DateTime::DATE : Sabre_VObject_Property_DateTime::LOCALTZ);
$type = ($allday ? Sabre\VObject\Property\DateTime::DATE : Sabre\VObject\Property\DateTime::LOCALTZ);
$datetime_start = new Sabre_VObject_Property_DateTime("DTSTART");
$datetime_start = new Sabre\VObject\Property\DateTime("DTSTART");
$datetime_start->setDateTime(new DateTime(date("Y-m-d H:i:s", $ts_start)), $type);
$datetime_end = new Sabre_VObject_Property_DateTime("DTEND");
$datetime_end = new Sabre\VObject\Property\DateTime("DTEND");
$datetime_end->setDateTime(new DateTime(date("Y-m-d H:i:s", $ts_end)), $type);
$component->add($datetime_start);

View file

@ -0,0 +1,227 @@
<?php
class Sabre_CardDAV_Backend_Friendica extends Sabre_CardDAV_Backend_Virtual
{
/**
* @var null|Sabre_CardDAV_Backend_Friendica
*/
private static $instance = null;
/**
* @static
* @return Sabre_CardDAV_Backend_Friendica
*/
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new Sabre_CardDAV_Backend_Friendica();
}
return self::$instance;
}
/**
* @return int
*/
public function getNamespace()
{
return CARDDAV_NAMESPACE_PRIVATE;
}
/**
* @static
* @return string
*/
public static function getBackendTypeName() {
return t("Friendica-Contacts");
}
/**
* Returns the list of addressbooks for a specific user.
*
* @param string $principalUri
* @return array
*/
public function getAddressBooksForUser($principalUri)
{
$uid = dav_compat_principal2uid($principalUri);
$addressBooks = array();
$books = q("SELECT id, ctag FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CARDDAV_NAMESPACE_PRIVATE, IntVal($uid), dbesc(CARDDAV_FRIENDICA_CONTACT));
$ctag = $books[0]["ctag"];
$addressBooks[] = array(
'id' => $books[0]["id"],
'uri' => "friendica",
'principaluri' => $principalUri,
'{DAV:}displayname' => t("Friendica-Contacts"),
'{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => t("Your Friendica-Contacts"),
'{http://calendarserver.org/ns/}getctag' => $ctag,
'{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' =>
new Sabre_CardDAV_Property_SupportedAddressData(),
);
return $addressBooks;
}
/**
* @static
* @param array $contact
* @return array
*/
private static function dav_contactarr2vcardsource($contact)
{
$name = explode(" ", $contact["name"]);
$first_name = $last_name = "";
$middle_name = array();
$num = count($name);
for ($i = 0; $i < $num && $first_name == ""; $i++) if ($name[$i] != "") {
$first_name = $name[$i];
unset($name[$i]);
}
for ($i = $num - 1; $i >= 0 && $last_name == ""; $i--) if (isset($name[$i]) && $name[$i] != "") {
$last_name = $name[$i];
unset($name[$i]);
}
foreach ($name as $n) if ($n != "") $middle_name[] = $n;
$vcarddata = new vcard_source_data($first_name, implode(" ", $middle_name), $last_name);
$vcarddata->homepages[] = new vcard_source_data_homepage("pref", $contact["url"]);
$vcarddata->last_update = ($contact["last-update"] > 0 ? $contact["last-update"] : $contact["created"]);
$photo = q("SELECT * FROM photo WHERE `contact-id` = %d ORDER BY scale DESC", $contact["id"]); //prefer size 80x80
if ($photo && count($photo) > 0) {
$photodata = new vcard_source_data_photo();
$photodata->width = $photo[0]["width"];
$photodata->height = $photo[0]["height"];
$photodata->type = "JPEG";
$photodata->binarydata = $photo[0]["data"];
$vcarddata->photo = $photodata;
}
switch ($contact["network"]) {
case "face":
$vcarddata->socialnetworks[] = new vcard_source_data_socialnetwork("facebook", $contact["notify"], "http://www.facebook.com/" . $contact["notify"]);
break;
case "dfrn":
$vcarddata->socialnetworks[] = new vcard_source_data_socialnetwork("dfrn", $contact["nick"], $contact["url"]);
break;
case "twitter":
$vcarddata->socialnetworks[] = new vcard_source_data_socialnetwork("twitter", $contact["nick"], "http://twitter.com/" . $contact["nick"]); // @TODO Stimmt das?
break;
}
$vcard = vcard_source_compile($vcarddata);
return array(
"id" => $contact["id"],
"carddata" => $vcard,
"uri" => $contact["id"] . ".vcf",
"lastmodified" => wdcal_mySql2PhpTime($vcarddata->last_update),
"etag" => md5($vcard),
"size" => strlen($vcard),
);
}
/**
* @static
* @param int $addressbookId
* @param bool $force
* @throws Sabre_DAV_Exception_NotFound
*/
static protected function createCache_internal($addressbookId, $force = false) {
//$notin = (count($exclude_ids) > 0 ? " AND id NOT IN (" . implode(", ", $exclude_ids) . ") " : "");
$addressbook = q("SELECT * FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId));
if (count($addressbook) != 1 || $addressbook[0]["namespace"] != CARDDAV_NAMESPACE_PRIVATE) throw new Sabre_DAV_Exception_NotFound();
$contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0 ORDER BY `name` ASC", $addressbook[0]["namespace_id"]);
foreach ($contacts as $contact) {
$x = static::dav_contactarr2vcardsource($contact);
q("INSERT INTO %s%saddressbookobjects (`addressbook_id`, `contact`, `carddata`, `uri`, `lastmodified`, `etag`, `size`) VALUES (%d, %d, '%s', '%s', NOW(), '%s', %d)",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId, $contact["id"], dbesc($x["carddata"]), dbesc($x["uri"]), dbesc($x["etag"]), $x["size"]
);
}
}
/**
* @static
* @param int $addressbookId
* @param int $contactId
* @param bool $force
* @throws Sabre_DAV_Exception_NotFound
*/
static protected function createCardCache($addressbookId, $contactId, $force = false)
{
$addressbook = q("SELECT * FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId));
if (count($addressbook) != 1 || $addressbook[0]["namespace"] != CARDDAV_NAMESPACE_PRIVATE) throw new Sabre_DAV_Exception_NotFound();
$contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0 AND `id` = %d ORDER BY `name` ASC",
$addressbook[0]["namespace_id"], IntVal($contactId));
$contact = $contacts[0];
$x = static::dav_contactarr2vcardsource($contact);
q("INSERT INTO %s%saddressbookobjects (`addressbook_id`, `contact`, `carddata`, `uri`, `lastmodified`, `etag`, `size`) VALUES (%d, %d, '%s', '%s', NOW(), '%s', %d)",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId, $contact["id"], dbesc($x["carddata"]), dbesc($x["uri"]), dbesc($x["etag"]), $x["size"]
);
}
/**
* Updates a card.
*
* The addressbook id will be passed as the first argument. This is the
* same id as it is returned from the getAddressbooksForUser method.
*
* The cardUri is a base uri, and doesn't include the full path. The
* cardData argument is the vcard body, and is passed as a string.
*
* It is possible to return an ETag from this method. This ETag should
* match that of the updated resource, and must be enclosed with double
* quotes (that is: the string itself must contain the actual quotes).
*
* You should only return the ETag if you store the carddata as-is. If a
* subsequent GET request on the same card does not have the same body,
* byte-by-byte and you did return an ETag here, clients tend to get
* confused.
*
* If you don't return an ETag, you can just return null.
*
* @param string $addressBookId
* @param string $cardUri
* @param string $cardData
* @throws Sabre_DAV_Exception_Forbidden
* @return string|null
*/
public function updateCard($addressBookId, $cardUri, $cardData)
{
$x = explode("-", $addressBookId);
$etag = md5($cardData);
q("UPDATE %s%scards SET carddata = '%s', lastmodified = %d, etag = '%s', size = %d, manually_edited = 1 WHERE uri = '%s' AND namespace = %d AND namespace_id =%d",
CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), time(), $etag, strlen($cardData), dbesc($cardUri), IntVal($x[10]), IntVal($x[1])
);
q('UPDATE %s%saddressbooks_community SET ctag = ctag + 1 WHERE uid = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
return '"' . $etag . '"';
}
/**
* Deletes a card
*
* @param string $addressBookId
* @param string $cardUri
* @throws Sabre_DAV_Exception_Forbidden
* @return bool
*/
public function deleteCard($addressBookId, $cardUri)
{
$x = explode("-", $addressBookId);
q("UPDATE %s%scards SET manually_deleted = 1 WHERE namespace = %d AND namespace_id = %d AND uri = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[0]), IntVal($x[1]), dbesc($cardUri));
q('UPDATE %s%saddressbooks_community SET ctag = ctag + 1 WHERE uid = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1]));
return true;
}
}

View file

@ -17,7 +17,7 @@ function wdcal_addRequiredHeaders()
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/dav/timepicker/timePicker.css' . '" media="all" />' . "\r\n";
$a->page['htmlhead'] .= '<script type="text/javascript" src="' . $a->get_baseurl() . '/addon/dav/timepicker/jquery.timePicker.min.js"></script>' . "\r\n";
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/dav/wdcal.css' . '" media="all" />' . "\r\n";
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/dav/friendica/wdcal.css' . '" media="all" />' . "\r\n";
$a->page['htmlhead'] .= '<script type="text/javascript" src="' . $a->get_baseurl() . '/addon/dav/common/wdcal.js"></script>' . "\r\n";
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/dav/wdcal/css/calendar.css' . '" media="all" />' . "\r\n";
@ -86,12 +86,12 @@ function wdcal_import_user_ics($calendar_id) {
if ($_FILES["ics_file"]["tmp_name"] != "" && is_uploaded_file($_FILES["ics_file"]["tmp_name"])) try {
$text = file_get_contents($_FILES["ics_file"]["tmp_name"]);
/** @var Sabre_VObject_Component_VCalendar $vObject */
$vObject = Sabre_VObject_Reader::read($text);
/** @var Sabre\VObject\Component\VCalendar $vObject */
$vObject = Sabre\VObject\Reader::read($text);
$comp = $vObject->getComponents();
$imported = array();
foreach ($comp as $c) try {
/** @var Sabre_VObject_Component_VEvent $c */
/** @var Sabre\VObject\Component\VEvent $c */
$uid = $c->__get("UID")->value;
if (!isset($imported[$uid])) $imported[$uid] = "";
$imported[$uid] .= $c->serialize();

View file

@ -26,21 +26,48 @@ function dav_module()
function dav_include_files()
{
require_once (__DIR__ . "/SabreDAV/lib/Sabre/autoload.php");
require_once (__DIR__ . "/../SabreDAV/lib/Sabre/autoload.php");
require_once (__DIR__ . "/common/calendar.fnk.php");
require_once (__DIR__ . "/common/calendar_rendering.fnk.php");
require_once (__DIR__ . "/common/dav_caldav_backend_common.inc.php");
require_once (__DIR__ . "/common/dav_caldav_backend_private.inc.php");
require_once (__DIR__ . "/common/dav_caldav_backend_virtual.inc.php");
require_once (__DIR__ . "/common/dav_caldav_root.inc.php");
require_once (__DIR__ . "/common/dav_user_calendars.inc.php");
require_once (__DIR__ . "/common/dav_carddav_root.inc.php");
require_once (__DIR__ . "/common/dav_carddav_backend_std.inc.php");
require_once (__DIR__ . "/common/dav_user_addressbooks.inc.php");
require_once (__DIR__ . "/common/dav_caldav_calendar_virtual.inc.php");
require_once (__DIR__ . "/common/wdcal_configuration.php");
require_once (__DIR__ . "/common/wdcal_backend.inc.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Node.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Element.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Component.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/DateTimeParser.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/ElementList.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/FreeBusyGenerator.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Parameter.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/ParseException.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Property.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Reader.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/RecurrenceIterator.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/TimeZoneUtil.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Version.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Property/DateTime.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Property/MultiDateTime.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Component/VAlarm.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Component/VCalendar.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Component/VEvent.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Component/VJournal.php");
require_once (__DIR__ . "/../sabre-vobject/lib/Sabre/VObject/Component/VTodo.php");
require_once (__DIR__ . "/../common/calendar.fnk.php");
require_once (__DIR__ . "/../common/calendar_rendering.fnk.php");
require_once (__DIR__ . "/../common/dav_caldav_backend_common.inc.php");
require_once (__DIR__ . "/../common/dav_caldav_backend_private.inc.php");
require_once (__DIR__ . "/../common/dav_caldav_backend_virtual.inc.php");
require_once (__DIR__ . "/../common/dav_caldav_root.inc.php");
require_once (__DIR__ . "/../common/dav_user_calendars.inc.php");
require_once (__DIR__ . "/../common/dav_caldav_calendar_virtual.inc.php");
require_once (__DIR__ . "/../common/dav_caldav_calendar_private.inc.php");
require_once (__DIR__ . "/../common/dav_carddav_root.inc.php");
require_once (__DIR__ . "/../common/dav_carddav_backend_common.inc.php");
require_once (__DIR__ . "/../common/dav_carddav_backend_virtual.inc.php");
require_once (__DIR__ . "/../common/dav_carddav_backend_private.inc.php");
require_once (__DIR__ . "/../common/dav_user_addressbooks.inc.php");
require_once (__DIR__ . "/../common/wdcal_configuration.php");
require_once (__DIR__ . "/../common/wdcal_backend.inc.php");
require_once (__DIR__ . "/dav_friendica_principal.inc.php");
require_once (__DIR__ . "/dav_friendica_auth.inc.php");
@ -48,7 +75,7 @@ function dav_include_files()
require_once (__DIR__ . "/dav_caldav_backend_virtual_friendica.inc.php");
require_once (__DIR__ . "/FriendicaACLPlugin.inc.php");
require_once (__DIR__ . "/common/wdcal_edit.inc.php");
require_once (__DIR__ . "/../common/wdcal_edit.inc.php");
require_once (__DIR__ . "/calendar.friendica.fnk.php");
require_once (__DIR__ . "/layout.fnk.php");
}
@ -65,6 +92,9 @@ function dav_init(&$a)
* ALTER TABLE `photo` ADD INDEX ( `contact-id` )
*/
ini_set("display_errors", 1);
error_reporting(E_ALL);
dav_include_files();
if (false) {
@ -74,6 +104,7 @@ function dav_init(&$a)
}
wdcal_create_std_calendars();
wdcal_create_std_addressbooks();
wdcal_addRequiredHeaders();
if ($a->argc >= 2 && $a->argv[1] == "wdcal") {
@ -99,9 +130,11 @@ function dav_init(&$a)
}
$server = dav_create_server();
$server = dav_create_server();
$browser = new Sabre_DAV_Browser_Plugin();
$server->addPlugin($browser);
$server->exec();
killme();
@ -281,8 +314,7 @@ function dav_plugin_admin_post(&$a = null, &$o = null)
if (count($errs) == 0) {
renderAllCalDavEntries();
info(t('The database tables have been updated.') . EOL);
}
else notice(t("An error occurred during the update.") . EOL);
} else notice(t("An error occurred during the update.") . EOL);
}
}
@ -307,6 +339,7 @@ function dav_plugin_admin(&$a, &$o)
$o .= t('Installed');
break;
case 1:
case 2:
$o .= "<strong>" . t('Upgrade needed') . "</strong><br>" . t("Please back up all calendar data (the tables beginning with dav_*) before proceeding. While all calendar events <i>should</i> be converted to the new database structure, it's always safe to have a backup. Below, you can have a look at the database-queries that will be made when pressing the 'update'-button.") . "<br><br><input type='submit' name='upgrade' value='" . t('Upgrade') . "'>";
break;
case -1:
@ -323,8 +356,8 @@ function dav_plugin_admin(&$a, &$o)
$o .= "<h4>" . t("Manual creation of the database tables:") . "</h4>";
$o .= "<a href='#' onClick='\$(\"#sqlstatements\").show(); return false;'>" . t("Show SQL-statements") . "</a><blockquote style='display: none;' id='sqlstatements'><pre>";
switch ($dbstatus) {
case 1:
$tables = dav_get_update_statements(1);
case 1: case 2:
$tables = dav_get_update_statements($dbstatus);
foreach ($tables as $t) $o .= escape_tags($t . ";\n\n");
break;
default:

View file

@ -0,0 +1,8 @@
language: php
php:
- 5.3
- 5.4
script: phpunit --configuration tests/phpunit.xml
before_script: composer install

View file

@ -0,0 +1,7 @@
2.0.0-stable (2012-08-08)
* VObject is now a separate project from SabreDAV. See the SabreDAV
changelog for version information before 2.0.
* New: VObject library now uses PHP 5.3 namespaces.
* New: It's possible to specify lists of parameters when constructing
properties.
* New: made it easier to construct the FreeBusyGenerator.

27
dav/sabre-vobject/LICENSE Normal file
View file

@ -0,0 +1,27 @@
Copyright (C) 2007-2012 Rooftop Solutions.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Sabre nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

388
dav/sabre-vobject/README.md Normal file
View file

@ -0,0 +1,388 @@
# SabreTooth VObject library
[![Build Status](https://secure.travis-ci.org/evert/sabre-vobject.png?branch=master)](http://travis-ci.org/evert/sabre-vobject)
The VObject library allows you to easily parse and manipulate [iCalendar](https://tools.ietf.org/html/rfc5545)
and [vCard](https://tools.ietf.org/html/rfc6350) objects using PHP.
The goal of the VObject library is to create a very complete library, with an easy to use API.
This project is a spin-off from [SabreDAV](http://code.google.com/p/sabredav/), where it has
been used for several years. The VObject library has 100% unittest coverage.
# Installation
VObject requires PHP 5.3, and should be installed using composer.
The general composer instructions can be found on the [composer website](http://getcomposer.org/doc/00-intro.md composer website).
After that, just declare the vobject dependency as follows:
```
"require" : {
"sabre/vobject" : "dev-master"
}
```
Then, run `composer.phar update` and you should be good. As soon as the first release is out, you should switch `dev-master` to `2.0.*` though.
# Usage
## Parsing
For our example, we will be using the following vcard:
```
BEGIN:VCARD
VERSION:3.0
PRODID:-//Sabre//Sabre VObject 2.0//EN
N:Planck;Max;;;
FN:Max Planck
EMAIL;TYPE=WORK:mplanck@example.org
item1.TEL;TYPE=CELL:(+49)3144435678
item1.X-ABLabel:Private cell
item2.TEL;TYPE=WORK:(+49)5554564744
item2.X-ABLabel:Work
END:VCARD
```
If we want to just print out Max' full name, you can just use property access:
```php
use Sabre\VObject;
$card = VObject\Reader::read($data);
echo $card->FN;
```
## Changing properties
Creating properties is pretty similar. If we like to add his birthday, we just
set the property:
```php
$card->BDAY = '1858-04-23';
```
Note that in the previous example, we're actually updating any existing BDAY that
may already exist. If we want to add a new property, without overwriting the previous
we can do this with the `add` method.
```php
$card->add('EMAIL','max@example.org');
```
## Parameters
If we want to also specify that this is max' home email addresses, we can do this with
a third parameter:
```
$card->add('EMAIL', 'max@example'org', array('type' => 'HOME'));
```
If we want to read out all the email addresses and their type, this would look something
like this:
```
foreach($card->EMAIL as $email) {
echo $email['TYPE'], ' - ', $email;
}
```
## Groups
In our example, you can see that the TEL properties are prefixed. These are 'groups' and
allow you to group multiple related properties together. The group can be any user-defined
name.
This particular example as generated by the OS X addressbook, which uses the `X-ABLabel`
to allow the user to specify custom labels for properties. OS X addressbook uses groups
to tie the label to the property.
The VObject library simply ignores the group if you don't specify it, so this will work:
```php
foreach($card->TEL as $tel) {
echo $tel, "\n";
}
```
But if you would like to target a specific group + property, this is possible too:
```php
echo $card->{'ITEM1.TEL'};
```
So if you would like to show all the phone numbers, along with their custom label, the
following syntax is used:
```
foreach($card->TEL as $tel) {
echo $card->{$tel->group . '.X-ABLABEL'}, ": ";
echo $tel, "\n";
}
```
## Serializing / Saving
If you want to generate your updated VObject, you can simply call the serialize() method.
```
echo $card->serialize();
```
## Components
iCalendar, unlike vCards always have sub-components. Where vCards are often just a flat
list, iCalendar objects tend to have a tree-like structure. For the following paragraphs,
we will use the following object as the example:
```
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Sabre//Sabre VObject 2.0//EN
BEGIN:VEVENT
SUMMARY:Curiosity landing
DTSTART:20120806T051439Z
LOCATION:Mars
END:VEVENT
END:VCALENDAR
```
Since events, tasks and journals are always in a sub component, this is also how we
access them.
```php
use Sabre\VObject;
$calendar = VObject\Reader::read($data);
echo $calendar->VEVENT->SUMMARY;
```
Adding components to a calendar is done with a factory method:
```php
$event = VObject\Component::create('VEVENT');
$calendar->add($event);
$event->SUMMARY = 'Curiosity launch';
$event->DTSTART = '20111126T150202Z';
$event->LOCATION = 'Cape Carnival';
```
By the way.. cloning also works as expected, as the entire structure is cloned along with it:
```php
$clonedEvent = clone $calendar->VEVENT[0];
$calendar->add($clonedEvent);
```
## Date and time handling
If you ever had to deal with iCalendar timezones, you know it can be complicated.
The way timezones are specified is flawed, which is something I may write an essay about some
day. VObject does its best to determine the correct timezone. Many standard formats
have been tested and verified, and special code has been implemented for special-casing
microsoft generated timezone information, and others.
To get a real php `DateTime` object, you can request this as follows:
```
$event = $calendar->VEVENT;
$start = $event->DTSTART->getDateTime();
echo $start->format(\DateTime::W3C);
```
To set the property with a DateTime object, you can use the following syntax:
```
$dateTime = new \DateTime('2012-08-07 23:53:00', new DateTimeZone('Europe/Amsterdam'));
$event->DTSTART->setDateTime($dateTime, VObject\Property\DateTime::DATE);
```
The second argument specifies the type of date you're setting. The following three
options exist:
1. `LOCAL` This is a floating time, with no timezone information. This basically specifies that the event happens in whatever the timezone's currently in. This would be encoded as `DTSTART;VALUE=DATE-TIME:20120807235300`
2. `UTC` This specifies that the time should be encoded as a UTC time. This is encoded as `DTSTART;VALUE=DATE-TIME:20120807205300Z`. Note the extra Z and the fact that it's two hours 'earlier'.
3. `LOCALTZ` specifies that it's supposed to be encoded in its local timezone. For example `DTSTART;VALUE=DATE-TIME;TZID=Europe/Amsterdam:20120807235300`.
4. `DATE` This is a date-only, and does not contain the time. In this case this would be encoded as `DTSTART;VALUE=DATE:20120807`.
A few important notes:
* When a `TZID` is specified, there should also be a matching `VTIMEZONE` object with all the timezone information. VObject cannot currently automatically embed this. However, in reality other clients seem to do fine without this information. Yet, for completeness, this will be added in the future.
* As mentioned, the timezone-determination process may sometimes fail. Report any issues you find, and I'll be quick to add workarounds!
## Recurrence rules
Recurrence rules allow events to recur, for example for a weekly meeting, or an anniversary.
This is done with the `RRULE` property. The `RRULE` property allows for a LOT of different
rules. VObject only implements the ones that actually appear in calendar software.
To read more about `RRULE` and all the options, check out [RFC5545](https://tools.ietf.org/html/rfc5545#section-3.8.5).
VObject supports the following options:
1. `UNTIL` for an end date.
2. `INTERVAL` for for example "every 2 days".
3. `COUNT` to stop recurring after x items.
4. `FREQ=DAILY` to recur every day, and `BYDAY` to limit it to certain days.
5. `FREQ=WEEKLY` to recur every week, `BYDAY` to expand this to multiple weekdays in every week and `WKST` to specify on which day the week starts.
6. `FREQ=MONTHLY` to recur every month, `BYMONTHDAY` to expand this to certain days in a month, `BYDAY` to expand it to certain weekdays occuring in a month, and `BYSETPOS` to limit the last two expansions.
7. `FREQ=YEARLY` to recur every year, `BYMONTH` to expand that to certain months in a year, and `BYDAY` and `BYWEEKDAY` to expand the `BYMONTH` rule even further.
VObject supports the `EXDATE` property for exclusions, but not yet the `RDATE` and `EXRULE`
properties. If you're interested in this, please file a github issue, as this will put it
on my radar.
This is a bit of a complex subject to go in excruciating detail. The
[RFC](https://tools.ietf.org/html/rfc5545#section-3.8.5) has a lot of examples though.
The hard part is not to write the RRULE, it is to expand them. The most complex and
hard-to-read code is hidden in this component. Dragons be here.
So, if we have a meeting every 2nd monday of the month, this would be specified as such:
```
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:1102c450-e0d7-11e1-9b23-0800200c9a66
DTSTART:20120109T140000Z
RRULE:FREQ=MONTHLY;BYDAY=MO;BYSETPOS=2
END:VEVENT
END:VCALENDAR
```
Note that normally it's not allowed to indent the object like this, but it does make
it easier to read. This is also the first time I added in a UID, which is required
for all VEVENT, VTODO and VJOURNAL objects!
To figure out all the meetings for this year, we can use the following syntax:
```php
use Sabre\VObject;
$calendar = VObject\Reader::read($data);
$calendar->expand(new DateTime('2012-01-01'), new DateTime('2012-12-31'));
```
What the expand method does, is look at its inner events, and expand the recurring
rule. Our calendar now contains 12 events. The first will have its RRULE stripped,
and every subsequent VEVENT has the correct meeting date and a `RECURRENCE-ID` set.
This results in something like this:
```
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:1102c450-e0d7-11e1-9b23-0800200c9a66
DTSTART:20120109T140000Z
END:VEVENT
BEGIN:VEVENT
UID:1102c450-e0d7-11e1-9b23-0800200c9a66
RECURRENCE-ID:20120213T140000Z
DTSTART:20120213T140000Z
END:VEVENT
BEGIN:VEVENT
UID:1102c450-e0d7-11e1-9b23-0800200c9a66
RECURRENCE-ID:20120312T140000Z
DTSTART:20120312T140000Z
END:VEVENT
..etc..
END:VCALENDAR
```
To show the list of dates, we would do this as such:
```
foreach($calendar->VEVENT as $event) {
echo $event->DTSTART->getDateTime()->format(\DateTime::ATOM);
}
```
In a recurring event, single instances can also be overriden. VObject also takes these
into consideration. The reason we needed to specify a start and end-date, is because
some recurrence rules can be 'never ending'.
You should make sure you pick a sane date-range. Because if you pick a 50 year
time-range, for a daily recurring event; this would result in over 18K objects.
# Free-busy report generation
Some calendaring software can make use of FREEBUSY reports to show when people are
available.
You can automatically generate these reports from calendars using the `FreeBusyGenerator`.
Example based on our last event:
```
// We're giving it the calendar object. It's also possible to specify multiple objects,
// by setting them as an array.
//
// We must also specify a start and end date, because recurring events are expanded.
$fbGenerator = new VObject\FreeBusyGenerator(
new DateTime('2012-01-01'),
new DateTime('2012-12-31'),
$calendar
);
// Grabbing the report
$freebusy = $fbGenerator->result();
// The freebusy report is another VCALENDAR object, so we can serialize it as usual:
echo $freebusy->serialize();
```
The output of this script will look like this:
```
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Sabre//Sabre VObject 2.0//EN
CALSCALE:GREGORIAN
BEGIN:VFREEBUSY
DTSTART;VALUE=DATE-TIME:20111231T230000Z
DTEND;VALUE=DATE-TIME:20111231T230000Z
DTSTAMP;VALUE=DATE-TIME:20120808T131628Z
FREEBUSY;FBTYPE=BUSY:20120109T140000Z/20120109T140000Z
FREEBUSY;FBTYPE=BUSY:20120213T140000Z/20120213T140000Z
FREEBUSY;FBTYPE=BUSY:20120312T140000Z/20120312T140000Z
FREEBUSY;FBTYPE=BUSY:20120409T140000Z/20120409T140000Z
FREEBUSY;FBTYPE=BUSY:20120514T140000Z/20120514T140000Z
FREEBUSY;FBTYPE=BUSY:20120611T140000Z/20120611T140000Z
FREEBUSY;FBTYPE=BUSY:20120709T140000Z/20120709T140000Z
FREEBUSY;FBTYPE=BUSY:20120813T140000Z/20120813T140000Z
FREEBUSY;FBTYPE=BUSY:20120910T140000Z/20120910T140000Z
FREEBUSY;FBTYPE=BUSY:20121008T140000Z/20121008T140000Z
FREEBUSY;FBTYPE=BUSY:20121112T140000Z/20121112T140000Z
FREEBUSY;FBTYPE=BUSY:20121210T140000Z/20121210T140000Z
END:VFREEBUSY
END:VCALENDAR
```

View file

@ -0,0 +1,27 @@
{
"name": "sabre/vobject",
"description" : "The VObject library for PHP allows you to easily parse and manipulate iCalendar and vCard objects",
"keywords" : [ "VObject", "iCalendar", "vCard" ],
"homepage" : "https://github.com/evert/sabre-vobject",
"license" : "BSD-3-Clause",
"require" : {
"php" : ">=5.3.1"
},
"authors" : [
{
"name" : "Evert Pot",
"email" : "evert@rooftopsolutions.nl",
"homepage" : "http://www.rooftopsolutions.nl/",
"role" : "Developer"
}
],
"support" : {
"forum" : "https://groups.google.com/group/sabredav-discuss",
"source" : "https://github.com/evert/sabre-vobject"
},
"autoload" : {
"psr-0" : {
"Sabre\\VObject" : "lib/"
}
}
}

View file

@ -1,5 +1,7 @@
<?php
namespace Sabre\VObject;
/**
* VObject Component
*
@ -7,13 +9,11 @@
* VEVENT, VTODO and also VCALENDAR. It starts with BEGIN:COMPONENTNAME and
* ends with END:COMPONENTNAME
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_Component extends Sabre_VObject_Element {
class Component extends Element {
/**
* Name, for example VEVENT
@ -29,6 +29,11 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
*/
public $children = array();
/**
* The following constants are used by the validate() method.
*/
const REPAIR = 1;
/**
* If components are added to this map, they will be automatically mapped
* to their respective classes, if parsed by the reader or constructed with
@ -37,11 +42,12 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
* @var array
*/
static public $classMap = array(
'VCALENDAR' => 'Sabre_VObject_Component_VCalendar',
'VEVENT' => 'Sabre_VObject_Component_VEvent',
'VTODO' => 'Sabre_VObject_Component_VTodo',
'VJOURNAL' => 'Sabre_VObject_Component_VJournal',
'VALARM' => 'Sabre_VObject_Component_VAlarm',
'VALARM' => 'Sabre\\VObject\\Component\\VAlarm',
'VCALENDAR' => 'Sabre\\VObject\\Component\\VCalendar',
'VCARD' => 'Sabre\\VObject\\Component\\VCard',
'VEVENT' => 'Sabre\\VObject\\Component\\VEvent',
'VJOURNAL' => 'Sabre\\VObject\\Component\\VJournal',
'VTODO' => 'Sabre\\VObject\\Component\\VTodo',
);
/**
@ -50,7 +56,7 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
*
* @param string $name
* @param string $value
* @return Sabre_VObject_Component
* @return Component
*/
static public function create($name, $value = null) {
@ -71,9 +77,9 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
* be overridden with the iterator argument
*
* @param string $name
* @param Sabre_VObject_ElementList $iterator
* @param ElementList $iterator
*/
public function __construct($name, Sabre_VObject_ElementList $iterator = null) {
public function __construct($name, ElementList $iterator = null) {
$this->name = strtoupper($name);
if (!is_null($iterator)) $this->iterator = $iterator;
@ -100,12 +106,13 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
* preserve the original relative order of elements.
*
* @param int $key
* @param Sabre_VObject $array
* @param array $array
* @return int
*/
$sortScore = function($key, $array) {
if ($array[$key] instanceof Sabre_VObject_Component) {
if ($array[$key] instanceof Component) {
// We want to encode VTIMEZONE first, this is a personal
// preference.
if ($array[$key]->name === 'VTIMEZONE') {
@ -118,7 +125,7 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
} else {
// Properties get encoded first
// VCARD version 4.0 wants the VERSION property to appear first
if ($array[$key] instanceof Sabre_VObject_Property) {
if ($array[$key] instanceof Property) {
if ($array[$key]->name === 'VERSION') {
$score=100000000;
return $score+$key;
@ -129,7 +136,6 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
}
}
}
next($children);
};
@ -157,8 +163,8 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
*
* You can call this method with the following syntaxes:
*
* add(Sabre_VObject_Element $element)
* add(string $name, $value)
* add(Element $element)
* add(string $name, $value, array $parameters = array())
*
* The first version adds an Element
* The second adds a property as a string.
@ -167,26 +173,26 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
* @param mixed $itemValue
* @return void
*/
public function add($item, $itemValue = null) {
public function add($item, $itemValue = null, array $parameters = array()) {
if ($item instanceof Sabre_VObject_Element) {
if ($item instanceof Element) {
if (!is_null($itemValue)) {
throw new InvalidArgumentException('The second argument must not be specified, when passing a VObject');
throw new \InvalidArgumentException('The second argument must not be specified, when passing a VObject');
}
$item->parent = $this;
$this->children[] = $item;
} elseif(is_string($item)) {
if (!is_scalar($itemValue)) {
throw new InvalidArgumentException('The second argument must be scalar');
throw new \InvalidArgumentException('The second argument must be scalar');
}
$item = Sabre_VObject_Property::create($item,$itemValue);
$item = Property::create($item,$itemValue, $parameters);
$item->parent = $this;
$this->children[] = $item;
} else {
throw new InvalidArgumentException('The first argument must either be a Sabre_VObject_Element or a string');
throw new \InvalidArgumentException('The first argument must either be a \\Sabre\\VObject\\Element or a string');
}
@ -195,11 +201,11 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
/**
* Returns an iterable list of children
*
* @return Sabre_VObject_ElementList
* @return ElementList
*/
public function children() {
return new Sabre_VObject_ElementList($this->children);
return new ElementList($this->children);
}
@ -232,7 +238,7 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
if (
strtoupper($child->name) === $name &&
(is_null($group) || ( $child instanceof Sabre_VObject_Property && strtoupper($child->group) === $group))
(is_null($group) || ( $child instanceof Property && strtoupper($child->group) === $group))
) {
$result[$key] = $child;
@ -255,7 +261,7 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
$result = array();
foreach($this->children as $child) {
if ($child instanceof Sabre_VObject_Component) {
if ($child instanceof Component) {
$result[] = $child;
}
}
@ -266,6 +272,11 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
/**
* Validates the node for correctness.
*
* The following options are supported:
* - Component::REPAIR - If something is broken, and automatic repair may
* be attempted.
*
* An array is returned with warnings.
*
* Every item in the array has the following properties:
@ -273,9 +284,10 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
* * message - (human readable message)
* * node - (reference to the offending node)
*
* @param int $options
* @return array
*/
public function validate() {
public function validate($options = 0) {
$result = array();
foreach($this->children as $child) {
@ -294,7 +306,7 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
* null is returned.
*
* @param string $name
* @return Sabre_VObject_Property
* @return Property
*/
public function __get($name) {
@ -303,8 +315,8 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
return null;
} else {
$firstMatch = current($matches);
/** @var $firstMatch Sabre_VObject_Property */
$firstMatch->setIterator(new Sabre_VObject_ElementList(array_values($matches)));
/** @var $firstMatch Property */
$firstMatch->setIterator(new ElementList(array_values($matches)));
return $firstMatch;
}
@ -326,7 +338,7 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
/**
* Using the setter method you can add properties or subcomponents
*
* You can either pass a Sabre_VObject_Component, Sabre_VObject_Property
* You can either pass a Component, Property
* object, or a string to automatically create a Property.
*
* If the item already exists, it will be removed. If you want to add
@ -341,7 +353,7 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
$matches = $this->select($name);
$overWrite = count($matches)?key($matches):null;
if ($value instanceof Sabre_VObject_Component || $value instanceof Sabre_VObject_Property) {
if ($value instanceof Component || $value instanceof Property) {
$value->parent = $this;
if (!is_null($overWrite)) {
$this->children[$overWrite] = $value;
@ -349,7 +361,7 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
$this->children[] = $value;
}
} elseif (is_scalar($value)) {
$property = Sabre_VObject_Property::create($name,$value);
$property = Property::create($name,$value);
$property->parent = $this;
if (!is_null($overWrite)) {
$this->children[$overWrite] = $property;
@ -357,7 +369,7 @@ class Sabre_VObject_Component extends Sabre_VObject_Element {
$this->children[] = $property;
}
} else {
throw new InvalidArgumentException('You must pass a Sabre_VObject_Component, Sabre_VObject_Property or scalar type');
throw new \InvalidArgumentException('You must pass a \\Sabre\\VObject\\Component, \\Sabre\\VObject\\Property or scalar type');
}
}

View file

@ -1,17 +1,18 @@
<?php
namespace Sabre\VObject\Component;
use Sabre\VObject;
/**
* VAlarm component
*
* This component contains some additional functionality specific for VALARMs.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_Component_VAlarm extends Sabre_VObject_Component {
class VAlarm extends VObject\Component {
/**
* Returns a DateTime object when this alarm is going to trigger.
@ -24,7 +25,7 @@ class Sabre_VObject_Component_VAlarm extends Sabre_VObject_Component {
$trigger = $this->TRIGGER;
if(!isset($trigger['VALUE']) || strtoupper($trigger['VALUE']) === 'DURATION') {
$triggerDuration = Sabre_VObject_DateTimeParser::parseDuration($this->TRIGGER);
$triggerDuration = VObject\DateTimeParser::parseDuration($this->TRIGGER);
$related = (isset($trigger['RELATED']) && strtoupper($trigger['RELATED']) == 'END') ? 'END' : 'START';
$parentComponent = $this->parent;
@ -37,7 +38,7 @@ class Sabre_VObject_Component_VAlarm extends Sabre_VObject_Component {
} elseif ($parentComponent->name === 'VEVENT') {
$endProp = 'DTEND';
} else {
throw new Sabre_DAV_Exception('time-range filters on VALARM components are only supported when they are a child of VTODO or VEVENT');
throw new \LogicException('time-range filters on VALARM components are only supported when they are a child of VTODO or VEVENT');
}
if (isset($parentComponent->$endProp)) {
@ -45,7 +46,7 @@ class Sabre_VObject_Component_VAlarm extends Sabre_VObject_Component {
$effectiveTrigger->add($triggerDuration);
} elseif (isset($parentComponent->DURATION)) {
$effectiveTrigger = clone $parentComponent->DTSTART->getDateTime();
$duration = Sabre_VObject_DateTimeParser::parseDuration($parentComponent->DURATION);
$duration = VObject\DateTimeParser::parseDuration($parentComponent->DURATION);
$effectiveTrigger->add($duration);
$effectiveTrigger->add($triggerDuration);
} else {
@ -67,22 +68,22 @@ class Sabre_VObject_Component_VAlarm extends Sabre_VObject_Component {
* The rules used to determine if an event falls within the specified
* time-range is based on the CalDAV specification.
*
* @param DateTime $start
* @param DateTime $end
* @param \DateTime $start
* @param \DateTime $end
* @return bool
*/
public function isInTimeRange(DateTime $start, DateTime $end) {
public function isInTimeRange(\DateTime $start, \DateTime $end) {
$effectiveTrigger = $this->getEffectiveTriggerTime();
if (isset($this->DURATION)) {
$duration = Sabre_VObject_DateTimeParser::parseDuration($this->DURATION);
$duration = VObject\DateTimeParser::parseDuration($this->DURATION);
$repeat = (string)$this->repeat;
if (!$repeat) {
$repeat = 1;
}
$period = new DatePeriod($effectiveTrigger, $duration, (int)$repeat);
$period = new \DatePeriod($effectiveTrigger, $duration, (int)$repeat);
foreach($period as $occurrence) {

View file

@ -1,17 +1,19 @@
<?php
namespace Sabre\VObject\Component;
use Sabre\VObject;
/**
* The VCalendar component
*
* This component adds functionality to a component, specific for a VCALENDAR.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_Component_VCalendar extends Sabre_VObject_Component {
class VCalendar extends VObject\Component {
/**
* Returns a list of all 'base components'. For instance, if an Event has
@ -28,7 +30,7 @@ class Sabre_VObject_Component_VCalendar extends Sabre_VObject_Component {
$components = array();
foreach($this->children as $component) {
if (!$component instanceof Sabre_VObject_Component)
if (!$component instanceof VObject\Component)
continue;
if (isset($component->{'RECURRENCE-ID'}))
@ -69,7 +71,7 @@ class Sabre_VObject_Component_VCalendar extends Sabre_VObject_Component {
* @param DateTime $end
* @return void
*/
public function expand(DateTime $start, DateTime $end) {
public function expand(\DateTime $start, \DateTime $end) {
$newEvents = array();
@ -91,10 +93,10 @@ class Sabre_VObject_Component_VCalendar extends Sabre_VObject_Component {
$uid = (string)$vevent->uid;
if (!$uid) {
throw new LogicException('Event did not have a UID!');
throw new \LogicException('Event did not have a UID!');
}
$it = new Sabre_VObject_RecurrenceIterator($this, $vevent->uid);
$it = new VObject\RecurrenceIterator($this, $vevent->uid);
$it->fastForward($start);
while($it->valid() && $it->getDTStart() < $end) {
@ -114,9 +116,9 @@ class Sabre_VObject_Component_VCalendar extends Sabre_VObject_Component {
foreach($newEvents as $newEvent) {
foreach($newEvent->children as $child) {
if ($child instanceof Sabre_VObject_Property_DateTime &&
$child->getDateType() == Sabre_VObject_Property_DateTime::LOCALTZ) {
$child->setDateTime($child->getDateTime(),Sabre_VObject_Property_DateTime::UTC);
if ($child instanceof VObject\Property\DateTime &&
$child->getDateType() == VObject\Property\DateTime::LOCALTZ) {
$child->setDateTime($child->getDateTime(),VObject\Property\DateTime::UTC);
}
}
@ -140,6 +142,7 @@ class Sabre_VObject_Component_VCalendar extends Sabre_VObject_Component {
*
* @return array
*/
/*
public function validate() {
$warnings = array();
@ -198,7 +201,7 @@ class Sabre_VObject_Component_VCalendar extends Sabre_VObject_Component {
);
$componentsFound = 0;
foreach($this->children as $child) {
if($child instanceof Sabre_VObject_Component) {
if($child instanceof Component) {
$componentsFound++;
if (!in_array($child->name, $allowedComponents)) {
$warnings[] = array(
@ -208,7 +211,7 @@ class Sabre_VObject_Component_VCalendar extends Sabre_VObject_Component {
);
}
}
if ($child instanceof Sabre_VObject_Property) {
if ($child instanceof Property) {
if (!in_array($child->name, $allowedProperties)) {
$warnings[] = array(
'level' => 2,
@ -233,6 +236,7 @@ class Sabre_VObject_Component_VCalendar extends Sabre_VObject_Component {
);
}
*/
}

View file

@ -0,0 +1,105 @@
<?php
namespace Sabre\VObject\Component;
use Sabre\VObject;
/**
* The VCard component
*
* This component represents the BEGIN:VCARD and END:VCARD found in every
* vcard.
*
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class VCard extends VObject\Component {
/**
* VCards with version 2.1, 3.0 and 4.0 are found.
*
* If the VCARD doesn't know its version, 4.0 is assumed.
*/
const DEFAULT_VERSION = '4.0';
/**
* Validates the node for correctness.
*
* The following options are supported:
* - Component::REPAIR - If something is broken, and automatic repair may
* be attempted.
*
* An array is returned with warnings.
*
* Every item in the array has the following properties:
* * level - (number between 1 and 3 with severity information)
* * message - (human readable message)
* * node - (reference to the offending node)
*
* @param int $options
* @return array
*/
public function validate($options = 0) {
$warnings = array();
$version = $this->select('VERSION');
if (count($version)!==1) {
$warnings[] = array(
'level' => 1,
'message' => 'The VERSION property must appear in the VCARD component exactly 1 time',
'node' => $this,
);
if ($options & self::REPAIR) {
$this->VERSION = self::DEFAULT_VERSION;
}
} else {
$version = (string)$this->VERSION;
if ($version!=='2.1' && $version!=='3.0' && $version!=='4.0') {
$warnings[] = array(
'level' => 1,
'message' => 'Only vcard version 4.0 (RFC6350), version 3.0 (RFC2426) or version 2.1 (icm-vcard-2.1) are supported.',
'node' => $this,
);
if ($options & self::REPAIR) {
$this->VERSION = '4.0';
}
}
}
$version = $this->select('FN');
if (count($version)!==1) {
$warnings[] = array(
'level' => 1,
'message' => 'The FN property must appear in the VCARD component exactly 1 time',
'node' => $this,
);
if (($options & self::REPAIR) && count($version) === 0) {
// We're going to try to see if we can use the contents of the
// N property.
if (isset($this->N)) {
$value = explode(';', (string)$this->N);
if (isset($value[1]) && $value[1]) {
$this->FN = $value[1] . ' ' . $value[0];
} else {
$this->FN = $value[0];
}
// Otherwise, the ORG property may work
} elseif (isset($this->ORG)) {
$this->FN = (string)$this->ORG;
}
}
}
return array_merge(
parent::validate($options),
$warnings
);
}
}

View file

@ -1,17 +1,18 @@
<?php
namespace Sabre\VObject\Component;
use Sabre\VObject;
/**
* VEvent component
*
* This component contains some additional functionality specific for VEVENT's.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_Component_VEvent extends Sabre_VObject_Component {
class VEvent extends VObject\Component {
/**
* Returns true or false depending on if the event falls in the specified
@ -20,14 +21,14 @@ class Sabre_VObject_Component_VEvent extends Sabre_VObject_Component {
* The rules used to determine if an event falls within the specified
* time-range is based on the CalDAV specification.
*
* @param DateTime $start
* @param DateTime $end
* @param \DateTime $start
* @param \DateTime $end
* @return bool
*/
public function isInTimeRange(DateTime $start, DateTime $end) {
public function isInTimeRange(\DateTime $start, \DateTime $end) {
if ($this->RRULE) {
$it = new Sabre_VObject_RecurrenceIterator($this);
$it = new VObject\RecurrenceIterator($this);
$it->fastForward($start);
// We fast-forwarded to a spot where the end-time of the
@ -42,18 +43,19 @@ class Sabre_VObject_Component_VEvent extends Sabre_VObject_Component {
$effectiveStart = $this->DTSTART->getDateTime();
if (isset($this->DTEND)) {
// The DTEND property is considered non inclusive. So for a 3 day
// event in july, dtstart and dtend would have to be July 1st and
// July 4th respectively.
//
// See:
// http://tools.ietf.org/html/rfc5545#page-54
$effectiveEnd = $this->DTEND->getDateTime();
// If this was an all-day event, we should just increase the
// end-date by 1. Otherwise the event will last until the second
// the date changed, by increasing this by 1 day the event lasts
// all of the last day as well.
if ($this->DTSTART->getDateType() == Sabre_VObject_Property_DateTime::DATE) {
$effectiveEnd->modify('+1 day');
}
} elseif (isset($this->DURATION)) {
$effectiveEnd = clone $effectiveStart;
$effectiveEnd->add( Sabre_VObject_DateTimeParser::parseDuration($this->DURATION) );
} elseif ($this->DTSTART->getDateType() == Sabre_VObject_Property_DateTime::DATE) {
$effectiveEnd->add( VObject\DateTimeParser::parseDuration($this->DURATION) );
} elseif ($this->DTSTART->getDateType() == VObject\Property\DateTime::DATE) {
$effectiveEnd = clone $effectiveStart;
$effectiveEnd->modify('+1 day');
} else {

View file

@ -1,17 +1,19 @@
<?php
namespace Sabre\VObject\Component;
use Sabre\VObject;
/**
* VJournal component
*
* This component contains some additional functionality specific for VJOURNALs.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_Component_VJournal extends Sabre_VObject_Component {
class VJournal extends VObject\Component {
/**
* Returns true or false depending on if the event falls in the specified
@ -24,12 +26,12 @@ class Sabre_VObject_Component_VJournal extends Sabre_VObject_Component {
* @param DateTime $end
* @return bool
*/
public function isInTimeRange(DateTime $start, DateTime $end) {
public function isInTimeRange(\DateTime $start, \DateTime $end) {
$dtstart = isset($this->DTSTART)?$this->DTSTART->getDateTime():null;
if ($dtstart) {
$effectiveEnd = clone $dtstart;
if ($this->DTSTART->getDateType() == Sabre_VObject_Property_DateTime::DATE) {
if ($this->DTSTART->getDateType() == VObject\Property\DateTime::DATE) {
$effectiveEnd->modify('+1 day');
}

View file

@ -1,17 +1,19 @@
<?php
namespace Sabre\VObject\Component;
use Sabre\VObject;
/**
* VTodo component
*
* This component contains some additional functionality specific for VTODOs.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_Component_VTodo extends Sabre_VObject_Component {
class VTodo extends VObject\Component {
/**
* Returns true or false depending on if the event falls in the specified
@ -24,10 +26,10 @@ class Sabre_VObject_Component_VTodo extends Sabre_VObject_Component {
* @param DateTime $end
* @return bool
*/
public function isInTimeRange(DateTime $start, DateTime $end) {
public function isInTimeRange(\DateTime $start, \DateTime $end) {
$dtstart = isset($this->DTSTART)?$this->DTSTART->getDateTime():null;
$duration = isset($this->DURATION)?Sabre_VObject_DateTimeParser::parseDuration($this->DURATION):null;
$duration = isset($this->DURATION)?VObject\DateTimeParser::parseDuration($this->DURATION):null;
$due = isset($this->DUE)?$this->DUE->getDateTime():null;
$completed = isset($this->COMPLETED)?$this->COMPLETED->getDateTime():null;
$created = isset($this->CREATED)?$this->CREATED->getDateTime():null;

View file

@ -1,18 +1,18 @@
<?php
namespace Sabre\VObject;
/**
* DateTimeParser
*
* This class is responsible for parsing the several different date and time
* formats iCalendar and vCards have.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_DateTimeParser {
class DateTimeParser {
/**
* Parses an iCalendar (rfc5545) formatted datetime and returns a DateTime object
@ -25,22 +25,22 @@ class Sabre_VObject_DateTimeParser {
* @param DateTimeZone $tz
* @return DateTime
*/
static public function parseDateTime($dt,DateTimeZone $tz = null) {
static public function parseDateTime($dt,\DateTimeZone $tz = null) {
// Format is YYYYMMDD + "T" + hhmmss
$result = preg_match('/^([1-3][0-9]{3})([0-1][0-9])([0-3][0-9])T([0-2][0-9])([0-5][0-9])([0-5][0-9])([Z]?)$/',$dt,$matches);
if (!$result) {
throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar datetime value is incorrect: ' . $dt);
throw new \LogicException('The supplied iCalendar datetime value is incorrect: ' . $dt);
}
if ($matches[7]==='Z' || is_null($tz)) {
$tz = new DateTimeZone('UTC');
$tz = new \DateTimeZone('UTC');
}
$date = new DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3] . ' ' . $matches[4] . ':' . $matches[5] .':' . $matches[6], $tz);
$date = new \DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3] . ' ' . $matches[4] . ':' . $matches[5] .':' . $matches[6], $tz);
// Still resetting the timezone, to normalize everything to UTC
$date->setTimeZone(new DateTimeZone('UTC'));
$date->setTimeZone(new \DateTimeZone('UTC'));
return $date;
}
@ -57,10 +57,10 @@ class Sabre_VObject_DateTimeParser {
$result = preg_match('/^([1-3][0-9]{3})([0-1][0-9])([0-3][0-9])$/',$date,$matches);
if (!$result) {
throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar date value is incorrect: ' . $date);
throw new \LogicException('The supplied iCalendar date value is incorrect: ' . $date);
}
$date = new DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3], new DateTimeZone('UTC'));
$date = new \DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3], new \DateTimeZone('UTC'));
return $date;
}
@ -79,7 +79,7 @@ class Sabre_VObject_DateTimeParser {
$result = preg_match('/^(?P<plusminus>\+|-)?P((?P<week>\d+)W)?((?P<day>\d+)D)?(T((?P<hour>\d+)H)?((?P<minute>\d+)M)?((?P<second>\d+)S)?)?$/', $duration, $matches);
if (!$result) {
throw new Sabre_DAV_Exception_BadRequest('The supplied iCalendar duration value is incorrect: ' . $duration);
throw new \LogicException('The supplied iCalendar duration value is incorrect: ' . $duration);
}
if (!$asString) {
@ -128,7 +128,7 @@ class Sabre_VObject_DateTimeParser {
if ($duration==='P') {
$duration = 'PT0S';
}
$iv = new DateInterval($duration);
$iv = new \DateInterval($duration);
if ($invert) $iv->invert = true;
return $iv;

View file

@ -1,15 +1,15 @@
<?php
namespace Sabre\VObject;
/**
* Base class for all elements
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
abstract class Sabre_VObject_Element extends Sabre_VObject_Node {
abstract class Element extends Node {
public $parent = null;

View file

@ -1,18 +1,18 @@
<?php
namespace Sabre\VObject;
/**
* VObject ElementList
*
* This class represents a list of elements. Lists are the result of queries,
* such as doing $vcalendar->vevent where there's multiple VEVENT objects.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_ElementList implements Iterator, Countable, ArrayAccess {
class ElementList implements \Iterator, \Countable, \ArrayAccess {
/**
* Inner elements
@ -44,7 +44,7 @@ class Sabre_VObject_ElementList implements Iterator, Countable, ArrayAccess {
/**
* Returns current item in iteration
*
* @return Sabre_VObject_Element
* @return Element
*/
public function current() {
@ -149,7 +149,7 @@ class Sabre_VObject_ElementList implements Iterator, Countable, ArrayAccess {
*/
public function offsetSet($offset,$value) {
throw new LogicException('You can not add new objects to an ElementList');
throw new \LogicException('You can not add new objects to an ElementList');
}
@ -163,7 +163,7 @@ class Sabre_VObject_ElementList implements Iterator, Countable, ArrayAccess {
*/
public function offsetUnset($offset) {
throw new LogicException('You can not remove objects from an ElementList');
throw new \LogicException('You can not remove objects from an ElementList');
}

View file

@ -1,5 +1,7 @@
<?php
namespace Sabre\VObject;
/**
* This class helps with generating FREEBUSY reports based on existing sets of
* objects.
@ -10,13 +12,11 @@
* VFREEBUSY components are described in RFC5545, The rules for what should
* go in a single freebusy report is taken from RFC4791, section 7.10.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_FreeBusyGenerator {
class FreeBusyGenerator {
/**
* Input objects
@ -42,10 +42,33 @@ class Sabre_VObject_FreeBusyGenerator {
/**
* VCALENDAR object
*
* @var Sabre_VObject_Component
* @var Component
*/
protected $baseObject;
/**
* Creates the generator.
*
* Check the setTimeRange and setObjects methods for details about the
* arguments.
*
* @param DateTime $start
* @param DateTime $end
* @param mixed $objects
* @return void
*/
public function __construct(\DateTime $start = null, \DateTime $end = null, $objects = null) {
if ($start && $end) {
$this->setTimeRange($start, $end);
}
if ($objects) {
$this->setObjects($objects);
}
}
/**
* Sets the VCALENDAR object.
*
@ -54,10 +77,10 @@ class Sabre_VObject_FreeBusyGenerator {
*
* The VFREEBUSY object will be automatically added though.
*
* @param Sabre_VObject_Component $vcalendar
* @param Component $vcalendar
* @return void
*/
public function setBaseObject(Sabre_VObject_Component $vcalendar) {
public function setBaseObject(Component $vcalendar) {
$this->baseObject = $vcalendar;
@ -66,22 +89,28 @@ class Sabre_VObject_FreeBusyGenerator {
/**
* Sets the input objects
*
* Every object must either be a string or a Sabre_VObject_Component.
* You must either specify a valendar object as a strong, or as the parse
* Component.
* It's also possible to specify multiple objects as an array.
*
* @param array $objects
* @param mixed $objects
* @return void
*/
public function setObjects(array $objects) {
public function setObjects($objects) {
if (!is_array($objects)) {
$objects = array($objects);
}
$this->objects = array();
foreach($objects as $object) {
if (is_string($object)) {
$this->objects[] = Sabre_VObject_Reader::read($object);
} elseif ($object instanceof Sabre_VObject_Component) {
$this->objects[] = Reader::read($object);
} elseif ($object instanceof Component) {
$this->objects[] = $object;
} else {
throw new InvalidArgumentException('You can only pass strings or Sabre_VObject_Component arguments to setObjects');
throw new \InvalidArgumentException('You can only pass strings or \\Sabre\\VObject\\Component arguments to setObjects');
}
}
@ -97,7 +126,7 @@ class Sabre_VObject_FreeBusyGenerator {
* @param DateTime $end
* @return void
*/
public function setTimeRange(DateTime $start = null, DateTime $end = null) {
public function setTimeRange(\DateTime $start = null, \DateTime $end = null) {
$this->start = $start;
$this->end = $end;
@ -108,7 +137,7 @@ class Sabre_VObject_FreeBusyGenerator {
* Parses the input data and returns a correct VFREEBUSY object, wrapped in
* a VCALENDAR.
*
* @return Sabre_VObject_Component
* @return Component
*/
public function getResult() {
@ -140,7 +169,7 @@ class Sabre_VObject_FreeBusyGenerator {
if ($component->RRULE) {
$iterator = new Sabre_VObject_RecurrenceIterator($object, (string)$component->uid);
$iterator = new RecurrenceIterator($object, (string)$component->uid);
if ($this->start) {
$iterator->fastForward($this->start);
}
@ -172,10 +201,10 @@ class Sabre_VObject_FreeBusyGenerator {
if (isset($component->DTEND)) {
$endTime = $component->DTEND->getDateTime();
} elseif (isset($component->DURATION)) {
$duration = Sabre_VObject_DateTimeParser::parseDuration((string)$component->DURATION);
$duration = DateTimeParser::parseDuration((string)$component->DURATION);
$endTime = clone $startTime;
$endTime->add($duration);
} elseif ($component->DTSTART->getDateType() === Sabre_VObject_Property_DateTime::DATE) {
} elseif ($component->DTSTART->getDateType() === Property\DateTime::DATE) {
$endTime = clone $startTime;
$endTime->modify('+1 day');
} else {
@ -212,14 +241,14 @@ class Sabre_VObject_FreeBusyGenerator {
$values = explode(',', $freebusy);
foreach($values as $value) {
list($startTime, $endTime) = explode('/', $value);
$startTime = Sabre_VObject_DateTimeParser::parseDateTime($startTime);
$startTime = DateTimeParser::parseDateTime($startTime);
if (substr($endTime,0,1)==='P' || substr($endTime,0,2)==='-P') {
$duration = Sabre_VObject_DateTimeParser::parseDuration($endTime);
$duration = DateTimeParser::parseDuration($endTime);
$endTime = clone $startTime;
$endTime->add($duration);
} else {
$endTime = Sabre_VObject_DateTimeParser::parseDateTime($endTime);
$endTime = DateTimeParser::parseDateTime($endTime);
}
if($this->start && $this->start > $endTime) continue;
@ -248,39 +277,35 @@ class Sabre_VObject_FreeBusyGenerator {
if ($this->baseObject) {
$calendar = $this->baseObject;
} else {
$calendar = new Sabre_VObject_Component('VCALENDAR');
$calendar = new Component('VCALENDAR');
$calendar->version = '2.0';
if (Sabre_DAV_Server::$exposeVersion) {
$calendar->prodid = '-//SabreDAV//Sabre VObject ' . Sabre_VObject_Version::VERSION . '//EN';
} else {
$calendar->prodid = '-//SabreDAV//Sabre VObject//EN';
}
$calendar->prodid = '-//Sabre//Sabre VObject ' . Version::VERSION . '//EN';
$calendar->calscale = 'GREGORIAN';
}
$vfreebusy = new Sabre_VObject_Component('VFREEBUSY');
$vfreebusy = new Component('VFREEBUSY');
$calendar->add($vfreebusy);
if ($this->start) {
$dtstart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtstart->setDateTime($this->start,Sabre_VObject_Property_DateTime::UTC);
$dtstart = new Property\DateTime('DTSTART');
$dtstart->setDateTime($this->start,Property\DateTime::UTC);
$vfreebusy->add($dtstart);
}
if ($this->end) {
$dtend = new Sabre_VObject_Property_DateTime('DTEND');
$dtend->setDateTime($this->start,Sabre_VObject_Property_DateTime::UTC);
$dtend = new Property\DateTime('DTEND');
$dtend->setDateTime($this->start,Property\DateTime::UTC);
$vfreebusy->add($dtend);
}
$dtstamp = new Sabre_VObject_Property_DateTime('DTSTAMP');
$dtstamp->setDateTime(new DateTime('now'), Sabre_VObject_Property_DateTime::UTC);
$dtstamp = new Property\DateTime('DTSTAMP');
$dtstamp->setDateTime(new \DateTime('now'), Property\DateTime::UTC);
$vfreebusy->add($dtstamp);
foreach($busyTimes as $busyTime) {
$busyTime[0]->setTimeZone(new DateTimeZone('UTC'));
$busyTime[1]->setTimeZone(new DateTimeZone('UTC'));
$busyTime[0]->setTimeZone(new \DateTimeZone('UTC'));
$busyTime[1]->setTimeZone(new \DateTimeZone('UTC'));
$prop = new Sabre_VObject_Property(
$prop = new Property(
'FREEBUSY',
$busyTime[0]->format('Ymd\\THis\\Z') . '/' . $busyTime[1]->format('Ymd\\THis\\Z')
);

View file

@ -1,15 +1,15 @@
<?php
namespace Sabre\VObject;
/**
* Base class for all nodes
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
abstract class Sabre_VObject_Node implements IteratorAggregate, ArrayAccess, Countable {
abstract class Node implements \IteratorAggregate, \ArrayAccess, \Countable {
/**
* Turns the object back into a serialized blob.
@ -21,14 +21,14 @@ abstract class Sabre_VObject_Node implements IteratorAggregate, ArrayAccess, Cou
/**
* Iterator override
*
* @var Sabre_VObject_ElementList
* @var ElementList
*/
protected $iterator = null;
/**
* A link to the parent node
*
* @var Sabre_VObject_Node
* @var Node
*/
public $parent = null;
@ -54,14 +54,14 @@ abstract class Sabre_VObject_Node implements IteratorAggregate, ArrayAccess, Cou
/**
* Returns the iterator for this object
*
* @return Sabre_VObject_ElementList
* @return ElementList
*/
public function getIterator() {
if (!is_null($this->iterator))
return $this->iterator;
return new Sabre_VObject_ElementList(array($this));
return new ElementList(array($this));
}
@ -70,10 +70,10 @@ abstract class Sabre_VObject_Node implements IteratorAggregate, ArrayAccess, Cou
*
* Note that this is not actually part of the iterator interface
*
* @param Sabre_VObject_ElementList $iterator
* @param ElementList $iterator
* @return void
*/
public function setIterator(Sabre_VObject_ElementList $iterator) {
public function setIterator(ElementList $iterator) {
$this->iterator = $iterator;

View file

@ -1,5 +1,7 @@
<?php
namespace Sabre\VObject;
/**
* VObject Parameter
*
@ -8,13 +10,11 @@
* DTSTART;VALUE=DATE:20101108
* VALUE=DATE would be the parameter name and value.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_Parameter extends Sabre_VObject_Node {
class Parameter extends Node {
/**
* Parameter name

View file

@ -1,12 +1,12 @@
<?php
namespace Sabre\VObject;
/**
* Exception thrown by Sabre_VObject_Reader if an invalid object was attempted to be parsed.
* Exception thrown by Reader if an invalid object was attempted to be parsed.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_ParseException extends Exception { }
class ParseException extends \Exception { }

View file

@ -1,5 +1,7 @@
<?php
namespace Sabre\VObject;
/**
* VObject Property
*
@ -11,13 +13,11 @@
*
* Parameters can be accessed using the ArrayAccess interface.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_Property extends Sabre_VObject_Element {
class Property extends Element {
/**
* Propertyname
@ -57,27 +57,33 @@ class Sabre_VObject_Property extends Sabre_VObject_Element {
* @var array
*/
static public $classMap = array(
'COMPLETED' => 'Sabre_VObject_Property_DateTime',
'CREATED' => 'Sabre_VObject_Property_DateTime',
'DTEND' => 'Sabre_VObject_Property_DateTime',
'DTSTAMP' => 'Sabre_VObject_Property_DateTime',
'DTSTART' => 'Sabre_VObject_Property_DateTime',
'DUE' => 'Sabre_VObject_Property_DateTime',
'EXDATE' => 'Sabre_VObject_Property_MultiDateTime',
'LAST-MODIFIED' => 'Sabre_VObject_Property_DateTime',
'RECURRENCE-ID' => 'Sabre_VObject_Property_DateTime',
'TRIGGER' => 'Sabre_VObject_Property_DateTime',
'COMPLETED' => 'Sabre\\VObject\\Property\\DateTime',
'CREATED' => 'Sabre\\VObject\\Property\\DateTime',
'DTEND' => 'Sabre\\VObject\\Property\\DateTime',
'DTSTAMP' => 'Sabre\\VObject\\Property\\DateTime',
'DTSTART' => 'Sabre\\VObject\\Property\\DateTime',
'DUE' => 'Sabre\\VObject\\Property\\DateTime',
'EXDATE' => 'Sabre\\VObject\\Property\\MultiDateTime',
'LAST-MODIFIED' => 'Sabre\\VObject\\Property\\DateTime',
'RECURRENCE-ID' => 'Sabre\\VObject\\Property\\DateTime',
'TRIGGER' => 'Sabre\\VObject\\Property\\DateTime',
);
/**
* Creates the new property by name, but in addition will also see if
* there's a class mapped to the property name.
*
* Parameters can be specified with the optional third argument. Parameters
* must be a key->value map of the parameter name, and value. If the value
* is specified as an array, it is assumed that multiple parameters with
* the same name should be added.
*
* @param string $name
* @param string $value
* @return Sabre_VObject_Property
* @param array $parameters
* @return Property
*/
static public function create($name, $value = null) {
static public function create($name, $value = null, array $parameters = array()) {
$name = strtoupper($name);
$shortName = $name;
@ -87,9 +93,9 @@ class Sabre_VObject_Property extends Sabre_VObject_Element {
}
if (isset(self::$classMap[$shortName])) {
return new self::$classMap[$shortName]($name, $value);
return new self::$classMap[$shortName]($name, $value, $parameters);
} else {
return new self($name, $value);
return new self($name, $value, $parameters);
}
}
@ -97,14 +103,16 @@ class Sabre_VObject_Property extends Sabre_VObject_Element {
/**
* Creates a new property object
*
* By default this object will iterate over its own children, but this can
* be overridden with the iterator argument
* Parameters can be specified with the optional third argument. Parameters
* must be a key->value map of the parameter name, and value. If the value
* is specified as an array, it is assumed that multiple parameters with
* the same name should be added.
*
* @param string $name
* @param string $value
* @param Sabre_VObject_ElementList $iterator
* @param array $parameters
*/
public function __construct($name, $value = null, $iterator = null) {
public function __construct($name, $value = null, array $parameters = array()) {
$name = strtoupper($name);
$group = null;
@ -113,13 +121,22 @@ class Sabre_VObject_Property extends Sabre_VObject_Element {
}
$this->name = $name;
$this->group = $group;
if (!is_null($iterator)) $this->iterator = $iterator;
$this->setValue($value);
foreach($parameters as $paramName => $paramValues) {
if (!is_array($paramValues)) {
$paramValues = array($paramValues);
}
foreach($paramValues as $paramValue) {
$this->add($paramName, $paramValue);
}
}
}
/**
* Updates the internal value
*
@ -180,7 +197,7 @@ class Sabre_VObject_Property extends Sabre_VObject_Element {
*
* You can call this method with the following syntaxes:
*
* add(Sabre_VObject_Parameter $element)
* add(Parameter $element)
* add(string $name, $value)
*
* The first version adds an Parameter
@ -192,24 +209,24 @@ class Sabre_VObject_Property extends Sabre_VObject_Element {
*/
public function add($item, $itemValue = null) {
if ($item instanceof Sabre_VObject_Parameter) {
if ($item instanceof Parameter) {
if (!is_null($itemValue)) {
throw new InvalidArgumentException('The second argument must not be specified, when passing a VObject');
throw new \InvalidArgumentException('The second argument must not be specified, when passing a VObject');
}
$item->parent = $this;
$this->parameters[] = $item;
} elseif(is_string($item)) {
if (!is_scalar($itemValue) && !is_null($itemValue)) {
throw new InvalidArgumentException('The second argument must be scalar');
throw new \InvalidArgumentException('The second argument must be scalar');
}
$parameter = new Sabre_VObject_Parameter($item,$itemValue);
$parameter = new Parameter($item,$itemValue);
$parameter->parent = $this;
$this->parameters[] = $parameter;
} else {
throw new InvalidArgumentException('The first argument must either be a Sabre_VObject_Element or a string');
throw new \InvalidArgumentException('The first argument must either be a Element or a string');
}
@ -240,7 +257,7 @@ class Sabre_VObject_Property extends Sabre_VObject_Element {
* Returns a parameter, or parameter list.
*
* @param string $name
* @return Sabre_VObject_Element
* @return Element
*/
public function offsetGet($name) {
@ -258,7 +275,7 @@ class Sabre_VObject_Property extends Sabre_VObject_Element {
} elseif (count($result)===1) {
return $result[0];
} else {
$result[0]->setIterator(new Sabre_VObject_ElementList($result));
$result[0]->setIterator(new ElementList($result));
return $result[0];
}
@ -277,21 +294,21 @@ class Sabre_VObject_Property extends Sabre_VObject_Element {
if (is_scalar($value)) {
if (!is_string($name))
throw new InvalidArgumentException('A parameter name must be specified. This means you cannot use the $array[]="string" to add parameters.');
throw new \InvalidArgumentException('A parameter name must be specified. This means you cannot use the $array[]="string" to add parameters.');
$this->offsetUnset($name);
$parameter = new Sabre_VObject_Parameter($name, $value);
$parameter = new Parameter($name, $value);
$parameter->parent = $this;
$this->parameters[] = $parameter;
} elseif ($value instanceof Sabre_VObject_Parameter) {
} elseif ($value instanceof Parameter) {
if (!is_null($name))
throw new InvalidArgumentException('Don\'t specify a parameter name if you\'re passing a Sabre_VObject_Parameter. Add using $array[]=$parameterObject.');
throw new \InvalidArgumentException('Don\'t specify a parameter name if you\'re passing a \\Sabre\\VObject\\Parameter. Add using $array[]=$parameterObject.');
$value->parent = $this;
$this->parameters[] = $value;
} else {
throw new InvalidArgumentException('You can only add parameters to the property object');
throw new \InvalidArgumentException('You can only add parameters to the property object');
}
}

View file

@ -1,5 +1,9 @@
<?php
namespace Sabre\VObject\Property;
use Sabre\VObject;
/**
* DateTime property
*
@ -13,13 +17,11 @@
* If you use the 'value' or properties directly, this object does not keep
* reference and results might appear incorrectly.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_Property_DateTime extends Sabre_VObject_Property {
class DateTime extends VObject\Property {
/**
* Local 'floating' time
@ -44,7 +46,7 @@ class Sabre_VObject_Property_DateTime extends Sabre_VObject_Property {
/**
* DateTime representation
*
* @var DateTime
* @var \DateTime
*/
protected $dateTime;
@ -58,11 +60,11 @@ class Sabre_VObject_Property_DateTime extends Sabre_VObject_Property {
/**
* Updates the Date and Time.
*
* @param DateTime $dt
* @param \DateTime $dt
* @param int $dateType
* @return void
*/
public function setDateTime(DateTime $dt, $dateType = self::LOCALTZ) {
public function setDateTime(\DateTime $dt, $dateType = self::LOCALTZ) {
switch($dateType) {
@ -73,7 +75,7 @@ class Sabre_VObject_Property_DateTime extends Sabre_VObject_Property {
$this->offsetSet('VALUE','DATE-TIME');
break;
case self::UTC :
$dt->setTimeZone(new DateTimeZone('UTC'));
$dt->setTimeZone(new \DateTimeZone('UTC'));
$this->setValue($dt->format('Ymd\\THis\\Z'));
$this->offsetUnset('VALUE');
$this->offsetUnset('TZID');
@ -93,7 +95,7 @@ class Sabre_VObject_Property_DateTime extends Sabre_VObject_Property {
$this->offsetSet('VALUE','DATE');
break;
default :
throw new InvalidArgumentException('You must pass a valid dateType constant');
throw new \InvalidArgumentException('You must pass a valid dateType constant');
}
$this->dateTime = $dt;
@ -106,7 +108,7 @@ class Sabre_VObject_Property_DateTime extends Sabre_VObject_Property {
*
* If no value was set, this method returns null.
*
* @return DateTime|null
* @return \DateTime|null
*/
public function getDateTime() {
@ -152,11 +154,11 @@ class Sabre_VObject_Property_DateTime extends Sabre_VObject_Property {
*
* @param string|null $propertyValue The string to parse (yymmdd or
* ymmddThhmmss, etc..)
* @param Sabre_VObject_Property|null $property The instance of the
* @param \Sabre\VObject\Property|null $property The instance of the
* property we're parsing.
* @return array
*/
static public function parseData($propertyValue, Sabre_VObject_Property $property = null) {
static public function parseData($propertyValue, VObject\Property $property = null) {
if (is_null($propertyValue)) {
return array(null, null);
@ -167,14 +169,14 @@ class Sabre_VObject_Property_DateTime extends Sabre_VObject_Property {
$regex = "/^$date(T$time(?P<isutc>Z)?)?$/";
if (!preg_match($regex, $propertyValue, $matches)) {
throw new InvalidArgumentException($propertyValue . ' is not a valid DateTime or Date string');
throw new \InvalidArgumentException($propertyValue . ' is not a valid \DateTime or Date string');
}
if (!isset($matches['hour'])) {
// Date-only
return array(
self::DATE,
new DateTime($matches['year'] . '-' . $matches['month'] . '-' . $matches['date'] . ' 00:00:00'),
new \DateTime($matches['year'] . '-' . $matches['month'] . '-' . $matches['date'] . ' 00:00:00', new \DateTimeZone('UTC')),
);
}
@ -187,8 +189,8 @@ class Sabre_VObject_Property_DateTime extends Sabre_VObject_Property {
$matches['second'];
if (isset($matches['isutc'])) {
$dt = new DateTime($dateStr,new DateTimeZone('UTC'));
$dt->setTimeZone(new DateTimeZone('UTC'));
$dt = new \DateTime($dateStr,new \DateTimeZone('UTC'));
$dt->setTimeZone(new \DateTimeZone('UTC'));
return array(
self::UTC,
$dt
@ -198,9 +200,12 @@ class Sabre_VObject_Property_DateTime extends Sabre_VObject_Property {
// Finding the timezone.
$tzid = $property['TZID'];
if (!$tzid) {
// This was a floating time string. This implies we use the
// timezone from date_default_timezone_set / date.timezone ini
// setting.
return array(
self::LOCAL,
new DateTime($dateStr)
new \DateTime($dateStr)
);
}
@ -210,12 +215,12 @@ class Sabre_VObject_Property_DateTime extends Sabre_VObject_Property {
$root = $root->parent;
}
if ($root->name === 'VCALENDAR') {
$tz = Sabre_VObject_TimeZoneUtil::getTimeZone((string)$tzid, $root);
$tz = VObject\TimeZoneUtil::getTimeZone((string)$tzid, $root);
} else {
$tz = Sabre_VObject_TimeZoneUtil::getTimeZone((string)$tzid);
$tz = VObject\TimeZoneUtil::getTimeZone((string)$tzid);
}
$dt = new DateTime($dateStr, $tz);
$dt = new \DateTime($dateStr, $tz);
$dt->setTimeZone($tz);
return array(

View file

@ -1,5 +1,9 @@
<?php
namespace Sabre\VObject\Property;
use Sabre\VObject;
/**
* Multi-DateTime property
*
@ -13,13 +17,11 @@
* If you use the 'value' or properties directly, this object does not keep
* reference and results might appear incorrectly.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_Property_MultiDateTime extends Sabre_VObject_Property {
class MultiDateTime extends VObject\Property {
/**
* DateTime representation
@ -31,7 +33,7 @@ class Sabre_VObject_Property_MultiDateTime extends Sabre_VObject_Property {
/**
* dateType
*
* This is one of the Sabre_VObject_Property_DateTime constants.
* This is one of the Sabre\VObject\Property\DateTime constants.
*
* @var int
*/
@ -44,17 +46,17 @@ class Sabre_VObject_Property_MultiDateTime extends Sabre_VObject_Property {
* @param int $dateType
* @return void
*/
public function setDateTimes(array $dt, $dateType = Sabre_VObject_Property_DateTime::LOCALTZ) {
public function setDateTimes(array $dt, $dateType = VObject\Property\DateTime::LOCALTZ) {
foreach($dt as $i)
if (!$i instanceof DateTime)
throw new InvalidArgumentException('You must pass an array of DateTime objects');
if (!$i instanceof \DateTime)
throw new \InvalidArgumentException('You must pass an array of DateTime objects');
$this->offsetUnset('VALUE');
$this->offsetUnset('TZID');
switch($dateType) {
case Sabre_VObject_Property_DateTime::LOCAL :
case DateTime::LOCAL :
$val = array();
foreach($dt as $i) {
$val[] = $i->format('Ymd\\THis');
@ -62,16 +64,16 @@ class Sabre_VObject_Property_MultiDateTime extends Sabre_VObject_Property {
$this->setValue(implode(',',$val));
$this->offsetSet('VALUE','DATE-TIME');
break;
case Sabre_VObject_Property_DateTime::UTC :
case DateTime::UTC :
$val = array();
foreach($dt as $i) {
$i->setTimeZone(new DateTimeZone('UTC'));
$i->setTimeZone(new \DateTimeZone('UTC'));
$val[] = $i->format('Ymd\\THis\\Z');
}
$this->setValue(implode(',',$val));
$this->offsetSet('VALUE','DATE-TIME');
break;
case Sabre_VObject_Property_DateTime::LOCALTZ :
case DateTime::LOCALTZ :
$val = array();
foreach($dt as $i) {
$val[] = $i->format('Ymd\\THis');
@ -80,7 +82,7 @@ class Sabre_VObject_Property_MultiDateTime extends Sabre_VObject_Property {
$this->offsetSet('VALUE','DATE-TIME');
$this->offsetSet('TZID', $dt[0]->getTimeZone()->getName());
break;
case Sabre_VObject_Property_DateTime::DATE :
case DateTime::DATE :
$val = array();
foreach($dt as $i) {
$val[] = $i->format('Ymd');
@ -89,7 +91,7 @@ class Sabre_VObject_Property_MultiDateTime extends Sabre_VObject_Property {
$this->offsetSet('VALUE','DATE');
break;
default :
throw new InvalidArgumentException('You must pass a valid dateType constant');
throw new \InvalidArgumentException('You must pass a valid dateType constant');
}
$this->dateTimes = $dt;
@ -121,7 +123,7 @@ class Sabre_VObject_Property_MultiDateTime extends Sabre_VObject_Property {
list(
$type,
$dt
) = Sabre_VObject_Property_DateTime::parseData($val, $this);
) = DateTime::parseData($val, $this);
$dts[] = $dt;
$this->dateType = $type;
}
@ -154,7 +156,7 @@ class Sabre_VObject_Property_MultiDateTime extends Sabre_VObject_Property {
list(
$type,
$dt
) = Sabre_VObject_Property_DateTime::parseData($val, $this);
) = DateTime::parseData($val, $this);
$dts[] = $dt;
$this->dateType = $type;
}

View file

@ -1,5 +1,7 @@
<?php
namespace Sabre\VObject;
/**
* VCALENDAR/VCARD reader
*
@ -8,19 +10,17 @@
* TODO: this class currently completely works 'statically'. This is pointless,
* and defeats OOP principals. Needs refactoring in a future version.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_Reader {
class Reader {
/**
* Parses the file and returns the top component
*
* @param string $data
* @return Sabre_VObject_Element
* @return Element
*/
static function read($data) {
@ -59,7 +59,7 @@ class Sabre_VObject_Reader {
* to traverse.
*
* @param array $lines
* @return Sabre_VObject_Element
* @return Element
*/
static private function readLine(&$lines) {
@ -71,7 +71,7 @@ class Sabre_VObject_Reader {
if (stripos($line,"BEGIN:")===0) {
$componentName = strtoupper(substr($line,6));
$obj = Sabre_VObject_Component::create($componentName);
$obj = Component::create($componentName);
$nextLine = current($lines);
@ -82,13 +82,13 @@ class Sabre_VObject_Reader {
$nextLine = current($lines);
if ($nextLine===false)
throw new Sabre_VObject_ParseException('Invalid VObject. Document ended prematurely.');
throw new ParseException('Invalid VObject. Document ended prematurely.');
}
// Checking component name of the 'END:' line.
if (substr($nextLine,4)!==$obj->name) {
throw new Sabre_VObject_ParseException('Invalid VObject, expected: "END:' . $obj->name . '" got: "' . $nextLine . '"');
throw new ParseException('Invalid VObject, expected: "END:' . $obj->name . '" got: "' . $nextLine . '"');
}
next($lines);
@ -107,7 +107,7 @@ class Sabre_VObject_Reader {
$result = preg_match($regex,$line,$matches);
if (!$result) {
throw new Sabre_VObject_ParseException('Invalid VObject, line ' . ($lineNr+1) . ' did not follow the icalendar/vcard format');
throw new ParseException('Invalid VObject, line ' . ($lineNr+1) . ' did not follow the icalendar/vcard format');
}
$propertyName = strtoupper($matches['name']);
@ -119,7 +119,7 @@ class Sabre_VObject_Reader {
}
}, $matches['value']);
$obj = Sabre_VObject_Property::create($propertyName, $propertyValue);
$obj = Property::create($propertyName, $propertyValue);
if ($matches['parameters']) {
@ -137,7 +137,7 @@ class Sabre_VObject_Reader {
/**
* Reads a parameter list from a property
*
* This method returns an array of Sabre_VObject_Parameter
* This method returns an array of Parameter
*
* @param string $parameters
* @return array
@ -171,7 +171,7 @@ class Sabre_VObject_Reader {
}
}, $value);
$params[] = new Sabre_VObject_Parameter($match['paramName'], $value);
$params[] = new Parameter($match['paramName'], $value);
}

View file

@ -1,5 +1,7 @@
<?php
namespace Sabre\VObject;
/**
* This class is used to determine new for a recurring event, when the next
* events occur.
@ -37,13 +39,11 @@
* you may get unexpected results. The effect is that in some applications the
* specified recurrence may look incorrect, or is missing.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_RecurrenceIterator implements Iterator {
class RecurrenceIterator implements \Iterator {
/**
* The initial event date
@ -82,7 +82,7 @@ class Sabre_VObject_RecurrenceIterator implements Iterator {
/**
* Base event
*
* @var Sabre_VObject_Component_VEvent
* @var Component\VEvent
*/
public $baseEvent;
@ -97,7 +97,7 @@ class Sabre_VObject_RecurrenceIterator implements Iterator {
/**
* list of events that are 'overridden'.
*
* This is an array of Sabre_VObject_Component_VEvent objects.
* This is an array of Component\VEvent objects.
*
* @var array
*/
@ -281,7 +281,7 @@ class Sabre_VObject_RecurrenceIterator implements Iterator {
* If the current iteration of the event is an overriden event, this
* property will hold the VObject
*
* @var Sabre_VObject_Component
* @var Component
*/
private $currentOverriddenEvent;
@ -300,14 +300,14 @@ class Sabre_VObject_RecurrenceIterator implements Iterator {
* You should pass a VCALENDAR component, as well as the UID of the event
* we're going to traverse.
*
* @param Sabre_VObject_Component $vcal
* @param Component $vcal
* @param string|null $uid
*/
public function __construct(Sabre_VObject_Component $vcal, $uid=null) {
public function __construct(Component $vcal, $uid=null) {
if (is_null($uid)) {
if ($vcal->name === 'VCALENDAR') {
throw new InvalidArgumentException('If you pass a VCALENDAR object, you must pass a uid argument as well');
throw new \InvalidArgumentException('If you pass a VCALENDAR object, you must pass a uid argument as well');
}
$components = array($vcal);
$uid = (string)$vcal->uid;
@ -325,7 +325,7 @@ class Sabre_VObject_RecurrenceIterator implements Iterator {
}
}
if (!$this->baseEvent) {
throw new InvalidArgumentException('Could not find a base event with uid: ' . $uid);
throw new \InvalidArgumentException('Could not find a base event with uid: ' . $uid);
}
$this->startDate = clone $this->baseEvent->DTSTART->getDateTime();
@ -336,8 +336,8 @@ class Sabre_VObject_RecurrenceIterator implements Iterator {
} else {
$this->endDate = clone $this->startDate;
if (isset($this->baseEvent->DURATION)) {
$this->endDate->add(Sabre_VObject_DateTimeParser::parse($this->baseEvent->DURATION->value));
} elseif ($this->baseEvent->DTSTART->getDateType()===Sabre_VObject_Property_DateTime::DATE) {
$this->endDate->add(DateTimeParser::parse($this->baseEvent->DURATION->value));
} elseif ($this->baseEvent->DTSTART->getDateType()===Property\DateTime::DATE) {
$this->endDate->modify('+1 day');
}
}
@ -362,14 +362,14 @@ class Sabre_VObject_RecurrenceIterator implements Iterator {
strtolower($value),
array('secondly','minutely','hourly','daily','weekly','monthly','yearly')
)) {
throw new InvalidArgumentException('Unknown value for FREQ=' . strtoupper($value));
throw new \InvalidArgumentException('Unknown value for FREQ=' . strtoupper($value));
}
$this->frequency = strtolower($value);
break;
case 'UNTIL' :
$this->until = Sabre_VObject_DateTimeParser::parse($value);
$this->until = DateTimeParser::parse($value);
break;
case 'COUNT' :
@ -431,7 +431,7 @@ class Sabre_VObject_RecurrenceIterator implements Iterator {
foreach(explode(',', (string)$exDate) as $exceptionDate) {
$this->exceptionDates[] =
Sabre_VObject_DateTimeParser::parse($exceptionDate, $this->startDate->getTimeZone());
DateTimeParser::parse($exceptionDate, $this->startDate->getTimeZone());
}
@ -489,7 +489,7 @@ class Sabre_VObject_RecurrenceIterator implements Iterator {
*
* This method always returns a cloned instance.
*
* @return Sabre_VObject_Component_VEvent
* @return Component\VEvent
*/
public function getEventObject() {
@ -565,7 +565,7 @@ class Sabre_VObject_RecurrenceIterator implements Iterator {
* @param DateTime $dt
* @return void
*/
public function fastForward(DateTime $dt) {
public function fastForward(\DateTime $dt) {
while($this->valid() && $this->getDTEnd() <= $dt) {
$this->next();

View file

@ -1,18 +1,18 @@
<?php
namespace Sabre\VObject;
/**
* Time zone name translation
*
* This file translates well-known time zone names into "Olson database" time zone names.
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Frank Edelhaeuser (fedel@users.sourceforge.net)
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_TimeZoneUtil {
class TimeZoneUtil {
public static $map = array(
@ -297,20 +297,20 @@ class Sabre_VObject_TimeZoneUtil {
* If the lookup fails, this method will return UTC.
*
* @param string $tzid
* @param Sabre_VObject_Component $vcalendar
* @param Sabre\VObject\Component $vcalendar
* @return DateTimeZone
*/
static public function getTimeZone($tzid, Sabre_VObject_Component $vcalendar = null) {
static public function getTimeZone($tzid, Component $vcalendar = null) {
// First we will just see if the tzid is a support timezone identifier.
try {
return new DateTimeZone($tzid);
return new \DateTimeZone($tzid);
} catch (\Exception $e) {
}
// Next, we check if the tzid is somewhere in our tzid map.
if (isset(self::$map[$tzid])) {
return new DateTimeZone(self::$map[$tzid]);
return new \DateTimeZone(self::$map[$tzid]);
}
if ($vcalendar) {
@ -323,7 +323,7 @@ class Sabre_VObject_TimeZoneUtil {
// Some clients add 'X-LIC-LOCATION' with the olson name.
if (isset($vtimezone->{'X-LIC-LOCATION'})) {
try {
return new DateTimeZone($vtimezone->{'X-LIC-LOCATION'});
return new \DateTimeZone($vtimezone->{'X-LIC-LOCATION'});
} catch (\Exception $e) {
}
@ -332,7 +332,7 @@ class Sabre_VObject_TimeZoneUtil {
// answer for.
if (isset($vtimezone->{'X-MICROSOFT-CDO-TZID'})) {
if (isset(self::$microsoftExchangeMap[(int)$vtimezone->{'X-MICROSOFT-CDO-TZID'}->value])) {
return new DateTimeZone(self::$microsoftExchangeMap[(int)$vtimezone->{'X-MICROSOFT-CDO-TZID'}->value]);
return new \DateTimeZone(self::$microsoftExchangeMap[(int)$vtimezone->{'X-MICROSOFT-CDO-TZID'}->value]);
}
}
}
@ -342,7 +342,7 @@ class Sabre_VObject_TimeZoneUtil {
}
// If we got all the way here, we default to UTC.
return new DateTimeZone(date_default_timezone_get());
return new \DateTimeZone(date_default_timezone_get());
}

View file

@ -1,20 +1,20 @@
<?php
namespace Sabre\VObject;
/**
* This class contains the version number for the VObject package
*
* @package Sabre
* @subpackage VObject
* @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved.
* @author Evert Pot (http://www.rooftopsolutions.nl/)
* @license http://code.google.com/p/sabredav/wiki/License Modified BSD License
*/
class Sabre_VObject_Version {
class Version {
/**
* Full version number
*/
const VERSION = '1.3.4';
const VERSION = '2.0';
/**
* Stability : alpha, beta, stable

View file

@ -1,11 +1,16 @@
<?php
class Sabre_VObject_Component_VAlarmTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject\Component;
use Sabre\VObject\Component;
use DateTime;
class VAlarmTest extends \PHPUnit_Framework_TestCase {
/**
* @dataProvider timeRangeTestData
*/
public function testInTimeRange(Sabre_VObject_Component_VAlarm $valarm,$start,$end,$outcome) {
public function testInTimeRange(VAlarm $valarm,$start,$end,$outcome) {
$this->assertEquals($outcome, $valarm->isInTimeRange($start, $end));
@ -16,7 +21,7 @@ class Sabre_VObject_Component_VAlarmTest extends PHPUnit_Framework_TestCase {
$tests = array();
// Hard date and time
$valarm1 = Sabre_VObject_Component::create('VALARM');
$valarm1 = Component::create('VALARM');
$valarm1->TRIGGER = '20120312T130000Z';
$valarm1->TRIGGER['VALUE'] = 'DATE-TIME';
@ -24,11 +29,11 @@ class Sabre_VObject_Component_VAlarmTest extends PHPUnit_Framework_TestCase {
$tests[] = array($valarm1, new DateTime('2012-03-01 01:00:00'), new DateTime('2012-03-10 01:00:00'), false);
// Relation to start time of event
$valarm2 = Sabre_VObject_Component::create('VALARM');
$valarm2 = Component::create('VALARM');
$valarm2->TRIGGER = '-P1D';
$valarm2->TRIGGER['VALUE'] = 'DURATION';
$vevent2 = Sabre_VObject_Component::create('VEVENT');
$vevent2 = Component::create('VEVENT');
$vevent2->DTSTART = '20120313T130000Z';
$vevent2->add($valarm2);
@ -36,12 +41,12 @@ class Sabre_VObject_Component_VAlarmTest extends PHPUnit_Framework_TestCase {
$tests[] = array($valarm2, new DateTime('2012-03-01 01:00:00'), new DateTime('2012-03-10 01:00:00'), false);
// Relation to end time of event
$valarm3 = Sabre_VObject_Component::create('VALARM');
$valarm3 = Component::create('VALARM');
$valarm3->TRIGGER = '-P1D';
$valarm3->TRIGGER['VALUE'] = 'DURATION';
$valarm3->TRIGGER['RELATED']= 'END';
$vevent3 = Sabre_VObject_Component::create('VEVENT');
$vevent3 = Component::create('VEVENT');
$vevent3->DTSTART = '20120301T130000Z';
$vevent3->DTEND = '20120401T130000Z';
$vevent3->add($valarm3);
@ -50,12 +55,12 @@ class Sabre_VObject_Component_VAlarmTest extends PHPUnit_Framework_TestCase {
$tests[] = array($valarm3, new DateTime('2012-03-25 01:00:00'), new DateTime('2012-04-05 01:00:00'), true);
// Relation to end time of todo
$valarm4 = Sabre_VObject_Component::create('VALARM');
$valarm4 = Component::create('VALARM');
$valarm4->TRIGGER = '-P1D';
$valarm4->TRIGGER['VALUE'] = 'DURATION';
$valarm4->TRIGGER['RELATED']= 'END';
$vtodo4 = Sabre_VObject_Component::create('VTODO');
$vtodo4 = Component::create('VTODO');
$vtodo4->DTSTART = '20120301T130000Z';
$vtodo4->DUE = '20120401T130000Z';
$vtodo4->add($valarm4);
@ -64,25 +69,25 @@ class Sabre_VObject_Component_VAlarmTest extends PHPUnit_Framework_TestCase {
$tests[] = array($valarm4, new DateTime('2012-03-25 01:00:00'), new DateTime('2012-04-05 01:00:00'), true);
// Relation to start time of event + repeat
$valarm5 = Sabre_VObject_Component::create('VALARM');
$valarm5 = Component::create('VALARM');
$valarm5->TRIGGER = '-P1D';
$valarm5->TRIGGER['VALUE'] = 'DURATION';
$valarm5->REPEAT = 10;
$valarm5->DURATION = 'P1D';
$vevent5 = Sabre_VObject_Component::create('VEVENT');
$vevent5 = Component::create('VEVENT');
$vevent5->DTSTART = '20120301T130000Z';
$vevent5->add($valarm5);
$tests[] = array($valarm5, new DateTime('2012-03-09 01:00:00'), new DateTime('2012-03-10 01:00:00'), true);
// Relation to start time of event + duration, but no repeat
$valarm6 = Sabre_VObject_Component::create('VALARM');
$valarm6 = Component::create('VALARM');
$valarm6->TRIGGER = '-P1D';
$valarm6->TRIGGER['VALUE'] = 'DURATION';
$valarm6->DURATION = 'P1D';
$vevent6 = Sabre_VObject_Component::create('VEVENT');
$vevent6 = Component::create('VEVENT');
$vevent6->DTSTART = '20120313T130000Z';
$vevent6->add($valarm6);
@ -91,12 +96,12 @@ class Sabre_VObject_Component_VAlarmTest extends PHPUnit_Framework_TestCase {
// Relation to end time of event (DURATION instead of DTEND)
$valarm7 = Sabre_VObject_Component::create('VALARM');
$valarm7 = Component::create('VALARM');
$valarm7->TRIGGER = '-P1D';
$valarm7->TRIGGER['VALUE'] = 'DURATION';
$valarm7->TRIGGER['RELATED']= 'END';
$vevent7 = Sabre_VObject_Component::create('VEVENT');
$vevent7 = Component::create('VEVENT');
$vevent7->DTSTART = '20120301T130000Z';
$vevent7->DURATION = 'P30D';
$vevent7->add($valarm7);
@ -105,12 +110,12 @@ class Sabre_VObject_Component_VAlarmTest extends PHPUnit_Framework_TestCase {
$tests[] = array($valarm7, new DateTime('2012-03-25 01:00:00'), new DateTime('2012-04-05 01:00:00'), true);
// Relation to end time of event (No DTEND or DURATION)
$valarm7 = Sabre_VObject_Component::create('VALARM');
$valarm7 = Component::create('VALARM');
$valarm7->TRIGGER = '-P1D';
$valarm7->TRIGGER['VALUE'] = 'DURATION';
$valarm7->TRIGGER['RELATED']= 'END';
$vevent7 = Sabre_VObject_Component::create('VEVENT');
$vevent7 = Component::create('VEVENT');
$vevent7->DTSTART = '20120301T130000Z';
$vevent7->add($valarm7);
@ -122,15 +127,15 @@ class Sabre_VObject_Component_VAlarmTest extends PHPUnit_Framework_TestCase {
}
/**
* @expectedException Sabre_DAV_Exception
* @expectedException LogicException
*/
public function testInTimeRangeInvalidComponent() {
$valarm = Sabre_VObject_Component::create('VALARM');
$valarm = Component::create('VALARM');
$valarm->TRIGGER = '-P1D';
$valarm->TRIGGER['RELATED'] = 'END';
$vjournal = Sabre_VObject_Component::create('VJOURNAL');
$vjournal = Component::create('VJOURNAL');
$vjournal->add($valarm);
$valarm->isInTimeRange(new DateTime('2012-02-25 01:00:00'), new DateTime('2012-03-05 01:00:00'));

View file

@ -1,20 +1,24 @@
<?php
class Sabre_VObject_Component_VCalendarTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject\Component;
use Sabre\VObject;
class VCalendarTest extends \PHPUnit_Framework_TestCase {
/**
* @dataProvider expandData
*/
public function testExpand($input, $output) {
$vcal = Sabre_VObject_Reader::read($input);
$vcal = VObject\Reader::read($input);
$vcal->expand(
new DateTime('2011-12-01'),
new DateTime('2011-12-31')
new \DateTime('2011-12-01'),
new \DateTime('2011-12-31')
);
// This will normalize the output
$output = Sabre_VObject_Reader::read($output)->serialize();
$output = VObject\Reader::read($output)->serialize();
$this->assertEquals($output, $vcal->serialize());
@ -229,10 +233,10 @@ DTSTART;VALUE=DATE:20111202
END:VEVENT
END:VCALENDAR
';
$vcal = Sabre_VObject_Reader::read($input);
$vcal = VObject\Reader::read($input);
$vcal->expand(
new DateTime('2011-12-01'),
new DateTime('2011-12-31')
new \DateTime('2011-12-01'),
new \DateTime('2011-12-31')
);
}

View file

@ -0,0 +1,100 @@
<?php
namespace Sabre\VObject\Component;
use Sabre\VObject;
class VCardTest extends \PHPUnit_Framework_TestCase {
/**
* @dataProvider validateData
*/
function testValidate($input, $expectedWarnings, $expectedRepairedOutput) {
$vcard = VObject\Reader::read($input);
$warnings = $vcard->validate();
$warnMsg = array();
foreach($warnings as $warning) {
$warnMsg[] = $warning['message'];
}
$this->assertEquals($expectedWarnings, $warnMsg);
$vcard->validate(VObject\Component::REPAIR);
$this->assertEquals(
$expectedRepairedOutput,
$vcard->serialize()
);
}
public function validateData() {
$tests = array();
// Correct
$tests[] = array(
"BEGIN:VCARD\r\nVERSION:4.0\r\nFN:John Doe\r\nEND:VCARD\r\n",
array(),
"BEGIN:VCARD\r\nVERSION:4.0\r\nFN:John Doe\r\nEND:VCARD\r\n",
);
// No VERSION
$tests[] = array(
"BEGIN:VCARD\r\nFN:John Doe\r\nEND:VCARD\r\n",
array(
'The VERSION property must appear in the VCARD component exactly 1 time',
),
"BEGIN:VCARD\r\nVERSION:4.0\r\nFN:John Doe\r\nEND:VCARD\r\n",
);
// Unknown version
$tests[] = array(
"BEGIN:VCARD\r\nVERSION:2.2\r\nFN:John Doe\r\nEND:VCARD\r\n",
array(
'Only vcard version 4.0 (RFC6350), version 3.0 (RFC2426) or version 2.1 (icm-vcard-2.1) are supported.',
),
"BEGIN:VCARD\r\nVERSION:4.0\r\nFN:John Doe\r\nEND:VCARD\r\n",
);
// No FN
$tests[] = array(
"BEGIN:VCARD\r\nVERSION:4.0\r\nEND:VCARD\r\n",
array(
'The FN property must appear in the VCARD component exactly 1 time',
),
"BEGIN:VCARD\r\nVERSION:4.0\r\nEND:VCARD\r\n",
);
// No FN, N fallback
$tests[] = array(
"BEGIN:VCARD\r\nVERSION:4.0\r\nN:Doe;John;;;;;\r\nEND:VCARD\r\n",
array(
'The FN property must appear in the VCARD component exactly 1 time',
),
"BEGIN:VCARD\r\nVERSION:4.0\r\nN:Doe;John;;;;;\r\nFN:John Doe\r\nEND:VCARD\r\n",
);
// No FN, N fallback, no first name
$tests[] = array(
"BEGIN:VCARD\r\nVERSION:4.0\r\nN:Doe;;;;;;\r\nEND:VCARD\r\n",
array(
'The FN property must appear in the VCARD component exactly 1 time',
),
"BEGIN:VCARD\r\nVERSION:4.0\r\nN:Doe;;;;;;\r\nFN:Doe\r\nEND:VCARD\r\n",
);
// No FN, ORG fallback
$tests[] = array(
"BEGIN:VCARD\r\nVERSION:4.0\r\nORG:Acme Co.\r\nEND:VCARD\r\n",
array(
'The FN property must appear in the VCARD component exactly 1 time',
),
"BEGIN:VCARD\r\nVERSION:4.0\r\nORG:Acme Co.\r\nFN:Acme Co.\r\nEND:VCARD\r\n",
);
return $tests;
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace Sabre\VObject\Component;
use Sabre\VObject;
class VEventTest extends \PHPUnit_Framework_TestCase {
/**
* @dataProvider timeRangeTestData
*/
public function testInTimeRange(VEvent $vevent,$start,$end,$outcome) {
$this->assertEquals($outcome, $vevent->isInTimeRange($start, $end));
}
public function timeRangeTestData() {
$tests = array();
$vevent = new VEvent('VEVENT');
$vevent->DTSTART = '20111223T120000Z';
$tests[] = array($vevent, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vevent, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$vevent2 = clone $vevent;
$vevent2->DTEND = '20111225T120000Z';
$tests[] = array($vevent2, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vevent2, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$vevent3 = clone $vevent;
$vevent3->DURATION = 'P1D';
$tests[] = array($vevent3, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vevent3, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$vevent4 = clone $vevent;
$vevent4->DTSTART = '20111225';
$vevent4->DTSTART['VALUE'] = 'DATE';
$tests[] = array($vevent4, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vevent4, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
// Event with no end date should be treated as lasting the entire day.
$tests[] = array($vevent4, new \DateTime('2011-12-25 16:00:00'), new \DateTime('2011-12-25 17:00:00'), true);
$vevent5 = clone $vevent;
$vevent5->DURATION = 'P1D';
$vevent5->RRULE = 'FREQ=YEARLY';
$tests[] = array($vevent5, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vevent5, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$tests[] = array($vevent5, new \DateTime('2013-12-01'), new \DateTime('2013-12-31'), true);
$vevent6 = clone $vevent;
$vevent6->DTSTART = '20111225';
$vevent6->DTSTART['VALUE'] = 'DATE';
$vevent6->DTEND = '20111225';
$vevent6->DTEND['VALUE'] = 'DATE';
$tests[] = array($vevent6, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vevent6, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
// Added this test to ensure that recurrence rules with no DTEND also
// get checked for the entire day.
$vevent7 = clone $vevent;
$vevent7->DTSTART = '20120101';
$vevent7->DTSTART['VALUE'] = 'DATE';
$vevent7->RRULE = 'FREQ=MONTHLY';
$tests[] = array($vevent7, new \DateTime('2012-02-01 15:00:00'), new \DateTime('2012-02-02'), true);
return $tests;
}
}

View file

@ -0,0 +1,41 @@
<?php
namespace Sabre\VObject\Component;
use Sabre\VObject\Component;
class VJournalTest extends \PHPUnit_Framework_TestCase {
/**
* @dataProvider timeRangeTestData
*/
public function testInTimeRange(VJournal $vtodo,$start,$end,$outcome) {
$this->assertEquals($outcome, $vtodo->isInTimeRange($start, $end));
}
public function timeRangeTestData() {
$tests = array();
$vjournal = Component::create('VJOURNAL');
$vjournal->DTSTART = '20111223T120000Z';
$tests[] = array($vjournal, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vjournal, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$vjournal2 = Component::create('VJOURNAL');
$vjournal2->DTSTART = '20111223';
$vjournal2->DTSTART['VALUE'] = 'DATE';
$tests[] = array($vjournal2, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vjournal2, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$vjournal3 = Component::create('VJOURNAL');
$tests[] = array($vjournal3, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), false);
$tests[] = array($vjournal3, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
return $tests;
}
}

View file

@ -0,0 +1,67 @@
<?php
namespace Sabre\VObject\Component;
use Sabre\VObject\Component;
class VTodoTest extends \PHPUnit_Framework_TestCase {
/**
* @dataProvider timeRangeTestData
*/
public function testInTimeRange(VTodo $vtodo,$start,$end,$outcome) {
$this->assertEquals($outcome, $vtodo->isInTimeRange($start, $end));
}
public function timeRangeTestData() {
$tests = array();
$vtodo = Component::create('VTODO');
$vtodo->DTSTART = '20111223T120000Z';
$tests[] = array($vtodo, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vtodo, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$vtodo2 = clone $vtodo;
$vtodo2->DURATION = 'P1D';
$tests[] = array($vtodo2, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vtodo2, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$vtodo3 = clone $vtodo;
$vtodo3->DUE = '20111225';
$tests[] = array($vtodo3, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vtodo3, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$vtodo4 = Component::create('VTODO');
$vtodo4->DUE = '20111225';
$tests[] = array($vtodo4, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vtodo4, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$vtodo5 = Component::create('VTODO');
$vtodo5->COMPLETED = '20111225';
$tests[] = array($vtodo5, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vtodo5, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$vtodo6 = Component::create('VTODO');
$vtodo6->CREATED = '20111225';
$tests[] = array($vtodo6, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vtodo6, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$vtodo7 = Component::create('VTODO');
$vtodo7->CREATED = '20111225';
$vtodo7->COMPLETED = '20111226';
$tests[] = array($vtodo7, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vtodo7, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), false);
$vtodo7 = Component::create('VTODO');
$tests[] = array($vtodo7, new \DateTime('2011-01-01'), new \DateTime('2012-01-01'), true);
$tests[] = array($vtodo7, new \DateTime('2011-01-01'), new \DateTime('2011-11-01'), true);
return $tests;
}
}

View file

@ -1,22 +1,24 @@
<?php
class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
class ComponentTest extends \PHPUnit_Framework_TestCase {
function testIterate() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$sub = new Sabre_VObject_Component('VEVENT');
$sub = new Component('VEVENT');
$comp->children[] = $sub;
$sub = new Sabre_VObject_Component('VTODO');
$sub = new Component('VTODO');
$comp->children[] = $sub;
$count = 0;
foreach($comp->children() as $key=>$subcomponent) {
$count++;
$this->assertInstanceOf('Sabre_VObject_Component',$subcomponent);
$this->assertInstanceOf('Sabre\\VObject\\Component',$subcomponent);
}
$this->assertEquals(2,$count);
@ -26,16 +28,16 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
function testMagicGet() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$sub = new Sabre_VObject_Component('VEVENT');
$sub = new Component('VEVENT');
$comp->children[] = $sub;
$sub = new Sabre_VObject_Component('VTODO');
$sub = new Component('VTODO');
$comp->children[] = $sub;
$event = $comp->vevent;
$this->assertInstanceOf('Sabre_VObject_Component', $event);
$this->assertInstanceOf('Sabre\\VObject\\Component', $event);
$this->assertEquals('VEVENT', $event->name);
$this->assertInternalType('null', $comp->vjournal);
@ -44,15 +46,15 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
function testMagicGetGroups() {
$comp = new Sabre_VObject_Component('VCARD');
$comp = new Component('VCARD');
$sub = new Sabre_VObject_Property('GROUP1.EMAIL','1@1.com');
$sub = new Property('GROUP1.EMAIL','1@1.com');
$comp->children[] = $sub;
$sub = new Sabre_VObject_Property('GROUP2.EMAIL','2@2.com');
$sub = new Property('GROUP2.EMAIL','2@2.com');
$comp->children[] = $sub;
$sub = new Sabre_VObject_Property('EMAIL','3@3.com');
$sub = new Property('EMAIL','3@3.com');
$comp->children[] = $sub;
$emails = $comp->email;
@ -70,12 +72,12 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
function testMagicIsset() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$sub = new Sabre_VObject_Component('VEVENT');
$sub = new Component('VEVENT');
$comp->children[] = $sub;
$sub = new Sabre_VObject_Component('VTODO');
$sub = new Component('VTODO');
$comp->children[] = $sub;
$this->assertTrue(isset($comp->vevent));
@ -86,10 +88,10 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
function testMagicSetScalar() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$comp->myProp = 'myValue';
$this->assertInstanceOf('Sabre_VObject_Property',$comp->MYPROP);
$this->assertInstanceOf('Sabre\\VObject\\Property',$comp->MYPROP);
$this->assertEquals('myValue',$comp->MYPROP->value);
@ -97,22 +99,22 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
function testMagicSetScalarTwice() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$comp->myProp = 'myValue';
$comp->myProp = 'myValue';
$this->assertEquals(1,count($comp->children));
$this->assertInstanceOf('Sabre_VObject_Property',$comp->MYPROP);
$this->assertInstanceOf('Sabre\\VObject\\Property',$comp->MYPROP);
$this->assertEquals('myValue',$comp->MYPROP->value);
}
function testMagicSetComponent() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
// Note that 'myProp' is ignored here.
$comp->myProp = new Sabre_VObject_Component('VEVENT');
$comp->myProp = new Component('VEVENT');
$this->assertEquals(1, count($comp->children));
@ -122,10 +124,10 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
function testMagicSetTwice() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$comp->VEVENT = new Sabre_VObject_Component('VEVENT');
$comp->VEVENT = new Sabre_VObject_Component('VEVENT');
$comp->VEVENT = new Component('VEVENT');
$comp->VEVENT = new Component('VEVENT');
$this->assertEquals(1, count($comp->children));
@ -135,9 +137,9 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
function testArrayAccessGet() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$event = new Sabre_VObject_Component('VEVENT');
$event = new Component('VEVENT');
$event->summary = 'Event 1';
$comp->add($event);
@ -148,16 +150,16 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
$comp->add($event2);
$this->assertEquals(2,count($comp->children()));
$this->assertTrue($comp->vevent[1] instanceof Sabre_VObject_Component);
$this->assertTrue($comp->vevent[1] instanceof Component);
$this->assertEquals('Event 2', (string)$comp->vevent[1]->summary);
}
function testArrayAccessExists() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$event = new Sabre_VObject_Component('VEVENT');
$event = new Component('VEVENT');
$event->summary = 'Event 1';
$comp->add($event);
@ -177,7 +179,7 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
*/
function testArrayAccessSet() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$comp['hey'] = 'hi there';
}
@ -186,30 +188,51 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
*/
function testArrayAccessUnset() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
unset($comp[0]);
}
function testAddScalar() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$comp->add('myprop','value');
$this->assertEquals(1, count($comp->children));
$this->assertTrue($comp->children[0] instanceof Sabre_VObject_Property);
$this->assertTrue($comp->children[0] instanceof Property);
$this->assertEquals('MYPROP',$comp->children[0]->name);
$this->assertEquals('value',$comp->children[0]->value);
}
function testAddScalarParams() {
$comp = Component::create('VCALENDAR');
$comp->add('myprop','value',array('param1'=>'value1'));
$this->assertEquals(1, count($comp->children));
$this->assertTrue($comp->children[0] instanceof Property);
$this->assertEquals('MYPROP',$comp->children[0]->name);
$this->assertEquals('value',$comp->children[0]->value);
$this->assertEquals(1, count($comp->children[0]->parameters));
$this->assertTrue($comp->children[0]->parameters[0] instanceof Parameter);
$this->assertEquals('PARAM1',$comp->children[0]->parameters[0]->name);
$this->assertEquals('value1',$comp->children[0]->parameters[0]->value);
}
function testAddComponent() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$comp->add(new Sabre_VObject_Component('VEVENT'));
$comp->add(new Component('VEVENT'));
$this->assertEquals(1, count($comp->children));
@ -219,10 +242,10 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
function testAddComponentTwice() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$comp->add(new Sabre_VObject_Component('VEVENT'));
$comp->add(new Sabre_VObject_Component('VEVENT'));
$comp->add(new Component('VEVENT'));
$comp->add(new Component('VEVENT'));
$this->assertEquals(2, count($comp->children));
@ -235,8 +258,8 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
*/
function testAddArgFail() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp->add(new Sabre_VObject_Component('VEVENT'),'hello');
$comp = new Component('VCALENDAR');
$comp->add(new Component('VEVENT'),'hello');
}
@ -245,7 +268,7 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
*/
function testAddArgFail2() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$comp->add(array());
}
@ -255,7 +278,7 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
*/
function testAddArgFail3() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$comp->add('hello',array());
}
@ -265,10 +288,10 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
*/
function testMagicSetInvalid() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
// Note that 'myProp' is ignored here.
$comp->myProp = new StdClass();
$comp->myProp = new \StdClass();
$this->assertEquals(1, count($comp->children));
@ -278,8 +301,8 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
function testMagicUnset() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp->add(new Sabre_VObject_Component('VEVENT'));
$comp = new Component('VCALENDAR');
$comp->add(new Component('VEVENT'));
unset($comp->vevent);
@ -290,34 +313,34 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
function testCount() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$this->assertEquals(1,$comp->count());
}
function testChildren() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
// Note that 'myProp' is ignored here.
$comp->children = array(
new Sabre_VObject_Component('VEVENT'),
new Sabre_VObject_Component('VTODO')
new Component('VEVENT'),
new Component('VTODO')
);
$r = $comp->children();
$this->assertTrue($r instanceof Sabre_VObject_ElementList);
$this->assertTrue($r instanceof ElementList);
$this->assertEquals(2,count($r));
}
function testGetComponents() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
// Note that 'myProp' is ignored here.
$comp->children = array(
new Sabre_VObject_Property('FOO','BAR'),
new Sabre_VObject_Component('VTODO')
new Property('FOO','BAR'),
new Component('VTODO')
);
$r = $comp->getComponents();
@ -328,17 +351,17 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
function testSerialize() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$this->assertEquals("BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n", $comp->serialize());
}
function testSerializeChildren() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp = new Component('VCALENDAR');
$comp->children = array(
new Sabre_VObject_Component('VEVENT'),
new Sabre_VObject_Component('VTODO')
new Component('VEVENT'),
new Component('VTODO')
);
$str = $comp->serialize();
@ -349,11 +372,11 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
function testSerializeOrderCompAndProp() {
$comp = new Sabre_VObject_Component('VCALENDAR');
$comp->add(new Sabre_VObject_Component('VEVENT'));
$comp = new Component('VCALENDAR');
$comp->add(new Component('VEVENT'));
$comp->add('PROP1','BLABLA');
$comp->add('VERSION','2.0');
$comp->add(new Sabre_VObject_Component('VTIMEZONE'));
$comp->add(new Component('VTIMEZONE'));
$str = $comp->serialize();
@ -365,7 +388,7 @@ class Sabre_VObject_ComponentTest extends PHPUnit_Framework_TestCase {
$prop4s=array('1', '2', '3', '4', '5', '6', '7', '8', '9', '10');
$comp = new Sabre_VObject_Component('VCARD');
$comp = new Component('VCARD');
$comp->__set('SOMEPROP','FOO');
$comp->__set('ANOTHERPROP','FOO');
$comp->__set('THIRDPROP','FOO');

View file

@ -0,0 +1,121 @@
<?php
namespace Sabre\VObject;
use DateTime;
use DateTimeZone;
use DateInterval;
class DateTimeParserTest extends \PHPUnit_Framework_TestCase {
function testParseICalendarDuration() {
$this->assertEquals('+1 weeks', DateTimeParser::parseDuration('P1W',true));
$this->assertEquals('+5 days', DateTimeParser::parseDuration('P5D',true));
$this->assertEquals('+5 days 3 hours 50 minutes 12 seconds', DateTimeParser::parseDuration('P5DT3H50M12S',true));
$this->assertEquals('-1 weeks 50 minutes', DateTimeParser::parseDuration('-P1WT50M',true));
$this->assertEquals('+50 days 3 hours 2 seconds', DateTimeParser::parseDuration('+P50DT3H2S',true));
$this->assertEquals(new DateInterval('PT0S'), DateTimeParser::parseDuration('PT0S'));
}
function testParseICalendarDurationDateInterval() {
$expected = new DateInterval('P7D');
$this->assertEquals($expected, DateTimeParser::parseDuration('P1W'));
$this->assertEquals($expected, DateTimeParser::parse('P1W'));
$expected = new DateInterval('PT3M');
$expected->invert = true;
$this->assertEquals($expected, DateTimeParser::parseDuration('-PT3M'));
}
/**
* @expectedException LogicException
*/
function testParseICalendarDurationFail() {
DateTimeParser::parseDuration('P1X',true);
}
function testParseICalendarDateTime() {
$dateTime = DateTimeParser::parseDateTime('20100316T141405');
$compare = new DateTime('2010-03-16 14:14:05',new DateTimeZone('UTC'));
$this->assertEquals($compare, $dateTime);
}
/**
* @depends testParseICalendarDateTime
* @expectedException LogicException
*/
function testParseICalendarDateTimeBadFormat() {
$dateTime = DateTimeParser::parseDateTime('20100316T141405 ');
}
/**
* @depends testParseICalendarDateTime
*/
function testParseICalendarDateTimeUTC() {
$dateTime = DateTimeParser::parseDateTime('20100316T141405Z');
$compare = new DateTime('2010-03-16 14:14:05',new DateTimeZone('UTC'));
$this->assertEquals($compare, $dateTime);
}
/**
* @depends testParseICalendarDateTime
*/
function testParseICalendarDateTimeUTC2() {
$dateTime = DateTimeParser::parseDateTime('20101211T160000Z');
$compare = new DateTime('2010-12-11 16:00:00',new DateTimeZone('UTC'));
$this->assertEquals($compare, $dateTime);
}
/**
* @depends testParseICalendarDateTime
*/
function testParseICalendarDateTimeCustomTimeZone() {
$dateTime = DateTimeParser::parseDateTime('20100316T141405', new DateTimeZone('Europe/Amsterdam'));
$compare = new DateTime('2010-03-16 13:14:05',new DateTimeZone('UTC'));
$this->assertEquals($compare, $dateTime);
}
function testParseICalendarDate() {
$dateTime = DateTimeParser::parseDate('20100316');
$expected = new DateTime('2010-03-16 00:00:00',new DateTimeZone('UTC'));
$this->assertEquals($expected, $dateTime);
$dateTime = DateTimeParser::parse('20100316');
$this->assertEquals($expected, $dateTime);
}
/**
* @depends testParseICalendarDate
* @expectedException LogicException
*/
function testParseICalendarDateBadFormat() {
$dateTime = DateTimeParser::parseDate('20100316T141405');
}
}

View file

@ -1,10 +1,12 @@
<?php
class Sabre_VObject_ElementListTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
class ElementListTest extends \PHPUnit_Framework_TestCase {
function testIterate() {
$sub = new Sabre_VObject_Component('VEVENT');
$sub = new Component('VEVENT');
$elems = array(
$sub,
@ -12,13 +14,13 @@ class Sabre_VObject_ElementListTest extends PHPUnit_Framework_TestCase {
clone $sub
);
$elemList = new Sabre_VObject_ElementList($elems);
$elemList = new ElementList($elems);
$count = 0;
foreach($elemList as $key=>$subcomponent) {
$count++;
$this->assertInstanceOf('Sabre_VObject_Component',$subcomponent);
$this->assertInstanceOf('Sabre\\VObject\\Component',$subcomponent);
}
$this->assertEquals(3,$count);

View file

@ -1,6 +1,8 @@
<?php
class Sabre_VObject_EmClientTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
class EmClientTest extends \PHPUnit_Framework_TestCase {
function testParseTz() {
@ -43,9 +45,9 @@ CLASS:PUBLIC
END:VEVENT
END:VCALENDAR';
$vObject = Sabre_VObject_Reader::read($str);
$vObject = Reader::read($str);
$dt = $vObject->VEVENT->DTSTART->getDateTime();
$this->assertEquals(new DateTime('2011-10-08 19:30:00', new DateTimeZone('America/Chicago')), $dt);
$this->assertEquals(new \DateTime('2011-10-08 19:30:00', new \DateTimeZone('America/Chicago')), $dt);
}

View file

@ -1,6 +1,8 @@
<?php
class Sabre_VObject_FreeBusyGeneratorTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
class FreeBusyGeneratorTest extends \PHPUnit_Framework_TestCase {
function getInput() {
@ -163,7 +165,7 @@ ICS;
$blob8,
$blob9,
$blob10,
Sabre_VObject_Reader::read($blob11),
Reader::read($blob11),
$blob12,
$blob13,
$blob14,
@ -173,11 +175,10 @@ ICS;
function testGenerator() {
$gen = new Sabre_VObject_FreeBusyGenerator();
$gen->setObjects($this->getInput());
$gen->setTimeRange(
new DateTime('20110101T110000Z'),
new DateTime('20110103T110000Z')
$gen = new FreeBusyGenerator(
new \DateTime('20110101T110000Z', new \DateTimeZone('UTC')),
new \DateTime('20110103T110000Z', new \DateTimeZone('UTC')),
$this->getInput()
);
$result = $gen->getResult();
@ -216,10 +217,10 @@ ICS;
function testGeneratorBaseObject() {
$obj = new Sabre_VObject_Component('VCALENDAR');
$obj = new Component('VCALENDAR');
$obj->METHOD = 'PUBLISH';
$gen = new Sabre_VObject_FreeBusyGenerator();
$gen = new FreeBusyGenerator();
$gen->setObjects(array());
$gen->setBaseObject($obj);
@ -227,20 +228,6 @@ ICS;
$this->assertEquals('PUBLISH', $result->METHOD->value);
}
function testGeneratorNoVersion() {
$v = Sabre_DAV_Server::$exposeVersion;
Sabre_DAV_Server::$exposeVersion = false;
$gen = new Sabre_VObject_FreeBusyGenerator();
$gen->setObjects(array());
$result = $gen->getResult();
Sabre_DAV_Server::$exposeVersion = $v;
$this->assertFalse(strpos($result->PRODID->value, Sabre_VObject_Version::VERSION));
}
/**
@ -248,8 +235,11 @@ ICS;
*/
function testInvalidArg() {
$gen = new Sabre_VObject_FreeBusyGenerator();
$gen->setObjects(array(new StdClass()));
$gen = new FreeBusyGenerator(
new \DateTime('2012-01-01'),
new \DateTime('2012-12-31'),
new \StdClass()
);
}

View file

@ -0,0 +1,14 @@
<?php
namespace Sabre\VObject;
class Issue153Test extends \PHPUnit_Framework_TestCase {
function testRead() {
$obj = Reader::read(file_get_contents(dirname(__FILE__) . '/issue153.vcf'));
$this->assertEquals('Test Benutzer', (string)$obj->fn);
}
}

View file

@ -1,10 +1,12 @@
<?php
class Sabre_VObject_Issue154Test extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
class Issue154Test extends \PHPUnit_Framework_TestCase {
function testStuff() {
$vcard = new Sabre_VObject_Component('VCARD');
$vcard = new Component('VCARD');
$vcard->VERSION = '3.0';
$vcard->PHOTO = base64_encode('random_stuff');
$vcard->PHOTO->add('BASE64',null);

View file

@ -1,10 +1,12 @@
<?php
class Sabre_VObject_ParameterTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
class ParameterTest extends \PHPUnit_Framework_TestCase {
function testSetup() {
$param = new Sabre_VObject_Parameter('name','value');
$param = new Parameter('name','value');
$this->assertEquals('NAME',$param->name);
$this->assertEquals('value',$param->value);
@ -12,7 +14,7 @@ class Sabre_VObject_ParameterTest extends PHPUnit_Framework_TestCase {
function testCastToString() {
$param = new Sabre_VObject_Parameter('name','value');
$param = new Parameter('name','value');
$this->assertEquals('value',$param->__toString());
$this->assertEquals('value',(string)$param);

View file

@ -1,14 +1,17 @@
<?php
class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject\Property;
use Sabre\VObject\Component;
class DateTimeTest extends \PHPUnit_Framework_TestCase {
function testSetDateTime() {
$tz = new DateTimeZone('Europe/Amsterdam');
$dt = new DateTime('1985-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('Europe/Amsterdam');
$dt = new \DateTime('1985-07-04 01:30:00', $tz);
$dt->setTimeZone($tz);
$elem = new Sabre_VObject_Property_DateTime('DTSTART');
$elem = new DateTime('DTSTART');
$elem->setDateTime($dt);
$this->assertEquals('19850704T013000', $elem->value);
@ -19,12 +22,12 @@ class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
function testSetDateTimeLOCAL() {
$tz = new DateTimeZone('Europe/Amsterdam');
$dt = new DateTime('1985-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('Europe/Amsterdam');
$dt = new \DateTime('1985-07-04 01:30:00', $tz);
$dt->setTimeZone($tz);
$elem = new Sabre_VObject_Property_DateTime('DTSTART');
$elem->setDateTime($dt, Sabre_VObject_Property_DateTime::LOCAL);
$elem = new DateTime('DTSTART');
$elem->setDateTime($dt, DateTime::LOCAL);
$this->assertEquals('19850704T013000', $elem->value);
$this->assertNull($elem['TZID']);
@ -34,12 +37,12 @@ class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
function testSetDateTimeUTC() {
$tz = new DateTimeZone('GMT');
$dt = new DateTime('1985-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('GMT');
$dt = new \DateTime('1985-07-04 01:30:00', $tz);
$dt->setTimeZone($tz);
$elem = new Sabre_VObject_Property_DateTime('DTSTART');
$elem->setDateTime($dt, Sabre_VObject_Property_DateTime::UTC);
$elem = new DateTime('DTSTART');
$elem->setDateTime($dt, DateTime::UTC);
$this->assertEquals('19850704T013000Z', $elem->value);
$this->assertNull($elem['TZID']);
@ -49,12 +52,12 @@ class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
function testSetDateTimeLOCALTZ() {
$tz = new DateTimeZone('Europe/Amsterdam');
$dt = new DateTime('1985-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('Europe/Amsterdam');
$dt = new \DateTime('1985-07-04 01:30:00', $tz);
$dt->setTimeZone($tz);
$elem = new Sabre_VObject_Property_DateTime('DTSTART');
$elem->setDateTime($dt, Sabre_VObject_Property_DateTime::LOCALTZ);
$elem = new DateTime('DTSTART');
$elem->setDateTime($dt, DateTime::LOCALTZ);
$this->assertEquals('19850704T013000', $elem->value);
$this->assertEquals('Europe/Amsterdam', (string)$elem['TZID']);
@ -64,12 +67,12 @@ class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
function testSetDateTimeDATE() {
$tz = new DateTimeZone('Europe/Amsterdam');
$dt = new DateTime('1985-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('Europe/Amsterdam');
$dt = new \DateTime('1985-07-04 01:30:00', $tz);
$dt->setTimeZone($tz);
$elem = new Sabre_VObject_Property_DateTime('DTSTART');
$elem->setDateTime($dt, Sabre_VObject_Property_DateTime::DATE);
$elem = new DateTime('DTSTART');
$elem->setDateTime($dt, DateTime::DATE);
$this->assertEquals('19850704', $elem->value);
$this->assertNull($elem['TZID']);
@ -82,22 +85,22 @@ class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
*/
function testSetDateTimeInvalid() {
$tz = new DateTimeZone('Europe/Amsterdam');
$dt = new DateTime('1985-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('Europe/Amsterdam');
$dt = new \DateTime('1985-07-04 01:30:00', $tz);
$dt->setTimeZone($tz);
$elem = new Sabre_VObject_Property_DateTime('DTSTART');
$elem = new DateTime('DTSTART');
$elem->setDateTime($dt, 7);
}
function testGetDateTimeCached() {
$tz = new DateTimeZone('Europe/Amsterdam');
$dt = new DateTime('1985-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('Europe/Amsterdam');
$dt = new \DateTime('1985-07-04 01:30:00', $tz);
$dt->setTimeZone($tz);
$elem = new Sabre_VObject_Property_DateTime('DTSTART');
$elem = new DateTime('DTSTART');
$elem->setDateTime($dt);
$this->assertEquals($elem->getDateTime(), $dt);
@ -106,7 +109,7 @@ class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
function testGetDateTimeDateNULL() {
$elem = new Sabre_VObject_Property_DateTime('DTSTART');
$elem = new DateTime('DTSTART');
$dt = $elem->getDateTime();
$this->assertNull($dt);
@ -116,42 +119,42 @@ class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
function testGetDateTimeDateDATE() {
$elem = new Sabre_VObject_Property_DateTime('DTSTART','19850704');
$elem = new DateTime('DTSTART','19850704');
$dt = $elem->getDateTime();
$this->assertInstanceOf('DateTime', $dt);
$this->assertEquals('1985-07-04 00:00:00', $dt->format('Y-m-d H:i:s'));
$this->assertEquals(Sabre_VObject_Property_DateTime::DATE, $elem->getDateType());
$this->assertEquals(DateTime::DATE, $elem->getDateType());
}
function testGetDateTimeDateLOCAL() {
$elem = new Sabre_VObject_Property_DateTime('DTSTART','19850704T013000');
$elem = new DateTime('DTSTART','19850704T013000');
$dt = $elem->getDateTime();
$this->assertInstanceOf('DateTime', $dt);
$this->assertEquals('1985-07-04 01:30:00', $dt->format('Y-m-d H:i:s'));
$this->assertEquals(Sabre_VObject_Property_DateTime::LOCAL, $elem->getDateType());
$this->assertEquals(DateTime::LOCAL, $elem->getDateType());
}
function testGetDateTimeDateUTC() {
$elem = new Sabre_VObject_Property_DateTime('DTSTART','19850704T013000Z');
$elem = new DateTime('DTSTART','19850704T013000Z');
$dt = $elem->getDateTime();
$this->assertInstanceOf('DateTime', $dt);
$this->assertEquals('1985-07-04 01:30:00', $dt->format('Y-m-d H:i:s'));
$this->assertEquals('UTC', $dt->getTimeZone()->getName());
$this->assertEquals(Sabre_VObject_Property_DateTime::UTC, $elem->getDateType());
$this->assertEquals(DateTime::UTC, $elem->getDateType());
}
function testGetDateTimeDateLOCALTZ() {
$elem = new Sabre_VObject_Property_DateTime('DTSTART','19850704T013000');
$elem = new DateTime('DTSTART','19850704T013000');
$elem['TZID'] = 'Europe/Amsterdam';
$dt = $elem->getDateTime();
@ -159,7 +162,7 @@ class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
$this->assertInstanceOf('DateTime', $dt);
$this->assertEquals('1985-07-04 01:30:00', $dt->format('Y-m-d H:i:s'));
$this->assertEquals('Europe/Amsterdam', $dt->getTimeZone()->getName());
$this->assertEquals(Sabre_VObject_Property_DateTime::LOCALTZ, $elem->getDateType());
$this->assertEquals(DateTime::LOCALTZ, $elem->getDateType());
}
@ -168,25 +171,25 @@ class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
*/
function testGetDateTimeDateInvalid() {
$elem = new Sabre_VObject_Property_DateTime('DTSTART','bla');
$elem = new DateTime('DTSTART','bla');
$dt = $elem->getDateTime();
}
function testGetDateTimeWeirdTZ() {
$elem = new Sabre_VObject_Property_DateTime('DTSTART','19850704T013000');
$elem = new DateTime('DTSTART','19850704T013000');
$elem['TZID'] = '/freeassociation.sourceforge.net/Tzfile/Europe/Amsterdam';
$event = new Sabre_VObject_Component('VEVENT');
$event = new Component('VEVENT');
$event->add($elem);
$timezone = new Sabre_VObject_Component('VTIMEZONE');
$timezone = new Component('VTIMEZONE');
$timezone->TZID = '/freeassociation.sourceforge.net/Tzfile/Europe/Amsterdam';
$timezone->{'X-LIC-LOCATION'} = 'Europe/Amsterdam';
$calendar = new Sabre_VObject_Component('VCALENDAR');
$calendar = new Component('VCALENDAR');
$calendar->add($event);
$calendar->add($timezone);
@ -195,7 +198,7 @@ class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
$this->assertInstanceOf('DateTime', $dt);
$this->assertEquals('1985-07-04 01:30:00', $dt->format('Y-m-d H:i:s'));
$this->assertEquals('Europe/Amsterdam', $dt->getTimeZone()->getName());
$this->assertEquals(Sabre_VObject_Property_DateTime::LOCALTZ, $elem->getDateType());
$this->assertEquals(DateTime::LOCALTZ, $elem->getDateType());
}
@ -204,18 +207,18 @@ class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
$default = date_default_timezone_get();
date_default_timezone_set('Canada/Eastern');
$elem = new Sabre_VObject_Property_DateTime('DTSTART','19850704T013000');
$elem = new DateTime('DTSTART','19850704T013000');
$elem['TZID'] = 'Moon';
$event = new Sabre_VObject_Component('VEVENT');
$event = new Component('VEVENT');
$event->add($elem);
$timezone = new Sabre_VObject_Component('VTIMEZONE');
$timezone = new Component('VTIMEZONE');
$timezone->TZID = 'Moon';
$timezone->{'X-LIC-LOCATION'} = 'Moon';
$calendar = new Sabre_VObject_Component('VCALENDAR');
$calendar = new Component('VCALENDAR');
$calendar->add($event);
$calendar->add($timezone);
@ -224,7 +227,7 @@ class Sabre_VObject_Property_DateTimeTest extends PHPUnit_Framework_TestCase {
$this->assertInstanceOf('DateTime', $dt);
$this->assertEquals('1985-07-04 01:30:00', $dt->format('Y-m-d H:i:s'));
$this->assertEquals('Canada/Eastern', $dt->getTimeZone()->getName());
$this->assertEquals(Sabre_VObject_Property_DateTime::LOCALTZ, $elem->getDateType());
$this->assertEquals(DateTime::LOCALTZ, $elem->getDateType());
date_default_timezone_set($default);
}

View file

@ -1,16 +1,18 @@
<?php
class Sabre_VObject_Property_MultiDateTimeTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject\Property;
class MultiDateTimeTest extends \PHPUnit_Framework_TestCase {
function testSetDateTime() {
$tz = new DateTimeZone('Europe/Amsterdam');
$dt1 = new DateTime('1985-07-04 01:30:00', $tz);
$dt2 = new DateTime('1986-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('Europe/Amsterdam');
$dt1 = new \DateTime('1985-07-04 01:30:00', $tz);
$dt2 = new \DateTime('1986-07-04 01:30:00', $tz);
$dt1->setTimeZone($tz);
$dt2->setTimeZone($tz);
$elem = new Sabre_VObject_Property_MultiDateTime('DTSTART');
$elem = new MultiDateTime('DTSTART');
$elem->setDateTimes(array($dt1,$dt2));
$this->assertEquals('19850704T013000,19860704T013000', $elem->value);
@ -21,14 +23,14 @@ class Sabre_VObject_Property_MultiDateTimeTest extends PHPUnit_Framework_TestCas
function testSetDateTimeLOCAL() {
$tz = new DateTimeZone('Europe/Amsterdam');
$dt1 = new DateTime('1985-07-04 01:30:00', $tz);
$dt2 = new DateTime('1986-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('Europe/Amsterdam');
$dt1 = new \DateTime('1985-07-04 01:30:00', $tz);
$dt2 = new \DateTime('1986-07-04 01:30:00', $tz);
$dt1->setTimeZone($tz);
$dt2->setTimeZone($tz);
$elem = new Sabre_VObject_Property_MultiDateTime('DTSTART');
$elem->setDateTimes(array($dt1,$dt2), Sabre_VObject_Property_DateTime::LOCAL);
$elem = new MultiDateTime('DTSTART');
$elem->setDateTimes(array($dt1,$dt2), DateTime::LOCAL);
$this->assertEquals('19850704T013000,19860704T013000', $elem->value);
$this->assertNull($elem['TZID']);
@ -38,14 +40,14 @@ class Sabre_VObject_Property_MultiDateTimeTest extends PHPUnit_Framework_TestCas
function testSetDateTimeUTC() {
$tz = new DateTimeZone('GMT');
$dt1 = new DateTime('1985-07-04 01:30:00', $tz);
$dt2 = new DateTime('1986-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('GMT');
$dt1 = new \DateTime('1985-07-04 01:30:00', $tz);
$dt2 = new \DateTime('1986-07-04 01:30:00', $tz);
$dt1->setTimeZone($tz);
$dt2->setTimeZone($tz);
$elem = new Sabre_VObject_Property_MultiDateTime('DTSTART');
$elem->setDateTimes(array($dt1,$dt2), Sabre_VObject_Property_DateTime::UTC);
$elem = new MultiDateTime('DTSTART');
$elem->setDateTimes(array($dt1,$dt2), DateTime::UTC);
$this->assertEquals('19850704T013000Z,19860704T013000Z', $elem->value);
$this->assertNull($elem['TZID']);
@ -55,14 +57,14 @@ class Sabre_VObject_Property_MultiDateTimeTest extends PHPUnit_Framework_TestCas
function testSetDateTimeLOCALTZ() {
$tz = new DateTimeZone('Europe/Amsterdam');
$dt1 = new DateTime('1985-07-04 01:30:00', $tz);
$dt2 = new DateTime('1986-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('Europe/Amsterdam');
$dt1 = new \DateTime('1985-07-04 01:30:00', $tz);
$dt2 = new \DateTime('1986-07-04 01:30:00', $tz);
$dt1->setTimeZone($tz);
$dt2->setTimeZone($tz);
$elem = new Sabre_VObject_Property_MultiDateTime('DTSTART');
$elem->setDateTimes(array($dt1,$dt2), Sabre_VObject_Property_DateTime::LOCALTZ);
$elem = new MultiDateTime('DTSTART');
$elem->setDateTimes(array($dt1,$dt2), DateTime::LOCALTZ);
$this->assertEquals('19850704T013000,19860704T013000', $elem->value);
$this->assertEquals('Europe/Amsterdam', (string)$elem['TZID']);
@ -72,14 +74,14 @@ class Sabre_VObject_Property_MultiDateTimeTest extends PHPUnit_Framework_TestCas
function testSetDateTimeDATE() {
$tz = new DateTimeZone('Europe/Amsterdam');
$dt1 = new datetime('1985-07-04 01:30:00', $tz);
$dt2 = new datetime('1986-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('Europe/Amsterdam');
$dt1 = new \DateTime('1985-07-04 01:30:00', $tz);
$dt2 = new \DateTime('1986-07-04 01:30:00', $tz);
$dt1->settimezone($tz);
$dt2->settimezone($tz);
$elem = new Sabre_VObject_Property_MultiDateTime('DTSTART');
$elem->setDateTimes(array($dt1,$dt2), Sabre_VObject_Property_DateTime::DATE);
$elem = new MultiDateTime('DTSTART');
$elem->setDateTimes(array($dt1,$dt2), DateTime::DATE);
$this->assertEquals('19850704,19860704', $elem->value);
$this->assertNull($elem['TZID']);
@ -92,24 +94,24 @@ class Sabre_VObject_Property_MultiDateTimeTest extends PHPUnit_Framework_TestCas
*/
function testSetDateTimeInvalid() {
$tz = new DateTimeZone('Europe/Amsterdam');
$dt = new DateTime('1985-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('Europe/Amsterdam');
$dt = new \DateTime('1985-07-04 01:30:00', $tz);
$dt->setTimeZone($tz);
$elem = new Sabre_VObject_Property_MultiDateTime('DTSTART');
$elem = new MultiDateTime('DTSTART');
$elem->setDateTimes(array($dt), 7);
}
function testGetDateTimeCached() {
$tz = new DateTimeZone('Europe/Amsterdam');
$dt1 = new datetime('1985-07-04 01:30:00', $tz);
$dt2 = new datetime('1986-07-04 01:30:00', $tz);
$tz = new \DateTimeZone('Europe/Amsterdam');
$dt1 = new \DateTime('1985-07-04 01:30:00', $tz);
$dt2 = new \DateTime('1986-07-04 01:30:00', $tz);
$dt1->settimezone($tz);
$dt2->settimezone($tz);
$elem = new Sabre_VObject_Property_MultiDateTime('DTSTART');
$elem = new MultiDateTime('DTSTART');
$elem->setDateTimes(array($dt1,$dt2));
$this->assertEquals($elem->getDateTimes(), array($dt1,$dt2));
@ -118,7 +120,7 @@ class Sabre_VObject_Property_MultiDateTimeTest extends PHPUnit_Framework_TestCas
function testGetDateTimeDateNULL() {
$elem = new Sabre_VObject_Property_MultiDateTime('DTSTART');
$elem = new MultiDateTime('DTSTART');
$dt = $elem->getDateTimes();
$this->assertNull($dt);
@ -128,20 +130,20 @@ class Sabre_VObject_Property_MultiDateTimeTest extends PHPUnit_Framework_TestCas
function testGetDateTimeDateDATE() {
$elem = new Sabre_VObject_Property_MultiDateTime('DTSTART','19850704,19860704');
$elem = new MultiDateTime('DTSTART','19850704,19860704');
$dt = $elem->getDateTimes();
$this->assertEquals('1985-07-04 00:00:00', $dt[0]->format('Y-m-d H:i:s'));
$this->assertEquals('1986-07-04 00:00:00', $dt[1]->format('Y-m-d H:i:s'));
$this->assertEquals(Sabre_VObject_Property_DateTime::DATE, $elem->getDateType());
$this->assertEquals(DateTime::DATE, $elem->getDateType());
}
function testGetDateTimeDateDATEReverse() {
$elem = new Sabre_VObject_Property_MultiDateTime('DTSTART','19850704,19860704');
$elem = new MultiDateTime('DTSTART','19850704,19860704');
$this->assertEquals(Sabre_VObject_Property_DateTime::DATE, $elem->getDateType());
$this->assertEquals(DateTime::DATE, $elem->getDateType());
$dt = $elem->getDateTimes();
$this->assertEquals('1985-07-04 00:00:00', $dt[0]->format('Y-m-d H:i:s'));
@ -152,30 +154,30 @@ class Sabre_VObject_Property_MultiDateTimeTest extends PHPUnit_Framework_TestCas
function testGetDateTimeDateLOCAL() {
$elem = new Sabre_VObject_Property_DateTime('DTSTART','19850704T013000');
$elem = new DateTime('DTSTART','19850704T013000');
$dt = $elem->getDateTime();
$this->assertInstanceOf('DateTime', $dt);
$this->assertEquals('1985-07-04 01:30:00', $dt->format('Y-m-d H:i:s'));
$this->assertEquals(Sabre_VObject_Property_DateTime::LOCAL, $elem->getDateType());
$this->assertEquals(DateTime::LOCAL, $elem->getDateType());
}
function testGetDateTimeDateUTC() {
$elem = new Sabre_VObject_Property_DateTime('DTSTART','19850704T013000Z');
$elem = new DateTime('DTSTART','19850704T013000Z');
$dt = $elem->getDateTime();
$this->assertInstanceOf('DateTime', $dt);
$this->assertEquals('1985-07-04 01:30:00', $dt->format('Y-m-d H:i:s'));
$this->assertEquals('UTC', $dt->getTimeZone()->getName());
$this->assertEquals(Sabre_VObject_Property_DateTime::UTC, $elem->getDateType());
$this->assertEquals(DateTime::UTC, $elem->getDateType());
}
function testGetDateTimeDateLOCALTZ() {
$elem = new Sabre_VObject_Property_DateTime('DTSTART','19850704T013000');
$elem = new DateTime('DTSTART','19850704T013000');
$elem['TZID'] = 'Europe/Amsterdam';
$dt = $elem->getDateTime();
@ -183,7 +185,7 @@ class Sabre_VObject_Property_MultiDateTimeTest extends PHPUnit_Framework_TestCas
$this->assertInstanceOf('DateTime', $dt);
$this->assertEquals('1985-07-04 01:30:00', $dt->format('Y-m-d H:i:s'));
$this->assertEquals('Europe/Amsterdam', $dt->getTimeZone()->getName());
$this->assertEquals(Sabre_VObject_Property_DateTime::LOCALTZ, $elem->getDateType());
$this->assertEquals(DateTime::LOCALTZ, $elem->getDateType());
}
@ -192,7 +194,7 @@ class Sabre_VObject_Property_MultiDateTimeTest extends PHPUnit_Framework_TestCas
*/
function testGetDateTimeDateInvalid() {
$elem = new Sabre_VObject_Property_DateTime('DTSTART','bla');
$elem = new DateTime('DTSTART','bla');
$dt = $elem->getDateTime();
}

View file

@ -1,10 +1,12 @@
<?php
class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
class PropertyTest extends \PHPUnit_Framework_TestCase {
public function testToString() {
$property = new Sabre_VObject_Property('propname','propvalue');
$property = new Property('propname','propvalue');
$this->assertEquals('PROPNAME', $property->name);
$this->assertEquals('propvalue', $property->value);
$this->assertEquals('propvalue', $property->__toString());
@ -14,8 +16,8 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
public function testParameterExists() {
$property = new Sabre_VObject_Property('propname','propvalue');
$property->parameters[] = new Sabre_VObject_Parameter('paramname','paramvalue');
$property = new Property('propname','propvalue');
$property->parameters[] = new Parameter('paramname','paramvalue');
$this->assertTrue(isset($property['PARAMNAME']));
$this->assertTrue(isset($property['paramname']));
@ -25,17 +27,17 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
public function testParameterGet() {
$property = new Sabre_VObject_Property('propname','propvalue');
$property->parameters[] = new Sabre_VObject_Parameter('paramname','paramvalue');
$property = new Property('propname','propvalue');
$property->parameters[] = new Parameter('paramname','paramvalue');
$this->assertInstanceOf('Sabre_VObject_Parameter',$property['paramname']);
$this->assertInstanceOf('Sabre\\VObject\\Parameter',$property['paramname']);
}
public function testParameterNotExists() {
$property = new Sabre_VObject_Property('propname','propvalue');
$property->parameters[] = new Sabre_VObject_Parameter('paramname','paramvalue');
$property = new Property('propname','propvalue');
$property->parameters[] = new Parameter('paramname','paramvalue');
$this->assertInternalType('null',$property['foo']);
@ -43,22 +45,22 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
public function testParameterMultiple() {
$property = new Sabre_VObject_Property('propname','propvalue');
$property->parameters[] = new Sabre_VObject_Parameter('paramname','paramvalue');
$property->parameters[] = new Sabre_VObject_Parameter('paramname','paramvalue');
$property = new Property('propname','propvalue');
$property->parameters[] = new Parameter('paramname','paramvalue');
$property->parameters[] = new Parameter('paramname','paramvalue');
$this->assertInstanceOf('Sabre_VObject_Parameter',$property['paramname']);
$this->assertInstanceOf('Sabre\\VObject\\Parameter',$property['paramname']);
$this->assertEquals(2,count($property['paramname']));
}
public function testSetParameterAsString() {
$property = new Sabre_VObject_Property('propname','propvalue');
$property = new Property('propname','propvalue');
$property['paramname'] = 'paramvalue';
$this->assertEquals(1,count($property->parameters));
$this->assertInstanceOf('Sabre_VObject_Parameter', $property->parameters[0]);
$this->assertInstanceOf('Sabre\\VObject\\Parameter', $property->parameters[0]);
$this->assertEquals('PARAMNAME',$property->parameters[0]->name);
$this->assertEquals('paramvalue',$property->parameters[0]->value);
@ -69,15 +71,15 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
*/
public function testSetParameterAsStringNoKey() {
$property = new Sabre_VObject_Property('propname','propvalue');
$property = new Property('propname','propvalue');
$property[] = 'paramvalue';
}
public function testSetParameterObject() {
$property = new Sabre_VObject_Property('propname','propvalue');
$param = new Sabre_VObject_Parameter('paramname','paramvalue');
$property = new Property('propname','propvalue');
$param = new Parameter('paramname','paramvalue');
$property[] = $param;
@ -91,8 +93,8 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
*/
public function testSetParameterObjectWithKey() {
$property = new Sabre_VObject_Property('propname','propvalue');
$param = new Sabre_VObject_Parameter('paramname','paramvalue');
$property = new Property('propname','propvalue');
$param = new Parameter('paramname','paramvalue');
$property['key'] = $param;
@ -104,15 +106,15 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
*/
public function testSetParameterObjectRandomObject() {
$property = new Sabre_VObject_Property('propname','propvalue');
$property[] = new StdClass();
$property = new Property('propname','propvalue');
$property[] = new \StdClass();
}
public function testUnsetParameter() {
$property = new Sabre_VObject_Property('propname','propvalue');
$param = new Sabre_VObject_Parameter('paramname','paramvalue');
$property = new Property('propname','propvalue');
$param = new Parameter('paramname','paramvalue');
$property->parameters[] = $param;
unset($property['PARAMNAME']);
@ -122,8 +124,8 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
public function testParamCount() {
$property = new Sabre_VObject_Property('propname','propvalue');
$param = new Sabre_VObject_Parameter('paramname','paramvalue');
$property = new Property('propname','propvalue');
$param = new Parameter('paramname','paramvalue');
$property->parameters[] = $param;
$property->parameters[] = clone $param;
@ -133,7 +135,7 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
public function testSerialize() {
$property = new Sabre_VObject_Property('propname','propvalue');
$property = new Property('propname','propvalue');
$this->assertEquals("PROPNAME:propvalue\r\n",$property->serialize());
@ -141,9 +143,9 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
public function testSerializeParam() {
$property = new Sabre_VObject_Property('propname','propvalue');
$property->parameters[] = new Sabre_VObject_Parameter('paramname','paramvalue');
$property->parameters[] = new Sabre_VObject_Parameter('paramname2','paramvalue2');
$property = new Property('propname','propvalue');
$property->parameters[] = new Parameter('paramname','paramvalue');
$property->parameters[] = new Parameter('paramname2','paramvalue2');
$this->assertEquals("PROPNAME;PARAMNAME=paramvalue;PARAMNAME2=paramvalue2:propvalue\r\n",$property->serialize());
@ -151,7 +153,7 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
public function testSerializeNewLine() {
$property = new Sabre_VObject_Property('propname',"line1\nline2");
$property = new Property('propname',"line1\nline2");
$this->assertEquals("PROPNAME:line1\\nline2\r\n",$property->serialize());
@ -160,7 +162,7 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
public function testSerializeLongLine() {
$value = str_repeat('!',200);
$property = new Sabre_VObject_Property('propname',$value);
$property = new Property('propname',$value);
$expected = "PROPNAME:" . str_repeat('!',66) . "\r\n " . str_repeat('!',74) . "\r\n " . str_repeat('!',60) . "\r\n";
@ -171,7 +173,7 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
public function testSerializeUTF8LineFold() {
$value = str_repeat('!',65) . "\xc3\xa4bla"; // inserted umlaut-a
$property = new Sabre_VObject_Property('propname', $value);
$property = new Property('propname', $value);
$expected = "PROPNAME:" . str_repeat('!',65) . "\r\n \xc3\xa4bla\r\n";
$this->assertEquals($expected, $property->serialize());
@ -179,8 +181,9 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
public function testGetIterator() {
$it = new Sabre_VObject_ElementList(array());
$property = new Sabre_VObject_Property('propname','propvalue', $it);
$it = new ElementList(array());
$property = new Property('propname','propvalue');
$property->setIterator($it);
$this->assertEquals($it,$property->getIterator());
}
@ -188,22 +191,22 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
public function testGetIteratorDefault() {
$property = new Sabre_VObject_Property('propname','propvalue');
$property = new Property('propname','propvalue');
$it = $property->getIterator();
$this->assertTrue($it instanceof Sabre_VObject_ElementList);
$this->assertTrue($it instanceof ElementList);
$this->assertEquals(1,count($it));
}
function testAddScalar() {
$property = new Sabre_VObject_Property('EMAIL');
$property = new Property('EMAIL');
$property->add('myparam','value');
$this->assertEquals(1, count($property->parameters));
$this->assertTrue($property->parameters[0] instanceof Sabre_VObject_Parameter);
$this->assertTrue($property->parameters[0] instanceof Parameter);
$this->assertEquals('MYPARAM',$property->parameters[0]->name);
$this->assertEquals('value',$property->parameters[0]->value);
@ -211,9 +214,9 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
function testAddParameter() {
$prop = new Sabre_VObject_Property('EMAIL');
$prop = new Property('EMAIL');
$prop->add(new Sabre_VObject_Parameter('MYPARAM','value'));
$prop->add(new Parameter('MYPARAM','value'));
$this->assertEquals(1, count($prop->parameters));
$this->assertEquals('MYPARAM',$prop['myparam']->name);
@ -222,10 +225,10 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
function testAddParameterTwice() {
$prop = new Sabre_VObject_Property('EMAIL');
$prop = new Property('EMAIL');
$prop->add(new Sabre_VObject_Parameter('MYPARAM', 'value1'));
$prop->add(new Sabre_VObject_Parameter('MYPARAM', 'value2'));
$prop->add(new Parameter('MYPARAM', 'value1'));
$prop->add(new Parameter('MYPARAM', 'value2'));
$this->assertEquals(2, count($prop->parameters));
@ -238,8 +241,8 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
*/
function testAddArgFail() {
$prop = new Sabre_VObject_Property('EMAIL');
$prop->add(new Sabre_VObject_Parameter('MPARAM'),'hello');
$prop = new Property('EMAIL');
$prop->add(new Parameter('MPARAM'),'hello');
}
@ -248,7 +251,7 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
*/
function testAddArgFail2() {
$property = new Sabre_VObject_Property('EMAIL','value');
$property = new Property('EMAIL','value');
$property->add(array());
}
@ -258,14 +261,14 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
*/
function testAddArgFail3() {
$property = new Sabre_VObject_Property('EMAIL','value');
$property = new Property('EMAIL','value');
$property->add('hello',array());
}
function testClone() {
$property = new Sabre_VObject_Property('EMAIL','value');
$property = new Property('EMAIL','value');
$property['FOO'] = 'BAR';
$property2 = clone $property;
@ -275,4 +278,16 @@ class Sabre_VObject_PropertyTest extends PHPUnit_Framework_TestCase {
}
function testCreateParams() {
$property = Property::create('X-PROP', 'value', array(
'param1' => 'value1',
'param2' => array('value2', 'value3')
));
$this->assertEquals(1, count($property['PARAM1']));
$this->assertEquals(2, count($property['PARAM2']));
}
}

View file

@ -1,14 +1,16 @@
<?php
class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
class ReaderTest extends \PHPUnit_Framework_TestCase {
function testReadComponent() {
$data = "BEGIN:VCALENDAR\r\nEND:VCALENDAR";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Component', $result);
$this->assertInstanceOf('Sabre\\VObject\\Component', $result);
$this->assertEquals('VCALENDAR', $result->name);
$this->assertEquals(0, count($result->children));
@ -18,9 +20,9 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
$data = "BEGIN:VCALENDAR\nEND:VCALENDAR";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Component', $result);
$this->assertInstanceOf('Sabre\\VObject\\Component', $result);
$this->assertEquals('VCALENDAR', $result->name);
$this->assertEquals(0, count($result->children));
@ -30,9 +32,9 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
$data = "BEGIN:VCALENDAR\rEND:VCALENDAR";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Component', $result);
$this->assertInstanceOf('Sabre\\VObject\\Component', $result);
$this->assertEquals('VCALENDAR', $result->name);
$this->assertEquals(0, count($result->children));
@ -42,31 +44,31 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
$data = "BEGIN:\r\n\tVCALENDAR\r\nE\r\n ND:VCALENDAR";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Component', $result);
$this->assertInstanceOf('Sabre\\VObject\\Component', $result);
$this->assertEquals('VCALENDAR', $result->name);
$this->assertEquals(0, count($result->children));
}
/**
* @expectedException Sabre_VObject_ParseException
* @expectedException Sabre\VObject\ParseException
*/
function testReadCorruptComponent() {
$data = "BEGIN:VCALENDAR\r\nEND:FOO";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
}
function testReadProperty() {
$data = "PROPNAME:propValue";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Property', $result);
$this->assertInstanceOf('Sabre\\VObject\\Property', $result);
$this->assertEquals('PROPNAME', $result->name);
$this->assertEquals('propValue', $result->value);
@ -75,9 +77,9 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
function testReadPropertyWithNewLine() {
$data = 'PROPNAME:Line1\\nLine2\\NLine3\\\\Not the 4th line!';
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Property', $result);
$this->assertInstanceOf('Sabre\\VObject\\Property', $result);
$this->assertEquals('PROPNAME', $result->name);
$this->assertEquals("Line1\nLine2\nLine3\\Not the 4th line!", $result->value);
@ -86,9 +88,9 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
function testReadMappedProperty() {
$data = "DTSTART:20110529";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Property_DateTime', $result);
$this->assertInstanceOf('Sabre\\VObject\\Property\\DateTime', $result);
$this->assertEquals('DTSTART', $result->name);
$this->assertEquals('20110529', $result->value);
@ -97,9 +99,9 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
function testReadMappedPropertyGrouped() {
$data = "foo.DTSTART:20110529";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Property_DateTime', $result);
$this->assertInstanceOf('Sabre\\VObject\\Property\\DateTime', $result);
$this->assertEquals('DTSTART', $result->name);
$this->assertEquals('20110529', $result->value);
@ -107,12 +109,12 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
/**
* @expectedException Sabre_VObject_ParseException
* @expectedException Sabre\VObject\ParseException
*/
function testReadBrokenLine() {
$data = "PROPNAME;propValue";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
}
@ -124,12 +126,12 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
"END:VCALENDAR"
);
$result = Sabre_VObject_Reader::read(implode("\r\n",$data));
$result = Reader::read(implode("\r\n",$data));
$this->assertInstanceOf('Sabre_VObject_Component', $result);
$this->assertInstanceOf('Sabre\\VObject\\Component', $result);
$this->assertEquals('VCALENDAR', $result->name);
$this->assertEquals(1, count($result->children));
$this->assertInstanceOf('Sabre_VObject_Property', $result->children[0]);
$this->assertInstanceOf('Sabre\\VObject\\Property', $result->children[0]);
$this->assertEquals('PROPNAME', $result->children[0]->name);
$this->assertEquals('propValue', $result->children[0]->value);
@ -146,15 +148,15 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
"END:VCALENDAR"
);
$result = Sabre_VObject_Reader::read(implode("\r\n",$data));
$result = Reader::read(implode("\r\n",$data));
$this->assertInstanceOf('Sabre_VObject_Component', $result);
$this->assertInstanceOf('Sabre\\VObject\\Component', $result);
$this->assertEquals('VCALENDAR', $result->name);
$this->assertEquals(1, count($result->children));
$this->assertInstanceOf('Sabre_VObject_Component', $result->children[0]);
$this->assertInstanceOf('Sabre\\VObject\\Component', $result->children[0]);
$this->assertEquals('VTIMEZONE', $result->children[0]->name);
$this->assertEquals(1, count($result->children[0]->children));
$this->assertInstanceOf('Sabre_VObject_Component', $result->children[0]->children[0]);
$this->assertInstanceOf('Sabre\\VObject\\Component', $result->children[0]->children[0]);
$this->assertEquals('DAYLIGHT', $result->children[0]->children[0]->name);
@ -163,9 +165,9 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
function testReadPropertyParameter() {
$data = "PROPNAME;PARAMNAME=paramvalue:propValue";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Property', $result);
$this->assertInstanceOf('Sabre\\VObject\\Property', $result);
$this->assertEquals('PROPNAME', $result->name);
$this->assertEquals('propValue', $result->value);
$this->assertEquals(1, count($result->parameters));
@ -177,9 +179,9 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
function testReadPropertyNoValue() {
$data = "PROPNAME;PARAMNAME:propValue";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Property', $result);
$this->assertInstanceOf('Sabre\\VObject\\Property', $result);
$this->assertEquals('PROPNAME', $result->name);
$this->assertEquals('propValue', $result->value);
$this->assertEquals(1, count($result->parameters));
@ -191,9 +193,9 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
function testReadPropertyParameterExtraColon() {
$data = "PROPNAME;PARAMNAME=paramvalue:propValue:anotherrandomstring";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Property', $result);
$this->assertInstanceOf('Sabre\\VObject\\Property', $result);
$this->assertEquals('PROPNAME', $result->name);
$this->assertEquals('propValue:anotherrandomstring', $result->value);
$this->assertEquals(1, count($result->parameters));
@ -205,9 +207,9 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
function testReadProperty2Parameters() {
$data = "PROPNAME;PARAMNAME=paramvalue;PARAMNAME2=paramvalue2:propValue";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Property', $result);
$this->assertInstanceOf('Sabre\\VObject\\Property', $result);
$this->assertEquals('PROPNAME', $result->name);
$this->assertEquals('propValue', $result->value);
$this->assertEquals(2, count($result->parameters));
@ -221,9 +223,9 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
function testReadPropertyParameterQuoted() {
$data = "PROPNAME;PARAMNAME=\"paramvalue\":propValue";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Property', $result);
$this->assertInstanceOf('Sabre\\VObject\\Property', $result);
$this->assertEquals('PROPNAME', $result->name);
$this->assertEquals('propValue', $result->value);
$this->assertEquals(1, count($result->parameters));
@ -234,9 +236,9 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
function testReadPropertyParameterNewLines() {
$data = "PROPNAME;PARAMNAME=paramvalue1\\nvalue2\\\\nvalue3:propValue";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Property', $result);
$this->assertInstanceOf('Sabre\\VObject\\Property', $result);
$this->assertEquals('PROPNAME', $result->name);
$this->assertEquals('propValue', $result->value);
@ -249,9 +251,9 @@ class Sabre_VObject_ReaderTest extends PHPUnit_Framework_TestCase {
function testReadPropertyParameterQuotedColon() {
$data = "PROPNAME;PARAMNAME=\"param:value\":propValue";
$result = Sabre_VObject_Reader::read($data);
$result = Reader::read($data);
$this->assertInstanceOf('Sabre_VObject_Property', $result);
$this->assertInstanceOf('Sabre\\VObject\\Property', $result);
$this->assertEquals('PROPNAME', $result->name);
$this->assertEquals('propValue', $result->value);
$this->assertEquals(1, count($result->parameters));

View file

@ -1,6 +1,8 @@
<?php
class Sabre_VObject_RecurrenceIteratorFifthTuesdayProblemTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
class RecurrenceIteratorFifthTuesdayProblemTest extends \PHPUnit_Framework_TestCase {
function testGetDTEnd() {
@ -26,8 +28,8 @@ END:VEVENT
END:VCALENDAR
ICS;
$vObject = Sabre_VObject_Reader::read($ics);
$it = new Sabre_VObject_RecurrenceIterator($vObject, (string)$vObject->VEVENT->UID);
$vObject = Reader::read($ics);
$it = new RecurrenceIterator($vObject, (string)$vObject->VEVENT->UID);
while($it->valid()) {
$it->next();

View file

@ -1,6 +1,11 @@
<?php
class Sabre_VObject_RecurrenceIteratorInfiniteLoopProblemTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
use DateTime;
use DateTimeZone;
class RecurrenceIteratorInfiniteLoopProblemTest extends \PHPUnit_Framework_TestCase {
/**
* This bug came from a Fruux customer. This would result in a never-ending
@ -8,7 +13,7 @@ class Sabre_VObject_RecurrenceIteratorInfiniteLoopProblemTest extends PHPUnit_Fr
*/
function testFastForwardTooFar() {
$ev = Sabre_VObject_Component::create('VEVENT');
$ev = Component::create('VEVENT');
$ev->DTSTART = '20090420T180000Z';
$ev->RRULE = 'FREQ=WEEKLY;BYDAY=MO;UNTIL=20090704T205959Z;INTERVAL=1';
@ -21,7 +26,7 @@ class Sabre_VObject_RecurrenceIteratorInfiniteLoopProblemTest extends PHPUnit_Fr
*/
function testYearlyByMonthLoop() {
$ev = Sabre_VObject_Component::create('VEVENT');
$ev = Component::create('VEVENT');
$ev->UID = 'uuid';
$ev->DTSTART = '20120101T154500';
$ev->DTSTART['TZID'] = 'Europe/Berlin';
@ -35,10 +40,10 @@ class Sabre_VObject_RecurrenceIteratorInfiniteLoopProblemTest extends PHPUnit_Fr
// The BYDAY part expands this to every day of the month, but the
// BYSETPOS limits this to only the 1st day of the month. Very crazy
// way to specify this, and could have certainly been a lot easier.
$cal = Sabre_VObject_Component::create('VCALENDAR');
$cal = Component::create('VCALENDAR');
$cal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($cal,'uuid');
$it = new RecurrenceIterator($cal,'uuid');
$it->fastForward(new DateTime('2012-01-29 23:00:00', new DateTimeZone('UTC')));
$collect = array();

View file

@ -1,21 +1,26 @@
<?php
class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
use DateTime;
use DateTimeZone;
class RecurrenceIteratorTest extends \PHPUnit_Framework_TestCase {
function testValues() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=DAILY;BYHOUR=10;BYMINUTE=5;BYSECOND=16;BYWEEKNO=32;BYYEARDAY=100,200';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07'),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals(array(10), $it->byHour);
$this->assertEquals(array(5), $it->byMinute);
@ -31,17 +36,17 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testInvalidFreq() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->RRULE = 'FREQ=SMONTHLY;INTERVAL=3;UNTIL=20111025T000000Z';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07'),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
}
@ -50,8 +55,8 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testVCalendarNoUID() {
$vcal = new Sabre_VObject_Component('VCALENDAR');
$it = new Sabre_VObject_RecurrenceIterator($vcal);
$vcal = new Component('VCALENDAR');
$it = new RecurrenceIterator($vcal);
}
@ -60,8 +65,8 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testVCalendarInvalidUID() {
$vcal = new Sabre_VObject_Component('VCALENDAR');
$it = new Sabre_VObject_RecurrenceIterator($vcal,'foo');
$vcal = new Component('VCALENDAR');
$it = new RecurrenceIterator($vcal,'foo');
}
@ -70,18 +75,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testDaily() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=DAILY;INTERVAL=3;UNTIL=20111025T000000Z';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,$ev->uid);
$it = new RecurrenceIterator($vcal,$ev->uid);
$this->assertEquals('daily', $it->frequency);
$this->assertEquals(3, $it->interval);
@ -121,17 +126,17 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testNoRRULE() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,$ev->uid);
$it = new RecurrenceIterator($vcal,$ev->uid);
$this->assertEquals('daily', $it->frequency);
$this->assertEquals(1, $it->interval);
@ -164,18 +169,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testDailyByDay() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=DAILY;INTERVAL=2;BYDAY=TU,WE,FR';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('daily', $it->frequency);
$this->assertEquals(2, $it->interval);
@ -220,18 +225,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testWeekly() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=WEEKLY;INTERVAL=2;COUNT=10';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('weekly', $it->frequency);
$this->assertEquals(2, $it->interval);
@ -274,18 +279,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testWeeklyByDay() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=WEEKLY;INTERVAL=2;BYDAY=TU,WE,FR;WKST=SU';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-10-07', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('weekly', $it->frequency);
$this->assertEquals(2, $it->interval);
@ -331,18 +336,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testMonthly() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=MONTHLY;INTERVAL=3;COUNT=5';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-12-05'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-12-05', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('monthly', $it->frequency);
$this->assertEquals(3, $it->interval);
@ -380,18 +385,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testMonthlyEndOfMonth() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=MONTHLY;INTERVAL=2;COUNT=12';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-12-31'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-12-31', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('monthly', $it->frequency);
$this->assertEquals(2, $it->interval);
@ -436,18 +441,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testMonthlyByMonthDay() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=MONTHLY;INTERVAL=5;COUNT=9;BYMONTHDAY=1,31,-7';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-01-01'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-01-01', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('monthly', $it->frequency);
$this->assertEquals(5, $it->interval);
@ -489,18 +494,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testMonthlyByDay() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=MONTHLY;INTERVAL=2;COUNT=16;BYDAY=MO,-2TU,+1WE,3TH';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-01-03'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-01-03', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('monthly', $it->frequency);
$this->assertEquals(2, $it->interval);
@ -549,18 +554,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testMonthlyByDayByMonthDay() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=MONTHLY;COUNT=10;BYDAY=MO;BYMONTHDAY=1';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-08-01'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-08-01', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('monthly', $it->frequency);
$this->assertEquals(1, $it->interval);
@ -604,18 +609,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testMonthlyByDayBySetPos() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=MONTHLY;COUNT=10;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=1,-1';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-01-03'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-01-03', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('monthly', $it->frequency);
$this->assertEquals(1, $it->interval);
@ -659,18 +664,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testYearly() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=YEARLY;COUNT=10;INTERVAL=3';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-01-01'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-01-01', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('yearly', $it->frequency);
$this->assertEquals(3, $it->interval);
@ -712,18 +717,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testYearlyLeapYear() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=YEARLY;COUNT=3';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2012-02-29'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2012-02-29', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('yearly', $it->frequency);
$this->assertEquals(3, $it->count);
@ -757,18 +762,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testYearlyByMonth() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=YEARLY;COUNT=8;INTERVAL=4;BYMONTH=4,10';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-04-07'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-04-07', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('yearly', $it->frequency);
$this->assertEquals(4, $it->interval);
@ -809,18 +814,18 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testYearlyByMonthByDay() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=YEARLY;COUNT=8;INTERVAL=5;BYMONTH=4,10;BYDAY=1MO,-1SU';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-04-04'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-04-04', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('yearly', $it->frequency);
$this->assertEquals(5, $it->interval);
@ -862,22 +867,22 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testFastForward() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=YEARLY;COUNT=8;INTERVAL=5;BYMONTH=4,10;BYDAY=1MO,-1SU';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-04-04'),Sabre_VObject_Property_DateTime::UTC);
$dtStart = new Property\DateTime('DTSTART');
$dtStart->setDateTime(new DateTime('2011-04-04', new DateTimeZone('UTC')),Property\DateTime::UTC);
$ev->add($dtStart);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
// The idea is that we're fast-forwarding too far in the future, so
// there will be no results left.
$it->fastForward(new DateTime('2020-05-05'));
$it->fastForward(new DateTime('2020-05-05', new DateTimeZone('UTC')));
$max = 20;
$result = array();
@ -901,27 +906,27 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testComplexExclusions() {
$ev = new Sabre_VObject_Component('VEVENT');
$ev = new Component('VEVENT');
$ev->UID = 'bla';
$ev->RRULE = 'FREQ=YEARLY;COUNT=10';
$dtStart = new Sabre_VObject_Property_DateTime('DTSTART');
$dtStart = new Property\DateTime('DTSTART');
$tz = new DateTimeZone('Canada/Eastern');
$dtStart->setDateTime(new DateTime('2011-01-01 13:50:20', $tz),Sabre_VObject_Property_DateTime::LOCALTZ);
$dtStart->setDateTime(new DateTime('2011-01-01 13:50:20', $tz),Property\DateTime::LOCALTZ);
$exDate1 = new Sabre_VObject_Property_MultiDateTime('EXDATE');
$exDate1->setDateTimes(array(new DateTime('2012-01-01 13:50:20', $tz), new DateTime('2014-01-01 13:50:20', $tz)), Sabre_VObject_Property_DateTime::LOCALTZ);
$exDate2 = new Sabre_VObject_Property_MultiDateTime('EXDATE');
$exDate2->setDateTimes(array(new DateTime('2016-01-01 13:50:20', $tz)), Sabre_VObject_Property_DateTime::LOCALTZ);
$exDate1 = new Property\MultiDateTime('EXDATE');
$exDate1->setDateTimes(array(new DateTime('2012-01-01 13:50:20', $tz), new DateTime('2014-01-01 13:50:20', $tz)), Property\DateTime::LOCALTZ);
$exDate2 = new Property\MultiDateTime('EXDATE');
$exDate2->setDateTimes(array(new DateTime('2016-01-01 13:50:20', $tz)), Property\DateTime::LOCALTZ);
$ev->add($dtStart);
$ev->add($exDate1);
$ev->add($exDate2);
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$vcal->add($ev);
$it = new Sabre_VObject_RecurrenceIterator($vcal,(string)$ev->uid);
$it = new RecurrenceIterator($vcal,(string)$ev->uid);
$this->assertEquals('yearly', $it->frequency);
$this->assertEquals(1, $it->interval);
@ -958,9 +963,9 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testOverridenEvent() {
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$ev1 = Sabre_VObject_Component::create('VEVENT');
$ev1 = Component::create('VEVENT');
$ev1->UID = 'overridden';
$ev1->RRULE = 'FREQ=DAILY;COUNT=10';
$ev1->DTSTART = '20120107T120000Z';
@ -969,7 +974,7 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
$vcal->add($ev1);
// ev2 overrides an event, and puts it on 2pm instead.
$ev2 = Sabre_VObject_Component::create('VEVENT');
$ev2 = Component::create('VEVENT');
$ev2->UID = 'overridden';
$ev2->{'RECURRENCE-ID'} = '20120110T120000Z';
$ev2->DTSTART = '20120110T140000Z';
@ -978,7 +983,7 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
$vcal->add($ev2);
// ev3 overrides an event, and puts it 2 days and 2 hours later
$ev3 = Sabre_VObject_Component::create('VEVENT');
$ev3 = Component::create('VEVENT');
$ev3->UID = 'overridden';
$ev3->{'RECURRENCE-ID'} = '20120113T120000Z';
$ev3->DTSTART = '20120115T140000Z';
@ -986,7 +991,7 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
$vcal->add($ev3);
$it = new Sabre_VObject_RecurrenceIterator($vcal,'overridden');
$it = new RecurrenceIterator($vcal,'overridden');
$dates = array();
$summaries = array();
@ -1032,9 +1037,9 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testOverridenEvent2() {
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$ev1 = Sabre_VObject_Component::create('VEVENT');
$ev1 = Component::create('VEVENT');
$ev1->UID = 'overridden';
$ev1->RRULE = 'FREQ=WEEKLY;COUNT=3';
$ev1->DTSTART = '20120112T120000Z';
@ -1043,7 +1048,7 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
$vcal->add($ev1);
// ev2 overrides an event, and puts it 6 days earlier instead.
$ev2 = Sabre_VObject_Component::create('VEVENT');
$ev2 = Component::create('VEVENT');
$ev2->UID = 'overridden';
$ev2->{'RECURRENCE-ID'} = '20120119T120000Z';
$ev2->DTSTART = '20120113T120000Z';
@ -1051,7 +1056,7 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
$vcal->add($ev2);
$it = new Sabre_VObject_RecurrenceIterator($vcal,'overridden');
$it = new RecurrenceIterator($vcal,'overridden');
$dates = array();
$summaries = array();
@ -1084,9 +1089,9 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
*/
function testOverridenEventNoValuesExpected() {
$vcal = Sabre_VObject_Component::create('VCALENDAR');
$vcal = Component::create('VCALENDAR');
$ev1 = Sabre_VObject_Component::create('VEVENT');
$ev1 = Component::create('VEVENT');
$ev1->UID = 'overridden';
$ev1->RRULE = 'FREQ=WEEKLY;COUNT=3';
$ev1->DTSTART = '20120124T120000Z';
@ -1095,7 +1100,7 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
$vcal->add($ev1);
// ev2 overrides an event, and puts it 6 days earlier instead.
$ev2 = Sabre_VObject_Component::create('VEVENT');
$ev2 = Component::create('VEVENT');
$ev2->UID = 'overridden';
$ev2->{'RECURRENCE-ID'} = '20120131T120000Z';
$ev2->DTSTART = '20120125T120000Z';
@ -1103,7 +1108,7 @@ class Sabre_VObject_RecurrenceIteratorTest extends PHPUnit_Framework_TestCase {
$vcal->add($ev2);
$it = new Sabre_VObject_RecurrenceIterator($vcal,'overridden');
$it = new RecurrenceIterator($vcal,'overridden');
$dates = array();
$summaries = array();

View file

@ -1,13 +1,15 @@
<?php
class Sabre_VObject_TimeZoneUtilTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
class TimezoneUtilTest extends \PHPUnit_Framework_TestCase {
/**
* @dataProvider getMapping
*/
function testCorrectTZ($timezoneName) {
$tz = new DateTimeZone($timezoneName);
$tz = new \DateTimeZone($timezoneName);
}
@ -18,7 +20,7 @@ class Sabre_VObject_TimeZoneUtilTest extends PHPUnit_Framework_TestCase {
function($value) {
return array($value);
},
Sabre_VObject_TimeZoneUtil::$map
TimeZoneUtil::$map
);
}
@ -58,9 +60,9 @@ END:VEVENT
END:VCALENDAR
HI;
$tz = Sabre_VObject_TimeZoneUtil::getTimeZone('foo', Sabre_VObject_Reader::read($vobj));
$tz = TimeZoneUtil::getTimeZone('foo', Reader::read($vobj));
$this->assertEquals(new DateTimeZone('Europe/Sarajevo'), $tz);
$this->assertEquals(new \DateTimeZone('Europe/Sarajevo'), $tz);
}
@ -99,16 +101,16 @@ END:VEVENT
END:VCALENDAR
HI;
$tz = Sabre_VObject_TimeZoneUtil::getTimeZone('foo', Sabre_VObject_Reader::read($vobj));
$tz = TimeZoneUtil::getTimeZone('foo', Reader::read($vobj));
$this->assertEquals(new DateTimeZone(date_default_timezone_get()), $tz);
$this->assertEquals(new \DateTimeZone(date_default_timezone_get()), $tz);
}
function testWindowsTimeZone() {
$tz = Sabre_VObject_TimeZoneUtil::getTimeZone('Eastern Standard Time');
$this->assertEquals(new DateTimeZone('America/New_York'), $tz);
$tz = TimeZoneUtil::getTimeZone('Eastern Standard Time');
$this->assertEquals(new \DateTimeZone('America/New_York'), $tz);
}
@ -144,9 +146,9 @@ UID:040000008200E00074C5B7101A82E0080000000010DA091DC31BCD01000000000000000
END:VEVENT
END:VCALENDAR
HI;
$tz = Sabre_VObject_TimeZoneUtil::getTimeZone('foo', Sabre_VObject_Reader::read($vobj));
$tz = TimeZoneUtil::getTimeZone('foo', Reader::read($vobj));
$this->assertEquals(new DateTimeZone(date_default_timezone_get()), $tz);
$this->assertEquals(new \DateTimeZone(date_default_timezone_get()), $tz);
}

View file

@ -1,13 +1,15 @@
<?php
class Sabre_VObject_VersionTest extends PHPUnit_Framework_TestCase {
namespace Sabre\VObject;
class VersionTest extends \PHPUnit_Framework_TestCase {
function testString() {
$v = Sabre_VObject_Version::VERSION;
$v = Version::VERSION;
$this->assertEquals(-1, version_compare('0.9.0',$v));
$s = Sabre_VObject_Version::STABILITY;
$s = Version::STABILITY;
$this->assertTrue($s == 'alpha' || $s == 'beta' || $s =='stable');
}

View file

@ -0,0 +1,4 @@
<?php
// Composer autoloader
include __DIR__ . '/../vendor/autoload.php';

View file

@ -0,0 +1,17 @@
<phpunit
colors="true"
bootstrap="bootstrap.php"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
>
<testsuite name="Sabre_VObject">
<directory>Sabre/</directory>
</testsuite>
<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix=".php">../lib/</directory>
</whitelist>
</filter>
</phpunit>

View file

@ -24,7 +24,7 @@
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript" src="jquery.timePicker.js"></script>
<script type="text/javascript">
jQuery(function() {
@ -74,10 +74,6 @@
});
</script>
<script type="text/javascript">
// Analytics.
var _gaq=_gaq||[];_gaq.push(["_setAccount","UA-123444-3"]),_gaq.push(["_trackPageview"]),function(){var a=document.createElement("script");a.type="text/javascript",a.async=!0,a.src=("https:"==document.location.protocol?"https://ssl":"http://www")+".google-analytics.com/ga.js";var b=document.getElementsByTagName("script")[0];b.parentNode.insertBefore(a,b)}()
</script>
</head>
<body>

Binary file not shown.

View file

@ -1,7 +1,7 @@
<?php
/**
* Name: Editplain
* Description: Disable richtext (TinyMCE) editor for status posting
* Description: This addon is deprecated and has been replaced with the "Advanced Features" setting. Admins should remove this addon when their core code is updated to include advanced feature settings.
* Version: 1.0
* Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
*

Binary file not shown.

View file

@ -1242,8 +1242,12 @@ function facebook_post_local(&$a,&$b) {
$fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
// if API is used, default to the chosen settings
if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default')))
$fb_enable = 1;
// but allow a specific override
if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
if(! x($_REQUEST,'facebook_enable'))
$fb_enable = 1;
}
if(! $fb_enable)
return;

BIN
fbpost.tgz Normal file

Binary file not shown.

18
fbpost/README.md Normal file
View file

@ -0,0 +1,18 @@
Installing the Friendica/Facebook connector
Detailed instructions how to use this plugin can be found at
the [How to: Friendica's Facebook Connector](https://github.com/friendica/friendica/wiki/How-to:-Friendica%E2%80%99s-Facebook-connector) page.
Vidoes and embeds will not be posted if there is no other content. Links
and images will be converted to a format suitable for the Facebook API and
long posts truncated - with a link to view the full post.
Facebook contacts will not be able to view private photos, as they are not able to
authenticate to your site to establish identity. We will address this
in a future release.
This addon will only post your entries to your Facebook account but won't fetch
content from there.
Info: please make sure that you understand all aspects due to Friendica's
default licence which is: [MIT License](https://github.com/friendica/friendica/blob/master/LICENSE)

13
fbpost/fbpost.css Normal file
View file

@ -0,0 +1,13 @@
#fbpost-enable-wrapper {
margin-top: 20px;
}
#fbpost-disable-wrapper {
margin-top: 20px;
}
#fbpost-post-default-form input {
margin-top: 20px;
margin-right: 20px;
}

967
fbpost/fbpost.php Normal file
View file

@ -0,0 +1,967 @@
<?php
/**
* Name: Facebook Post Connector
* Version: 1.3
* Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
* Author: Tobias Hößl <https://github.com/CatoTH/>
*
*/
/**
* Installing the Friendica/Facebook connector
*
* Detailed instructions how to use this plugin can be found at
* https://github.com/friendica/friendica/wiki/How-to:-Friendica%E2%80%99s-Facebook-connector
*
* Vidoes and embeds will not be posted if there is no other content. Links
* and images will be converted to a format suitable for the Facebook API and
* long posts truncated - with a link to view the full post.
*
* Facebook contacts will not be able to view private photos, as they are not able to
* authenticate to your site to establish identity. We will address this
* in a future release.
*/
require_once('include/security.php');
function fbpost_install() {
register_hook('post_local', 'addon/fbpost/fbpost.php', 'fbpost_post_local');
register_hook('notifier_normal', 'addon/fbpost/fbpost.php', 'fbpost_post_hook');
register_hook('jot_networks', 'addon/fbpost/fbpost.php', 'fbpost_jot_nets');
register_hook('connector_settings', 'addon/fbpost/fbpost.php', 'fbpost_plugin_settings');
register_hook('enotify', 'addon/fbpost/fbpost.php', 'fbpost_enotify');
register_hook('queue_predeliver', 'addon/fbpost/fbpost.php', 'fbpost_queue_hook');
}
function fbpost_uninstall() {
unregister_hook('post_local', 'addon/fbpost/fbpost.php', 'fbpost_post_local');
unregister_hook('notifier_normal', 'addon/fbpost/fbpost.php', 'fbpost_post_hook');
unregister_hook('jot_networks', 'addon/fbpost/fbpost.php', 'fbpost_jot_nets');
unregister_hook('connector_settings', 'addon/fbpost/fbpost.php', 'fbpost_plugin_settings');
unregister_hook('enotify', 'addon/fbpost/fbpost.php', 'fbpost_enotify');
unregister_hook('queue_predeliver', 'addon/fbpost/fbpost.php', 'fbpost_queue_hook');
}
/* declare the fbpost_module function so that /fbpost url requests will land here */
function fbpost_module() {}
// If a->argv[1] is a nickname, this is a callback from Facebook oauth requests.
// If $_REQUEST["realtime_cb"] is set, this is a callback from the Real-Time Updates API
/**
* @param App $a
*/
function fbpost_init(&$a) {
if($a->argc != 2)
return;
$nick = $a->argv[1];
if(strlen($nick))
$r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
dbesc($nick)
);
if(!(isset($r) && count($r)))
return;
$uid = $r[0]['uid'];
$auth_code = (x($_GET, 'code') ? $_GET['code'] : '');
$error = (x($_GET, 'error_description') ? $_GET['error_description'] : '');
if($error)
logger('fbpost_init: Error: ' . $error);
if($auth_code && $uid) {
$appid = get_config('facebook','appid');
$appsecret = get_config('facebook', 'appsecret');
$x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id='
. $appid . '&client_secret=' . $appsecret . '&redirect_uri='
. urlencode($a->get_baseurl() . '/fbpost/' . $nick)
. '&code=' . $auth_code);
logger('fbpost_init: returned access token: ' . $x, LOGGER_DATA);
if(strpos($x,'access_token=') !== false) {
$token = str_replace('access_token=', '', $x);
if(strpos($token,'&') !== false)
$token = substr($token,0,strpos($token,'&'));
set_pconfig($uid,'facebook','access_token',$token);
set_pconfig($uid,'facebook','post','1');
fbpost_get_self($uid);
}
}
}
/**
* @param int $uid
*/
function fbpost_get_self($uid) {
$access_token = get_pconfig($uid,'facebook','access_token');
if(! $access_token)
return;
$s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
if($s) {
$j = json_decode($s);
set_pconfig($uid,'facebook','self_id',(string) $j->id);
}
}
// This is the POST method to the facebook settings page
// Content is posted to Facebook in the function facebook_post_hook()
/**
* @param App $a
*/
function fbpost_post(&$a) {
$uid = local_user();
if($uid){
$fb_limited = get_config('facebook','crestrict');
$value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
set_pconfig($uid,'facebook','post_by_default', $value);
$value = ((x($_POST,'suppress_view_on_friendica')) ? intval($_POST['suppress_view_on_friendica']) : 0);
set_pconfig($uid,'facebook','suppress_view_on_friendica', $value);
$value = ((x($_POST,'post_to_page')) ? $_POST['post_to_page'] : "0-0");
$values = explode("-", $value);
set_pconfig($uid,'facebook','post_to_page', $values[0]);
set_pconfig($uid,'facebook','page_access_token', $values[1]);
info( t('Settings updated.') . EOL);
}
return;
}
// Facebook settings form
/**
* @param App $a
* @return string
*/
function fbpost_content(&$a) {
if(! local_user()) {
notice( t('Permission denied.') . EOL);
return '';
}
if(! service_class_allows(local_user(),'facebook_connect')) {
notice( t('Permission denied.') . EOL);
return upgrade_bool_message();
}
if($a->argc > 1 && $a->argv[1] === 'remove') {
del_pconfig(local_user(),'facebook','post');
info( t('Facebook Post disabled') . EOL);
}
$o = '';
$fb_installed = false;
if (get_pconfig(local_user(),'facebook','post')) {
$access_token = get_pconfig(local_user(),'facebook','access_token');
if ($access_token) {
$s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
if($s) {
$j = json_decode($s);
if (isset($j->data)) $fb_installed = true;
}
}
}
$appid = get_config('facebook','appid');
if(! $appid) {
notice( t('Facebook API key is missing.') . EOL);
return '';
}
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'
. $a->get_baseurl() . '/addon/fbpost/fbpost.css' . '" media="all" />' . "\r\n";
$o .= '<h3>' . t('Facebook Post') . '</h3>';
if(! $fb_installed) {
$o .= '<div id="fbpost-enable-wrapper">';
$o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
. $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=publish_stream,manage_pages,photo_upload,user_groups,offline_access">' . t('Install Facebook Post connector for this account.') . '</a>';
$o .= '</div>';
}
if($fb_installed) {
$o .= '<div id="fbpost-disable-wrapper">';
$o .= '<a href="' . $a->get_baseurl() . '/fbpost/remove' . '">' . t('Remove Facebook Post connector') . '</a></div>';
$o .= '<div id="fbpost-enable-wrapper">';
$o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
. $a->get_baseurl() . '/fbpost/' . $a->user['nickname'] . '&scope=publish_stream,manage_pages,photo_upload,user_groups,offline_access">' . t('Re-authenticate [This is necessary whenever your Facebook password is changed.]') . '</a>';
$o .= '</div>';
$o .= '<div id="fbpost-post-default-form">';
$o .= '<form action="fbpost" method="post" >';
$post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
$checked = (($post_by_default) ? ' checked="checked" ' : '');
$o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . EOL;
$suppress_view_on_friendica = get_pconfig(local_user(),'facebook','suppress_view_on_friendica');
$checked = (($suppress_view_on_friendica) ? ' checked="checked" ' : '');
$o .= '<input type="checkbox" name="suppress_view_on_friendica" value="1"' . $checked . '/>' . ' ' . t('Suppress "View on friendica"') . EOL;
// List all pages
$post_to_page = get_pconfig(local_user(),'facebook','post_to_page');
$page_access_token = get_pconfig(local_user(),'facebook','page_access_token');
$fb_token = get_pconfig($a->user['uid'],'facebook','access_token');
$url = 'https://graph.facebook.com/me/accounts';
$x = fetch_url($url."?access_token=".$fb_token);
$accounts = json_decode($x);
$o .= t("Post to page/group:")."<select name='post_to_page'>";
if (intval($post_to_page) == 0)
$o .= "<option value='0-0' selected>".t('None')."</option>";
else
$o .= "<option value='0-0'>".t('None')."</option>";
foreach($accounts->data as $account) {
if (is_array($account->perms))
if ($post_to_page == $account->id)
$o .= "<option value='".$account->id."-".$account->access_token."' selected>".$account->name."</option>";
else
$o .= "<option value='".$account->id."-".$account->access_token."'>".$account->name."</option>";
}
$url = 'https://graph.facebook.com/me/groups';
$x = fetch_url($url."?access_token=".$fb_token);
$groups = json_decode($x);
foreach($groups->data as $group) {
if ($post_to_page == $group->id)
$o .= "<option value='".$group->id."-0' selected>".$group->name."</option>";
else
$o .= "<option value='".$group->id."-0'>".$group->name."</option>";
}
$o .= "</select>";
$o .= '<p><input type="submit" name="submit" value="' . t('Submit') . '" /></form></div>';
}
return $o;
}
/**
* @param App $a
* @param null|object $b
*/
function fbpost_plugin_settings(&$a,&$b) {
$b .= '<div class="settings-block">';
$b .= '<h3>' . t('Facebook') . '</h3>';
$b .= '<a href="fbpost">' . t('Facebook Post Settings') . '</a><br />';
$b .= '</div>';
}
/**
* @param App $a
* @param null|object $o
*/
function fbpost_plugin_admin(&$a, &$o){
$o = '<input type="hidden" name="form_security_token" value="' . get_form_security_token("fbsave") . '">';
$o .= '<h4>' . t('Facebook API Key') . '</h4>';
$appid = get_config('facebook', 'appid' );
$appsecret = get_config('facebook', 'appsecret' );
$ret1 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appid' LIMIT 1");
$ret2 = q("SELECT `v` FROM `config` WHERE `cat` = 'facebook' AND `k` = 'appsecret' LIMIT 1");
if ((count($ret1) > 0 && $ret1[0]['v'] != $appid) || (count($ret2) > 0 && $ret2[0]['v'] != $appsecret)) $o .= t('Error: it appears that you have specified the App-ID and -Secret in your .htconfig.php file. As long as they are specified there, they cannot be set using this form.<br><br>');
$o .= '<label for="fb_appid">' . t('App-ID / API-Key') . '</label><input id="fb_appid" name="appid" type="text" value="' . escape_tags($appid ? $appid : "") . '"><br style="clear: both;">';
$o .= '<label for="fb_appsecret">' . t('Application secret') . '</label><input id="fb_appsecret" name="appsecret" type="text" value="' . escape_tags($appsecret ? $appsecret : "") . '"><br style="clear: both;">';
$o .= '<input type="submit" name="fb_save_keys" value="' . t('Save') . '">';
}
/**
* @param App $a
*/
function fbpost_plugin_admin_post(&$a){
check_form_security_token_redirectOnErr('/admin/plugins/fbpost', 'fbsave');
if (x($_REQUEST,'fb_save_keys')) {
set_config('facebook', 'appid', $_REQUEST['appid']);
set_config('facebook', 'appsecret', $_REQUEST['appsecret']);
info(t('The new values have been saved.'));
}
}
/**
* @param App $a
* @param object $b
* @return mixed
*/
function fbpost_jot_nets(&$a,&$b) {
if(! local_user())
return;
$fb_post = get_pconfig(local_user(),'facebook','post');
if(intval($fb_post) == 1) {
$fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
$selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
$b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . ' value="1" /> '
. t('Post to Facebook') . '</div>';
}
}
function fbpost_ShareAttributes($match) {
$attributes = $match[1];
$author = "";
preg_match("/author='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "")
$author = $matches[1];
preg_match('/author="(.*?)"/ism', $attributes, $matches);
if ($matches[1] != "")
$author = $matches[1];
$headline = '<div class="shared_header">';
$headline .= sprintf(t('%s:'), $author);
$headline .= "</div>";
//$text = "<br />".$headline."</strong><blockquote>".$match[2]."</blockquote>";
$text = "\n\t".$match[2].":\t";
return($text);
}
/**
* @param App $a
* @param object $b
* @return mixed
*/
function fbpost_post_hook(&$a,&$b) {
if($b['deleted'] || ($b['created'] !== $b['edited']))
return;
/**
* Post to Facebook stream
*/
require_once('include/group.php');
require_once('include/html2plain.php');
logger('Facebook post');
$reply = false;
$likes = false;
$deny_arr = array();
$allow_arr = array();
$toplevel = (($b['id'] == $b['parent']) ? true : false);
$linking = ((get_pconfig($b['uid'],'facebook','no_linking')) ? 0 : 1);
if((! $toplevel) && ($linking)) {
$r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
intval($b['parent']),
intval($b['uid'])
);
if(count($r) && substr($r[0]['uri'],0,4) === 'fb::')
$reply = substr($r[0]['uri'],4);
elseif(count($r) && substr($r[0]['extid'],0,4) === 'fb::')
$reply = substr($r[0]['extid'],4);
else
return;
$u = q("SELECT * FROM user where uid = %d limit 1",
intval($b['uid'])
);
if(! count($u))
return;
// only accept comments from the item owner. Other contacts are unknown to FB.
if(! link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname']))
return;
logger('facebook reply id=' . $reply);
}
if(strstr($b['postopts'],'facebook') || ($b['private']) || ($reply)) {
if($b['private'] && $reply === false) {
$allow_people = expand_acl($b['allow_cid']);
$allow_groups = expand_groups(expand_acl($b['allow_gid']));
$deny_people = expand_acl($b['deny_cid']);
$deny_groups = expand_groups(expand_acl($b['deny_gid']));
$recipients = array_unique(array_merge($allow_people,$allow_groups));
$deny = array_unique(array_merge($deny_people,$deny_groups));
$allow_str = dbesc(implode(', ',$recipients));
if($allow_str) {
$r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $allow_str ) AND `network` = 'face'");
if(count($r))
foreach($r as $rr)
$allow_arr[] = $rr['notify'];
}
$deny_str = dbesc(implode(', ',$deny));
if($deny_str) {
$r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( $deny_str ) AND `network` = 'face'");
if(count($r))
foreach($r as $rr)
$deny_arr[] = $rr['notify'];
}
if(count($deny_arr) && (! count($allow_arr))) {
// One or more FB folks were denied access but nobody on FB was specifically allowed access.
// This might cause the post to be open to public on Facebook, but only to selected members
// on another network. Since this could potentially leak a post to somebody who was denied,
// we will skip posting it to Facebook with a slightly vague but relevant message that will
// hopefully lead somebody to this code comment for a better explanation of what went wrong.
notice( t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL);
return;
}
// if it's a private message but no Facebook members are allowed or denied, skip Facebook post
if((! count($allow_arr)) && (! count($deny_arr)))
return;
}
if($b['verb'] == ACTIVITY_LIKE)
$likes = true;
$appid = get_config('facebook', 'appid' );
$secret = get_config('facebook', 'appsecret' );
if($appid && $secret) {
logger('facebook: have appid+secret');
$fb_token = get_pconfig($b['uid'],'facebook','access_token');
// post to facebook if it's a public post and we've ticked the 'post to Facebook' box,
// or it's a private message with facebook participants
// or it's a reply or likes action to an existing facebook post
if($fb_token && ($toplevel || $b['private'] || $reply)) {
logger('facebook: able to post');
require_once('library/facebook.php');
require_once('include/bbcode.php');
$msg = $b['body'];
logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
// make links readable before we strip the code
// unless it's a dislike - just send the text as a comment
// if($b['verb'] == ACTIVITY_DISLIKE)
// $msg = trim(strip_tags(bbcode($msg)));
// Old code
/*$search_str = $a->get_baseurl() . '/search';
if(preg_match("/\[url=(.*?)\](.*?)\[\/url\]/is",$msg,$matches)) {
// don't use hashtags for message link
if(strpos($matches[2],$search_str) === false) {
$link = $matches[1];
if(substr($matches[2],0,5) != '[img]')
$linkname = $matches[2];
}
}
// strip tag links to avoid link clutter, this really should be
// configurable because we're losing information
$msg = preg_replace("/\#\[url=(.*?)\](.*?)\[\/url\]/is",'#$2',$msg);
// provide the link separately for normal links
$msg = preg_replace("/\[url=(.*?)\](.*?)\[\/url\]/is",'$2 $1',$msg);
if(preg_match("/\[img\](.*?)\[\/img\]/is",$msg,$matches))
$image = $matches[1];
$msg = preg_replace("/\[img\](.*?)\[\/img\]/is", t('Image: ') . '$1', $msg);
if((strpos($link,z_root()) !== false) && (! $image))
$image = $a->get_baseurl() . '/images/friendica-64.jpg';
$msg = trim(strip_tags(bbcode($msg)));*/
// New code
// Looking for the first image
$image = '';
if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
$image = $matches[3];
if ($image == '')
if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
$image = $matches[1];
// When saved into the database the content is sent through htmlspecialchars
// That means that we have to decode all image-urls
$image = htmlspecialchars_decode($image);
// Checking for a bookmark element
$body = $b['body'];
if (strpos($body, "[bookmark") !== false) {
// splitting the text in two parts:
// before and after the bookmark
$pos = strpos($body, "[bookmark");
$body1 = substr($body, 0, $pos);
$body2 = substr($body, $pos);
// Removing the bookmark and all quotes after the bookmark
// they are mostly only the content after the bookmark.
$body2 = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",'',$body2);
$body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
$body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
$body = $body1.$body2;
}
// Convert recycle signs
$body = str_replace("\t", " ", $body);
// recycle 1
$recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
$body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n\t$2:\t", $body);
// recycle 2 (Test)
$recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
$body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n\t$2:\t", $body);
// share element
$body = preg_replace_callback("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]/ism","fbpost_ShareAttributes", $body);
$bodyparts = explode("\t", $body);
// Doesn't help with multiple repeats - the problem has to be solved later
if (sizeof($bodyparts) == 3) {
$html = bbcode($bodyparts[2], false, false);
$test = trim(html2plain($html, 0, true));
if (trim($bodyparts[0]) == "")
$body = trim($bodyparts[2]);
else if (trim($test) == "")
$body = trim($bodyparts[0]);
else
$body = trim($bodyparts[0])."\n\n".trim($bodyparts[1])."[quote]".trim($bodyparts[2])."[/quote]";
} else
$body = str_replace("\t", "", $body);
// At first convert the text to html
$html = bbcode($body, false, false);
// Then convert it to plain text
$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
// Removing useless spaces
if (substr($msg, -2) == "«")
$msg = trim(substr($msg, 0, -2))."«";
$msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
// Removing multiple newlines
while (strpos($msg, "\n\n\n") !== false)
$msg = str_replace("\n\n\n", "\n\n", $msg);
// add any attachments as text urls
$arr = explode(',',$b['attach']);
if(count($arr)) {
$msg .= "\n";
foreach($arr as $r) {
$matches = false;
$cnt = preg_match('|\[attach\]href=\"(.*?)\" size=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
if($cnt) {
$msg .= "\n".$matches[1];
}
}
}
$link = '';
$linkname = '';
// look for bookmark-bbcode and handle it with priority
if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches)) {
$link = $matches[1];
$linkname = $matches[2];
}
// If there is no bookmark element then take the first link
if ($link == '') {
$links = collecturls($html);
if (sizeof($links) > 0) {
reset($links);
$link = current($links);
}
}
// Remove trailing and leading spaces
$msg = trim($msg);
// Fallback - if message is empty
if(!strlen($msg))
$msg = $linkname;
if(!strlen($msg))
$msg = $link;
if(!strlen($msg))
$msg = $image;
// If there is nothing to post then exit
if(!strlen($msg))
return;
logger('Facebook post: msg=' . $msg, LOGGER_DATA);
$video = "";
if($likes) {
$postvars = array('access_token' => $fb_token);
} else {
// message, picture, link, name, caption, description, source, place, tags
if(trim($link) != "")
if (@exif_imagetype($link) != 0) {
$image = $link;
$link = "";
}
$postvars = array(
'access_token' => $fb_token,
'message' => $msg
);
if(trim($image) != "")
$postvars['picture'] = $image;
if(trim($link) != "") {
$postvars['link'] = $link;
if ((stristr($link,'youtube')) || (stristr($link,'youtu.be')) || (stristr($link,'vimeo'))) {
$video = $link;
}
}
if(trim($linkname) != "")
$postvars['name'] = $linkname;
}
if(($b['private']) && ($toplevel)) {
$postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"';
if(count($allow_arr))
$postvars['privacy'] .= ',"allow": "' . implode(',',$allow_arr) . '"';
if(count($deny_arr))
$postvars['privacy'] .= ',"deny": "' . implode(',',$deny_arr) . '"';
$postvars['privacy'] .= '}';
}
$post_to_page = get_pconfig($b['uid'],'facebook','post_to_page');
$page_access_token = get_pconfig($b['uid'],'facebook','page_access_token');
if ((intval($post_to_page) != 0) and ($page_access_token != ""))
$target = $post_to_page;
else
$target = "me";
if($reply) {
$url = 'https://graph.facebook.com/' . $reply . '/' . (($likes) ? 'likes' : 'comments');
} else if (($video != "") or (($image == "") and ($link != ""))) {
// If it is a link to a video or a link without a preview picture then post it as a link
if ($video != "")
$link = $video;
$postvars = array(
'access_token' => $fb_token,
'link' => $link,
);
if ($msg != $video)
$postvars['message'] = $msg;
$url = 'https://graph.facebook.com/'.$target.'/links';
} else if (($link == "") and ($image != "")) {
// If it is only an image without a page link then post this image as a photo
$postvars = array(
'access_token' => $fb_token,
'url' => $image,
);
if ($msg != $image)
$postvars['message'] = $msg;
$url = 'https://graph.facebook.com/'.$target.'/photos';
} else if (($link != "") or ($image != "") or ($b['title'] == '') or (strlen($msg) < 500)) {
$url = 'https://graph.facebook.com/'.$target.'/feed';
if (!get_pconfig($b['uid'],'facebook','suppress_view_on_friendica') and $b['plink'])
$postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' . $b['plink'] . '"}';
} else {
// if its only a message and a subject and the message is larger than 500 characters then post it as note
$postvars = array(
'access_token' => $fb_token,
'message' => bbcode($b['body'], false, false),
'subject' => $b['title'],
);
$url = 'https://graph.facebook.com/'.$target.'/notes';
}
// Post to page?
if (!$reply and ($target != "me") and $page_access_token)
$postvars['access_token'] = $page_access_token;
logger('facebook: post to ' . $url);
logger('facebook: postvars: ' . print_r($postvars,true));
// "test_mode" prevents anything from actually being posted.
// Otherwise, let's do it.
if(! get_config('facebook','test_mode')) {
$x = post_url($url, $postvars);
logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
$retj = json_decode($x);
if($retj->id) {
q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
dbesc('fb::' . $retj->id),
intval($b['id'])
);
}
else {
if(! $likes) {
$s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
require_once('include/queue_fn.php');
add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
notice( t('Facebook post failed. Queued for retry.') . EOL);
}
if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) {
logger('Facebook session has expired due to changed password.', LOGGER_DEBUG);
$last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent');
if (!$last_notification || $last_notification < (time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL)) {
require_once('include/enotify.php');
$r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid']) );
notification(array(
'uid' => $b['uid'],
'type' => NOTIFY_SYSTEM,
'system_type' => 'facebook_connection_invalid',
'language' => $r[0]['language'],
'to_name' => $r[0]['username'],
'to_email' => $r[0]['email'],
'source_name' => t('Administrator'),
'source_link' => $a->config["system"]["url"],
'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg',
));
set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time());
} else logger('Facebook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG);
}
}
}
}
}
}
}
/**
* @param App $app
* @param object $data
*/
function fbpost_enotify(&$app, &$data) {
if (x($data, 'params') && $data['params']['type'] == NOTIFY_SYSTEM && x($data['params'], 'system_type') && $data['params']['system_type'] == 'facebook_connection_invalid') {
$data['itemlink'] = '/facebook';
$data['epreamble'] = $data['preamble'] = t('Your Facebook connection became invalid. Please Re-authenticate.');
$data['subject'] = t('Facebook connection became invalid');
$data['body'] = sprintf( t("Hi %1\$s,\n\nThe connection between your accounts on %2\$s and Facebook became invalid. This usually happens after you change your Facebook-password. To enable the connection again, you have to %3\$sre-authenticate the Facebook-connector%4\$s."), $data['params']['to_name'], "[url=" . $app->config["system"]["url"] . "]" . $app->config["sitename"] . "[/url]", "[url=" . $app->config["system"]["url"] . "/facebook]", "[/url]");
}
}
/**
* @param App $a
* @param object $b
*/
function fbpost_post_local(&$a,&$b) {
// Figure out if Facebook posting is enabled for this post and file it in 'postopts'
// where we will discover it during background delivery.
// This can only be triggered by a local user posting to their own wall.
if((local_user()) && (local_user() == $b['uid'])) {
$fb_post = intval(get_pconfig(local_user(),'facebook','post'));
$fb_enable = (($fb_post && x($_REQUEST,'facebook_enable')) ? intval($_REQUEST['facebook_enable']) : 0);
// if API is used, default to the chosen settings
// but allow a specific override
if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'facebook','post_by_default'))) {
if(! x($_REQUEST,'facebook_enable'))
$fb_enable = 1;
}
if(! $fb_enable)
return;
if(strlen($b['postopts']))
$b['postopts'] .= ',';
$b['postopts'] .= 'facebook';
}
}
/**
* @param App $a
* @param object $b
*/
function fbpost_queue_hook(&$a,&$b) {
$qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
dbesc(NETWORK_FACEBOOK)
);
if(! count($qi))
return;
require_once('include/queue_fn.php');
foreach($qi as $x) {
if($x['network'] !== NETWORK_FACEBOOK)
continue;
logger('facebook_queue: run');
$r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
intval($x['cid'])
);
if(! count($r))
continue;
$user = $r[0];
$appid = get_config('facebook', 'appid' );
$secret = get_config('facebook', 'appsecret' );
if($appid && $secret) {
$fb_post = intval(get_pconfig($user['uid'],'facebook','post'));
$fb_token = get_pconfig($user['uid'],'facebook','access_token');
if($fb_post && $fb_token) {
logger('facebook_queue: able to post');
require_once('library/facebook.php');
$z = unserialize($x['content']);
$item = $z['item'];
$j = post_url($z['url'],$z['post']);
$retj = json_decode($j);
if($retj->id) {
q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1",
dbesc('fb::' . $retj->id),
intval($item)
);
logger('facebook_queue: success: ' . $j);
remove_queue_item($x['id']);
}
else {
logger('facebook_queue: failed: ' . $j);
update_queue_time($x['id']);
}
}
}
}
}
/**
* @return bool|string
*/
function fbpost_get_app_access_token() {
$acc_token = get_config('facebook','app_access_token');
if ($acc_token !== false) return $acc_token;
$appid = get_config('facebook','appid');
$appsecret = get_config('facebook', 'appsecret');
if ($appid === false || $appsecret === false) {
logger('fb_get_app_access_token: appid and/or appsecret not set', LOGGER_DEBUG);
return false;
}
logger('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials', LOGGER_DATA);
$x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id=' . $appid . '&client_secret=' . $appsecret . '&grant_type=client_credentials');
if(strpos($x,'access_token=') !== false) {
logger('fb_get_app_access_token: returned access token: ' . $x, LOGGER_DATA);
$token = str_replace('access_token=', '', $x);
if(strpos($token,'&') !== false)
$token = substr($token,0,strpos($token,'&'));
if ($token == "") {
logger('fb_get_app_access_token: empty token: ' . $x, LOGGER_DEBUG);
return false;
}
set_config('facebook','app_access_token',$token);
return $token;
} else {
logger('fb_get_app_access_token: response did not contain an access_token: ' . $x, LOGGER_DATA);
return false;
}
}

BIN
fortunate.tgz Normal file

Binary file not shown.

7
fortunate/README Normal file
View file

@ -0,0 +1,7 @@
This addon requires a fortune server. You may use the DB supplied here to create one.
gunzip the fortunate.sql.gz and import into your database.
Copy cookie.php to the top level Friendica directory.
Edit fortunate.php and change FORTUNATE_SERVER definition to your hostname. Change the http in that file to https if your server doesn't support http.
Many additional options are available if you examine cookie.php - a clever developer can provide a settings page to tailor this to one's liking. Also several languages are supported, and it would be convenient to set this to the current Friendica language if that is amongst those supported.

349
fortunate/cookie.php Normal file
View file

@ -0,0 +1,349 @@
<?php
set_time_limit(0);
error_reporting(0);
require(".htconfig.php");
$db = @new mysqli($db_host,$db_user,$db_pass,$db_data);
header( "Content-type: text/html; charset=utf-8");
header( "Last-Modified: " . gmdate( "D, j M Y H:i:s" ) . " GMT" );
header( "Expires: " . gmdate( "D, j M Y H:i:s", time() ) . " GMT" );
header( "Cache-Control: no-store, no-cache, must-revalidate" ); // HTTP/1.1
header( "Cache-Control: post-check=0, pre-check=0", FALSE );
header( "Pragma: no-cache" ); // HTTP/1.0
$lang = 'en';
$offensive = $_GET['off'];
if($offensive == 'o')
$adult = 2;
elseif($offensive == 'a')
$adult = 1;
else
$adult = 0;
$length = (($_GET['length']) ? intval($_GET['length']) : 0);
$numlines = ((intval($_GET['numlines'])) ? intval($_GET['numlines']) : 0);
$cat = (($_GET['cat'] == '1') ? 1 : 0);
$equal = (($_GET['equal'] == '1') ? 1 : 0);
$stats = (($_GET['stats'] == '1') ? 1 : 0);
if(strlen($_GET['lang']))
$lang = @$db->real_escape_string($_GET['lang']);
if(strlen($_GET['pattern']))
$pattern = @$db->real_escape_string(urldecode($_GET['pattern']));
if(strlen($_GET['regex']))
$regex = @$db->real_escape_string(urldecode($_GET['regex']));
if(strlen($_GET['db']))
$table = @$db->real_escape_string(urldecode($_GET['db']));
else
$table = '';
if($length < 0)
$length = 0;
if($numlines < 0)
$numlines = 0;
function do_query($table,$length,$numlines,$adult,$cat,$limit,$lang,$pattern,$regex,$equal) {
global $db;
$rnd = mt_rand();
$r = array();
$typesql = (($table) ? " WHERE `category` = '$table' " : " WHERE 1 ");
$lengthsql = (($length) ? " AND LENGTH(`text`) < $length " : "" );
if($adult == 2)
$adultsql = " AND offensive = 1 ";
elseif($adult == 1)
$adultsql = "";
else
$adultsql = " AND offensive = 0 ";
if($numlines)
$lengthsql .=
" AND (LENGTH(`text`) - LENGTH(REPLACE(`text`,\"\n\",\"\"))) <= $numlines ";
$langsql = " AND lang = '$lang' ";
$patsql = '';
if(strlen($pattern))
$patsql = " AND MATCH text AGAINST ('$pattern' IN BOOLEAN MODE) ";
$regexsql = '';
if(strlen($regex))
$regexsql = " AND text REGEXP '$regex' ";
$eqsql = '';
if($equal) {
$catsavail = array();
$res = @$db->query("SELECT DISTINCT ( `category` ) FROM `fortune`
$typesql
$adultsql
$lengthsql
$langsql
$patsql
$regexsql ");
if($res->num_rows) {
while($x = $res->fetch_array(MYSQL_ASSOC))
$catsavail[] = $x['category'];
$eqsql = " AND `category` = '"
. $catsavail[mt_rand(0,$res->num_rows - 1)] . "' ";
}
}
$result = @$db->query("SELECT `text`, `category` FROM `fortune`
$typesql
$adultsql
$lengthsql
$langsql
$patsql
$regexsql
$eqsql
ORDER BY RAND($rnd)
LIMIT $limit");
if($result->num_rows) {
while($x = $result->fetch_array(MYSQL_ASSOC))
$r[] = fortune_to_html($x['text'])
.(($cat) ? "<br />[{$x['category']}]<br />" : "");
}
return $r;
}
function do_stats($table,$length,$numlines,$adult,$cat,$limit,$lang,$pattern,$regex,$equal) {
global $db;
$rnd = mt_rand();
$r = array();
$typesql = (($table) ? " WHERE `category` = '$table' " : " WHERE 1 ");
$lengthsql = (($length) ? " AND LENGTH(`text`) < $length " : "" );
if($adult == 2)
$adultsql = " AND offensive = 1 ";
elseif($adult == 1)
$adultsql = "";
else
$adultsql = " AND offensive = 0 ";
if($numlines)
$lengthsql .=
" AND (LENGTH(`text`) - LENGTH(REPLACE(`text`,\"\n\",\"\"))) <= $numlines ";
$langsql = " AND lang = '$lang' ";
$patsql = '';
if(strlen($pattern))
$patsql = " AND MATCH text AGAINST ('$pattern' IN BOOLEAN MODE) ";
$regexsql = '';
if(strlen($regex))
$regexsql = " AND text REGEXP '$regex' ";
$eqsql = '';
$result = @$db->query("SELECT `text`, `category` FROM `fortune`
$typesql
$adultsql
$lengthsql
$langsql
$patsql
$regexsql
$eqsql");
echo '<br />' . $result->num_rows . ' matching quotations.<br />';
$res = @$db->query("SELECT DISTINCT ( `category` ) FROM `fortune`
$typesql
$adultsql
$lengthsql
$langsql
$patsql
$regexsql ");
if($res->num_rows) {
echo '<br />Matching Databases:<br />';
while($x = $res->fetch_array(MYSQL_ASSOC))
echo $x['category'].'<br />';
}
else
echo '<br />No matching databases using those search parameters - please refine your options.<br />';
}
function fortune_to_html($s) {
// First pass - escape all the HTML entities, and while we're at it
// get rid of any MS-DOS end-of-line characters and expand tabs to
// 8 non-breaking spaces, and translate linefeeds to <br />.
// We also get rid of ^G which used to sound the terminal beep or bell
// on ASCII terminals and were humourous in some fortunes.
// We could map these to autoplay a short sound file but browser support
// is still sketchy and then there's the issue of where to locate the
// URL, and a lot of people find autoplay sounds downright annoying.
// So for now, just remove them.
$s = str_replace(
array("&",
"<",
">",
'"',
"\007",
"\t",
"\r",
"\n"),
array("&amp;",
"&lt;",
"&gt;",
"&quot;",
"",
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;",
"",
"<br />"),
$s);
// Replace pseudo diacritics
// These were used to produce accented characters. For instance an accented
// e would have been encoded by '^He - the backspace moving the cursor
// backward so both the single quote and the e would appear in the same
// character position. Umlauts were quite clever - they used a double quote
// as the accent mark over a normal character.
$s = preg_replace("/'\010([a-zA-Z])/","&\\1acute;",$s);
$s = preg_replace("/\&quot;\010([a-zA-Z])/","&\\1uml;",$s);
$s = preg_replace("/\`\010([a-zA-Z])/","&\\1grave;",$s);
$s = preg_replace("/\^\010([a-zA-Z])/","&\\1circ;",$s);
$s = preg_replace("/\~\010([a-zA-Z])/","&\\1tilde;",$s);
// Ignore multiple underlines for the same character. These were
// most useful when sent to a line printer back in the day as it
// would type over the same character a number of times making it
// much darker (e.g. bold). I think there are only one or two
// instances of this in the current (2008) fortune cookie database.
$s = preg_replace("/(_\010)+/","_\010",$s);
// Map the characters which sit underneath a backspace.
// If you can come up with a regex to do all of the following
// madness - be my guest.
// It's not as simple as you think. We need to take something
// that has been backspaced over an arbitrary number of times
// and wrap a forward looking matching number of characters in
// HTML, whilst deciding if it's intended as an underline or
// strikeout sequence.
// Essentially we produce a string of '1' and '0' characters
// the same length as the source text.
// Any position which is marked '1' has been backspaced over.
$cursor = 0;
$dst = $s;
$bs_found = false;
for($x = 0; $x < strlen($s); $x ++) {
if($s[$x] == "\010" && $cursor) {
$bs_found = true;
$cursor --;
$dst[$cursor] = '1';
$dst[$x] = '0';
$continue;
}
else {
if($bs_found) {
$bs_found = false;
$cursor = $x;
}
$dst[$cursor] = '0';
$cursor ++;
}
}
$out = '';
$strike = false;
$bold = false;
// Underline sequence, convert to bold to avoid confusion with links.
// These were generally used for emphasis so it's a reasonable choice.
// Please note that this logic will fail if there is an underline sequence
// and also a strikeout sequence in the same fortune.
if(strstr($s,"_\010")) {
$len = 0;
for($x = 0; $x < strlen($s); $x ++) {
if($dst[$x] == '1') {
$len ++;
$bold = true;
}
else {
if($bold) {
$out .= '<strong>';
while($s[$x] == "\010")
$x ++;
$out .= substr($s,$x,$len);
$out .= '</strong>';
$x = $x + $len - 1;
$len = 0;
$bold = false;
}
else
$out .= $s[$x];
}
}
}
// These aren't seen very often these days - simulation of
// backspace/replace. You could occasionally see the original text
// on slower terminals before it got replaced. Once modems reached
// 4800/9600 baud in the late 70's and early 80's the effect was
// mostly lost - but if you find a really old fortune file you might
// encounter a few of these.
else {
for($x = 0; $x < strlen($s); $x ++) {
if($dst[$x] == '1') {
if($strike)
$out .= $s[$x];
else
$out .= '<strike>'.$s[$x];
$strike = true;
}
else {
if($strike)
$out .= '</strike>';
$strike = false;
$out .= $s[$x];
}
}
}
// Many of the underline sequences are also wrapped in asterisks,
// which was yet another way of marking ASCII as 'bold'.
// So if it's an underline sequence, and there are asterisks
// on both ends, strip the asterisks as we've already emboldened the text.
$out = preg_replace('/\*(<strong>[^<]*<\/strong>)\*/',"\\1",$out);
// Finally, remove the backspace characters which we don't need anymore.
return str_replace("\010","",$out);
}
$result1 = do_query($table,$length,$numlines,$adult,$cat,1,$lang,$pattern,$regex,$equal);
if(count($result1))
echo $result1[0];
if($stats)
do_stats($table,$length,$numlines,$adult,$cat,1,$lang,$pattern,$regex,$equal);

7
fortunate/fortunate.css Normal file
View file

@ -0,0 +1,7 @@
.fortunate {
margin-top: 25px;
margin-left: 100px;
margin-bottom: 25px;
color: #000088;
font-size: 14px;
}

35
fortunate/fortunate.php Normal file
View file

@ -0,0 +1,35 @@
<?php
/**
* Name: Fortunate
* Description: Add a random fortune cookie at the bottom of every pages. [Requires manual confguration.]
* Version: 1.0
* Author: Mike Macgirvin <http://macgirvin.com/profile/mike>
*/
// IMPORTANT: SET THIS to your fortunate server
define ('FORTUNATE_SERVER', 'hostname.com');
function fortunate_install() {
register_hook('page_end', 'addon/fortunate/fortunate.php', 'fortunate_fetch');
if(FORTUNATE_SERVER == 'hostname.com' && is_site_admin()) {
notice('Fortunate plugin requires configuration. See README');
}
}
function fortunate_uninstall() {
unregister_hook('page_end', 'addon/fortunate/fortunate.php', 'fortunate_fetch');
}
function fortunate_fetch(&$a,&$b) {
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'
. $a->get_baseurl() . '/addon/fortunate/fortunate.css' . '" media="all" />' . "\r\n";
if(FORTUNATE_SERVER != 'hostname.com') {
$s = fetch_url('http://' . FORTUNATE_SERVER . '/cookie.php?numlines=2&equal=1&rand=' . mt_rand());
$b .= '<div class="fortunate">' . $s . '</div>';
}
}

BIN
fortunate/fortunemod.sql.gz Normal file

Binary file not shown.

BIN
forumdirectory.tgz Normal file

Binary file not shown.

View file

@ -0,0 +1,67 @@
section .forumdirectory-item dl {
height: auto;
overflow: auto;
}
section .forumdirectory-item dt {
float: left;
margin-left: 0px;
text-align: right;
color: #999;
}
section .forumdirectory-item dd {
float: left;
margin-left: 5px;
}
.forumdirectory-profile-wrapper {
float: left;
/*max-height: 178px; */
overflow: hidden;
width: 500px;
margin: 0px 20px;
}
.forumdirectory-copy-wrapper {
float: left;
overflow: hidden;
}
.forumdirectory-item {
float: left;
width: 800px;
/* height: 200px; */
box-shadow: 8px 8px 4px #000;
margin-top: 30px;
border: solid 1px #222;
}
section .forumdirectory-photo-wrapper {
float: left;
height: 200px;
width: 165px;
}
.forumcontact-name {
font-size: 18px;
font-weight: bold;
margin-bottom: -3px;
text-align: left;
}
.page-type {
font-size: 10px;
font-style: italic;
}
.directory-detailscolumn-wrapper {
float: left;
width: 305px;
margin-right: 10px;
}
.directory-profile-wrapper dl {
margin-top: 3px;
margin-bottom: 3px;
}
.directory-profile-title {
font-weight: bold;
margin-bottom: 3px;
font-size: 14px;
}

View file

@ -0,0 +1,206 @@
<?php
/**
* Name: Forum Directory
* Description: Add a directory of forums hosted on your server, with verbose descriptions.
* Version: 1.0
* Author: Thomas Willingham <https://kakste.com/profile/beardyunixer>
*/
function forumdirectory_install() {
register_hook('app_menu', 'addon/forumdirectory/forumdirectory.php', 'forumdirectory_app_menu');
}
function forumdirectory_uninstall() {
unregister_hook('app_menu', 'addon/forumdirectory/forumdirectory.php', 'forumdirectory_app_menu');
}
function forumdirectory_module() {
return;
}
function forumdirectory_app_menu($a,&$b) {
$b['app_menu'][] = '<div class="app-title"><a href="forumdirectory">' . t('Forum Directory') . '</a></div>';
}
function forumdirectory_init(&$a) {
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'.$a->get_baseurl().'/addon/forumdirectory/forumdirectory.css" media="all" />';
$a->set_pager_itemspage(60);
if(local_user()) {
require_once('include/contact_widgets.php');
$a->page['aside'] .= findpeople_widget();
}
else
unset($_SESSION['theme']);
}
function forumdirectory_post(&$a) {
if(x($_POST,'search'))
$a->data['search'] = $_POST['search'];
}
function forumdirectory_content(&$a) {
if((get_config('system','block_public')) && (! local_user()) && (! remote_user())) {
notice( t('Public access denied.') . EOL);
return;
}
$o = '';
nav_set_selected('directory');
if(x($a->data,'search'))
$search = notags(trim($a->data['search']));
else
$search = ((x($_GET,'search')) ? notags(trim(rawurldecode($_GET['search']))) : '');
$tpl = get_markup_template('directory_header.tpl');
$globaldir = '';
$gdirpath = dirname(get_config('system','directory_submit_url'));
if(strlen($gdirpath)) {
$globaldir = '<ul><li><div id="global-directory-link"><a href="'
. zrl($gdirpath,true) . '">' . t('Global Directory') . '</a></div></li></ul>';
}
$admin = '';
$o .= replace_macros($tpl, array(
'$search' => $search,
'$globaldir' => $globaldir,
'$desc' => t('Find on this site'),
'$admin' => $admin,
'$finding' => (strlen($search) ? '<h4>' . t('Finding: ') . "'" . $search . "'" . '</h4>' : ""),
'$sitedir' => t('Site Directory'),
'$submit' => t('Find')
));
if($search)
$search = dbesc($search);
$sql_extra = ((strlen($search)) ? " AND MATCH (`profile`.`name`, `user`.`nickname`, `pdesc`, `locality`,`region`,`country-name`,`gender`,`marital`,`sexual`,`about`,`romance`,`work`,`education`,`pub_keywords`,`prv_keywords` ) AGAINST ('$search' IN BOOLEAN MODE) " : "");
$publish = ((get_config('system','publish_all')) ? '' : " AND `publish` = 1 " );
$r = q("SELECT COUNT(*) AS `total` FROM `profile` LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid` WHERE `is-default` = 1 $publish AND `user`.`blocked` = 0 AND `page-flags` = 2 $sql_extra ");
if(count($r))
$a->set_pager_total($r[0]['total']);
$order = " ORDER BY `name` ASC ";
$r = q("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags` FROM `profile` LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid` WHERE `is-default` = 1 $publish AND `user`.`blocked` = 0 AND `page-flags` = 2 $sql_extra $order LIMIT %d , %d ",
intval($a->pager['start']),
intval($a->pager['itemspage'])
);
if(count($r)) {
if(in_array('small', $a->argv))
$photo = 'thumb';
else
$photo = 'photo';
foreach($r as $rr) {
$profile_link = $a->get_baseurl() . '/profile/' . ((strlen($rr['nickname'])) ? $rr['nickname'] : $rr['profile_uid']);
$pdesc = (($rr['pdesc']) ? $rr['pdesc'] . '<br />' : '');
$details = '';
if(strlen($rr['locality']))
$details .= $rr['locality'];
if(strlen($rr['region'])) {
if(strlen($rr['locality']))
$details .= ', ';
$details .= $rr['region'];
}
if(strlen($rr['country-name'])) {
if(strlen($details))
$details .= ', ';
$details .= $rr['country-name'];
}
if(strlen($rr['dob'])) {
if(($years = age($rr['dob'],$rr['timezone'],'')) != 0)
$details .= '<br />' . t('Age: ') . $years ;
}
if(strlen($rr['gender']))
$details .= '<br />' . t('Gender: ') . $rr['gender'];
if($rr['page-flags'] == PAGE_NORMAL)
$page_type = "Personal Profile";
if($rr['page-flags'] == PAGE_SOAPBOX)
$page_type = "Fan Page";
if($rr['page-flags'] == PAGE_COMMUNITY)
$page_type = "Community Forum";
if($rr['page-flags'] == PAGE_FREELOVE)
$page_type = "Open Forum";
if($rr['page-flags'] == PAGE_PRVGROUP)
$page_type = "Private Group";
$profile = $rr;
if((x($profile,'address') == 1)
|| (x($profile,'locality') == 1)
|| (x($profile,'region') == 1)
|| (x($profile,'postal-code') == 1)
|| (x($profile,'country-name') == 1))
$location = t('Location:');
$gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
$marital = ((x($profile,'marital') == 1) ? t('Status:') : False);
$homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False);
$about = ((x($profile,'about') == 1) ? t('About:') : False);
# $tpl = file_get_contents( dirname(__file__).'/forumdirectory_item.tpl');
$tpl = get_markup_template( 'forumdirectory_item.tpl', 'addon/forumdirectory/' );
$entry = replace_macros($tpl,array(
'$id' => $rr['id'],
'$profile-link' => $profile_link,
'$photo' => $a->get_cached_avatar_image($rr[$photo]),
'$alt-text' => $rr['name'],
'$name' => $rr['name'],
'$details' => $pdesc . $details,
'$page-type' => $page_type,
'$profile' => $profile,
'$location' => template_escape($location),
'$gender' => $gender,
'$pdesc' => $pdesc,
'$marital' => $marital,
'$homepage' => $homepage,
'$about' => $about,
));
$arr = array('contact' => $rr, 'entry' => $entry);
call_hooks('directory_item', $arr);
unset($profile);
unset($location);
$o .= $entry;
}
$o .= "<div class=\"directory-end\" ></div>\r\n";
$o .= paginate($a);
}
else
info( t("No entries \x28some entries may be hidden\x29.") . EOL);
return $o;
}

View file

@ -0,0 +1,42 @@
<div class="forumdirectory-item" id="forumdirectory-item-$id" >
<div class="forumdirectory-photo-wrapper" id="forumdirectory-photo-wrapper-$id" >
<div class="forumdirectory-photo" id="forumdirectory-photo-$id" >
<a href="$profile-link" class="forumdirectory-profile-link" id="forumdirectory-profile-link-$id" >
<img class="forumdirectory-photo-img photo" src="$photo" alt="$alt-text" title="$alt-text" />
</a>
</div>
</div>
<div class="forumdirectory-profile-wrapper" id="forumdirectory-profile-wrapper-$id" >
<div class="contact-name" id="forumdirectory-name-$id">$name</div>
<div class="page-type">$page-type</div>
{{ if $pdesc }}<div class="forumdirectory-profile-title">$profile.pdesc</div>{{ endif }}
<div class="forumdirectory-detailcolumns-wrapper" id="forumdirectory-detailcolumns-wrapper-$id">
<div class="forumdirectory-detailscolumn-wrapper" id="forumdirectory-detailscolumn1-wrapper-$id">
{{ if $location }}
<dl class="location"><dt class="location-label">$location</dt>
<dd class="adr">
{{ if $profile.address }}<div class="street-address">$profile.address</div>{{ endif }}
<span class="city-state-zip">
<span class="locality">$profile.locality</span>{{ if $profile.locality }}, {{ endif }}
<span class="region">$profile.region</span>
<span class="postal-code">$profile.postal-code</span>
</span>
{{ if $profile.country-name }}<span class="country-name">$profile.country-name</span>{{ endif }}
</dd>
</dl>
{{ endif }}
{{ if $gender }}<dl class="mf"><dt class="gender-label">$gender</dt> <dd class="x-gender">$profile.gender</dd></dl>{{ endif }}
</div>
<div class="forumdirectory-detailscolumn-wrapper" id="forumdirectory-detailscolumn2-wrapper-$id">
{{ if $marital }}<dl class="marital"><dt class="marital-label"><span class="heart">&hearts;</span>$marital</dt><dd class="marital-text">$profile.marital</dd></dl>{{ endif }}
{{ if $homepage }}<dl class="homepage"><dt class="homepage-label">$homepage</dt><dd class="homepage-url"><a href="$profile.homepage" target="external-link">$profile.homepage</a></dd></dl>{{ endif }}
</div>
</div>
<div class="forumdirectory-copy-wrapper" id="forumdirectory-copy-wrapper-$id" >
{{ if $about }}<dl class="forumdirectory-copy"><dt class="forumdirectory-copy-label">$about</dt><dd class="forumdirectory-copy-data">$profile.about</dd></dl>{{ endif }}
</div>
</div>
</div>

View file

@ -0,0 +1,42 @@
<div class="forumdirectory-item" id="forumdirectory-item-{{$id}}" >
<div class="forumdirectory-photo-wrapper" id="forumdirectory-photo-wrapper-{{$id}}" >
<div class="forumdirectory-photo" id="forumdirectory-photo-{{$id}}" >
<a href="{{$profile}}-link" class="forumdirectory-profile-link" id="forumdirectory-profile-link-{{$id}}" >
<img class="forumdirectory-photo-img photo" src="{{$photo}}" alt="{{$alt}}-text" title="{{$alt}}-text" />
</a>
</div>
</div>
<div class="forumdirectory-profile-wrapper" id="forumdirectory-profile-wrapper-{{$id}}" >
<div class="contact-name" id="forumdirectory-name-{{$id}}">{{$name}}</div>
<div class="page-type">{{$page}}-type</div>
{{if $pdesc}}<div class="forumdirectory-profile-title">{{$profile.pdesc}}</div>{{/if}}
<div class="forumdirectory-detailcolumns-wrapper" id="forumdirectory-detailcolumns-wrapper-{{$id}}">
<div class="forumdirectory-detailscolumn-wrapper" id="forumdirectory-detailscolumn1-wrapper-{{$id}}">
{{if $location}}
<dl class="location"><dt class="location-label">{{$location}}</dt>
<dd class="adr">
{{if $profile.address}}<div class="street-address">{{$profile.address}}</div>{{/if}}
<span class="city-state-zip">
<span class="locality">{{$profile.locality}}</span>{{if $profile.locality}}, {{/if}}
<span class="region">{{$profile.region}}</span>
<span class="postal-code">{{$profile.postal-code}}</span>
</span>
{{if $profile.country-name}}<span class="country-name">{{$profile.country-name}}</span>{{/if}}
</dd>
</dl>
{{/if}}
{{if $gender}}<dl class="mf"><dt class="gender-label">{{$gender}}</dt> <dd class="x-gender">{{$profile.gender}}</dd></dl>{{/if}}
</div>
<div class="forumdirectory-detailscolumn-wrapper" id="forumdirectory-detailscolumn2-wrapper-{{$id}}">
{{if $marital}}<dl class="marital"><dt class="marital-label"><span class="heart">&hearts;</span>{{$marital}}</dt><dd class="marital-text">{{$profile.marital}}</dd></dl>{{/if}}
{{if $homepage}}<dl class="homepage"><dt class="homepage-label">{{$homepage}}</dt><dd class="homepage-url"><a href="{{$profile.homepage}}" target="external-link">{{$profile.homepage}}</a></dd></dl>{{/if}}
</div>
</div>
<div class="forumdirectory-copy-wrapper" id="forumdirectory-copy-wrapper-{{$id}}" >
{{if $about}}<dl class="forumdirectory-copy"><dt class="forumdirectory-copy-label">{{$about}}</dt><dd class="forumdirectory-copy-data">{{$profile.about}}</dd></dl>{{/if}}
</div>
</div>
</div>

BIN
forumlist.tgz Normal file

Binary file not shown.

22
forumlist/forumlist.css Normal file
View file

@ -0,0 +1,22 @@
#hide-forum-list {
opacity: 0.3;
filter:alpha(opacity=30);
}
#hide-forum-list:hover {
opacity: 1.0;
filter:alpha(opacity=100);
}
#forumlist-settings-label, #forumlist-random-label, #forumlist-profile-label, #forumlist-network-label {
float: left;
width: 200px;
margin-bottom: 25px;
}
#forumlist-max-forumlists, #forumlist-random, #forumlist-profile, #forumlist-network {
float: left;
}

182
forumlist/forumlist.php Normal file
View file

@ -0,0 +1,182 @@
<?php
/**
* Name: ForumList
* Description: Shows list of subscribed community forums on network sidebar
* Version: 1.1
* Author: Mike Macgirvin <mike@macgirvin.com>
* based on pages plugin by
* Author: Michael Vogel <ike@piratenpartei.de>
*
*/
function forumlist_install() {
register_hook('network_mod_init', 'addon/forumlist/forumlist.php', 'forumlist_network_mod_init');
register_hook('plugin_settings', 'addon/forumlist/forumlist.php', 'forumlist_plugin_settings');
register_hook('plugin_settings_post', 'addon/forumlist/forumlist.php', 'forumlist_plugin_settings_post');
register_hook('profile_advanced', 'addon/forumlist/forumlist.php', 'forumlist_profile_advanced');
}
function forumlist_uninstall() {
unregister_hook('network_mod_init', 'addon/forumlist/forumlist.php', 'forumlist_network_mod_init');
unregister_hook('plugin_settings', 'addon/forumlist/forumlist.php', 'forumlist_plugin_settings');
unregister_hook('plugin_settings_post', 'addon/forumlist/forumlist.php', 'forumlist_plugin_settings_post');
unregister_hook('profile_advanced', 'addon/forumlist/forumlist.php', 'forumlist_profile_advanced');
}
function forumlist_getpage($uid,$showhidden = true,$randomise = false, $showprivate = false) {
$forumlist = array();
$order = (($showhidden) ? '' : " and hidden = 0 ");
$order .= (($randomise) ? ' order by rand() ' : ' order by name asc ');
$select = "`forum` = 1";
if ($showprivate) {
$select = "( `forum` = 1 OR `prv` = 1 )";
}
$contacts = q("SELECT `contact`.`id`, `contact`.`url`, `contact`.`name`, `contact`.`micro` from contact
WHERE `network`= 'dfrn' AND $select AND `uid` = %d
and blocked = 0 and hidden = 0 and pending = 0 and archive = 0
$order ",
intval($uid)
);
// Look if the profile is a community page
foreach($contacts as $contact) {
$forumlist[] = array("url"=>$contact["url"], "name"=>$contact["name"], "id"=>$contact["id"], "micro"=>$contact['micro']);
}
return($forumlist);
}
function forumlist_network_mod_init($a,$b) {
if(! intval(get_pconfig(local_user(),'forumlist','show_on_network')))
return;
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/forumlist/forumlist.css' . '" media="all" />' . "\r\n";
$forumlist = '<div id="forumlist-sidebar" class="widget">
<div class="title tool">
<h3>'.t("Forums").'</h3></div>';
$forumlist .= '<div id="hide-forum-list" class="fakelink" onclick="openClose(\'forum-list\');" >'
. t('show/hide') . '</div>'
. '<div id="forum-list" style="display: none;">';
$randomise = intval(get_pconfig(local_user(),'forumlist','randomise'));
$contacts = forumlist_getpage($a->user['uid'],true,$randomise, true);
if(count($contacts)) {
foreach($contacts as $contact) {
$forumlist .= '<a href="' . $a->get_baseurl() . '/redir/' . $contact["id"] . '" title="' . $contact['url'] . '" class="label sparkle" target="external-link"><img class="forumlist-img" height="20" width="20" src="' . $contact['micro'] .'" alt="' . $contact['url'] . '" /></a> <a href="' . $a->get_baseurl() . '/network?f=&cid=' . $contact['id'] . '" >' . $contact["name"]."</a><br />";
}
}
else {
$forumlist .= t('No forum subscriptions');
}
$forumlist .= "</div></div>";
if (sizeof($contacts) > 0)
$a->page['aside'] = $forumlist . $a->page['aside'];
}
function forumlist_profile_advanced($a,&$b) {
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/forumlist/forumlist.css' . '" media="all" />' . "\r\n";
$profile = intval(get_pconfig($a->profile['profile_uid'],'forumlist','show_on_profile'));
if(! $profile)
return;
$forumlist = '<div id="forumlist-profile">
<div class="title">'.t("Forums:").'</div>
<div id="profile-forumlist-list">';
// place holder in case somebody wants configurability
$show_total = 9999;
$randomise = true;
$contacts = forumlist_getpage($a->user['uid'],false,$randomise,false);
$total_shown = 0;
$more = false;
foreach($contacts as $contact) {
$forumlist .= micropro($contact,false,'forumlist-profile-advanced');
$total_shown ++;
if($total_shown == $show_total)
break;
}
$forumlist .= '</div></div><div class="clear"></div>';
if(count($contacts) > 0)
$b .= $forumlist;
}
function forumlist_plugin_settings_post($a,$post) {
if(! local_user() || (! x($_POST,'forumlist-settings-submit')))
return;
// set_pconfig(local_user(),'forumlist','max_forumlists',intval($_POST['forumlist_max_forumlists']));
set_pconfig(local_user(),'forumlist','randomise',intval($_POST['forumlist_random']));
set_pconfig(local_user(),'forumlist','show_on_profile',intval($_POST['forumlist_profile']));
set_pconfig(local_user(),'forumlist','show_on_network',intval($_POST['forumlist_network']));
info( t('Forumlist settings updated.') . EOL);
}
function forumlist_plugin_settings(&$a,&$s) {
if(! local_user())
return;
/* Add our stylesheet to the forumlist so we can make our settings look nice */
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/forumlist/forumlist.css' . '" media="all" />' . "\r\n";
/* Get the current state of our config variable */
$randomise = intval(get_pconfig(local_user(),'forumlist','randomise'));
$randomise_checked = (($randomise) ? ' checked="checked" ' : '');
$profile = intval(get_pconfig(local_user(),'forumlist','show_on_profile'));
$profile_checked = (($profile) ? ' checked="checked" ' : '');
$network = intval(get_pconfig(local_user(),'forumlist','show_on_network'));
$network_checked = (($network) ? ' checked="checked" ' : '');
/* Add some HTML to the existing form */
$s .= '<div class="settings-block">';
$s .= '<h3>' . t('Forumlist Settings') . '</h3>';
$s .= '<div id="forumlist-settings-wrapper">';
$s .= '<label id="forumlist-random-label" for="forumlist-random">' . t('Randomise forum list') . '</label>';
$s .= '<input id="forumlist-random" type="checkbox" name="forumlist_random" value="1" ' . $randomise_checked . '/>';
$s .= '<div class="clear"></div>';
$s .= '<label id="forumlist-profile-label" for="forumlist-profile">' . t('Show forums on profile page') . '</label>';
$s .= '<input id="forumlist-profile" type="checkbox" name="forumlist_profile" value="1" ' . $profile_checked . '/>';
$s .= '<div class="clear"></div>';
$s .= '<label id="forumlist-network-label" for="forumlist-network">' . t('Show forums on network page') . '</label>';
$s .= '<input id="forumlist-network" type="checkbox" name="forumlist_network" value="1" ' . $network_checked . '/>';
$s .= '<div class="clear"></div>';
$s .= '</div>';
/* provide a submit button */
$s .= '<div class="settings-submit-wrapper" ><input type="submit" name="forumlist-settings-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
}

BIN
fromapp.tgz Normal file

Binary file not shown.

14
fromapp/fromapp.css Normal file
View file

@ -0,0 +1,14 @@
#fromapp-label, #fromapp-force-label {
float: left;
width: 200px;
margin-bottom: 25px;
}
#fromapp-input, #fromapp-force {
float: left;
}

101
fromapp/fromapp.php Normal file
View file

@ -0,0 +1,101 @@
<?php
/**
* Name: FromApp
* Description: Change the displayed application you are posting from
* Version: 1.0
* Author: Commander Zot
*
*/
function fromapp_install() {
register_hook('post_local', 'addon/fromapp/fromapp.php', 'fromapp_post_hook');
register_hook('plugin_settings', 'addon/fromapp/fromapp.php', 'fromapp_settings');
register_hook('plugin_settings_post', 'addon/fromapp/fromapp.php', 'fromapp_settings_post');
logger("installed fromapp");
}
function fromapp_uninstall() {
unregister_hook('post_local', 'addon/fromapp/fromapp.php', 'fromapp_post_hook');
unregister_hook('plugin_settings', 'addon/fromapp/fromapp.php', 'fromapp_settings');
unregister_hook('plugin_settings_post', 'addon/fromapp/fromapp.php', 'fromapp_settings_post');
logger("removed fromapp");
}
function fromapp_settings_post($a,$post) {
if(! local_user() || (! x($_POST,'fromapp-submit')))
return;
set_pconfig(local_user(),'fromapp','app',$_POST['fromapp-input']);
set_pconfig(local_user(),'fromapp','force',intval($_POST['fromapp-force']));
info( t('Fromapp settings updated.') . EOL);
}
function fromapp_settings(&$a,&$s) {
if(! local_user())
return;
/* Add our stylesheet to the page so we can make our settings look nice */
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/fromapp/fromapp.css' . '" media="all" />' . "\r\n";
/* Get the current state of our config variable */
$fromapp = get_pconfig(local_user(),'fromapp','app');
if($fromapp === false)
$fromapp = '';
$force = intval(get_pconfig(local_user(),'fromapp','force'));
$force_enabled = (($force) ? ' checked="checked" ' : '');
/* Add some HTML to the existing form */
$s .= '<div class="settings-block">';
$s .= '<h3>' . t('FromApp Settings') . '</h3>';
$s .= '<div id="fromapp-wrapper">';
$s .= '<label id="fromapp-label" for="fromapp-input">' . t('The application name you would like to show your posts originating from.') . '</label>';
$s .= '<input id="fromapp-input" type="text" name="fromapp-input" value="' . $fromapp . '" ' . '/>';
$s .= '<div class="clear"></div>';
$s .= '<label id="fromapp-force-label" for="fromapp-force">' . t('Use this application name even if another application was used.') . '</label>';
$s .= '<input id="fromapp-force" type="checkbox" name="fromapp-force" value="1" ' . $force_enabled . '/>';
$s .= '</div><div class="clear"></div>';
/* provide a submit button */
$s .= '<div class="settings-submit-wrapper" ><input type="submit" name="fromapp-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
}
function fromapp_post_hook(&$a,&$item) {
if(! local_user())
return;
if(local_user() != $item['uid'])
return;
$app = get_pconfig(local_user(), 'fromapp', 'app');
$force = intval(get_pconfig(local_user(), 'fromapp','force'));
if(($app === false) || (! strlen($app)))
return;
if(strlen(trim($item['app'])) && (! $force))
return;
$apps = explode(',',$app);
$item['app'] = trim($apps[mt_rand(0,count($apps)-1)]);
return;
}

BIN
fromgplus.tgz Normal file

Binary file not shown.

View file

@ -1 +1,15 @@
This extension is a preparation of the upcoming import of items via Google+
This extension fetches messages from a Google+ account and reshares it.
You have to place the following config values in your .htconfig.php:
$a->config['fromgplus']['key'] = "your key";
$a->config['fromgplus']['poll_interval'] = 10;
You need an API key for "Simple API Access".
- You go to https://code.google.com/apis/console/
- Then you go to "Services" and activate "Google+ API".
- After that you go to "API Access".
- At the bottom of the page you see "Simple API Access".
The value after "API key:" is the key that you need.

View file

@ -1,20 +1,24 @@
<?php
/**
* Name: From GPlus
* Description: Imports posts from a Google+ account and repeats them - not working by now
* Description: Imports posts from a Google+ account and repeats them
* Version: 0.1
* Author: Michael Vogel <ike@piratenpartei.de>
*
*/
define('FROMGPLUS_DEFAULT_POLL_INTERVAL', 30); // given in minutes
function fromgplus_install() {
register_hook('plugin_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
register_hook('plugin_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
register_hook('cron', 'addon/fromgplus/fromgplus.php', 'fromgplus_cron');
}
function fromgplus_uninstall() {
unregister_hook('plugin_settings', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings');
unregister_hook('plugin_settings_post', 'addon/fromgplus/fromgplus.php', 'fromgplus_addon_settings_post');
unregister_hook('cron', 'addon/fromgplus/fromgplus.php', 'fromgplus_cron');
}
function fromgplus_addon_settings(&$a,&$s) {
@ -55,129 +59,324 @@ function fromgplus_addon_settings_post(&$a,&$b) {
info( t('Google+ Import Settings saved.') . EOL);
}
}
/*
function html2bbcode($html) {
function fromgplus_cron($a,$b) {
$last = get_config('fromgplus','last_poll');
$poll_interval = intval(get_config('fromgplus','poll_interval'));
if(! $poll_interval)
$poll_interval = FROMGPLUS_DEFAULT_POLL_INTERVAL;
if($last) {
$next = $last + ($poll_interval * 60);
if($next > time()) {
logger('fromgplus: poll intervall not reached');
return;
}
}
logger('fromgplus: cron_start');
$r = q("SELECT * FROM `pconfig` WHERE `cat` = 'fromgplus' AND `k` = 'enable' AND `v` = '1' ORDER BY RAND() ");
if(count($r)) {
foreach($r as $rr) {
$account = get_pconfig($rr['uid'],'fromgplus','account');
if ($account) {
logger('fromgplus: fetching for user '.$rr['uid']);
fromgplus_fetch($a, $rr['uid']);
}
}
}
logger('fromgplus: cron_end');
set_config('fromgplus','last_poll', time());
}
function fromgplus_post($a, $uid, $source, $body, $location) {
//$uid = 2;
$body = trim($body);
if (substr($body, 0, 3) == "[b]") {
$pos = strpos($body, "[/b]");
$title = substr($body, 3, $pos-3);
$body = trim(substr($body, $pos+4));
} else
$title = "";
$_SESSION['authenticated'] = true;
$_SESSION['uid'] = $uid;
$_REQUEST['type'] = 'wall';
$_REQUEST['api_source'] = true;
$_REQUEST['profile_uid'] = $uid;
$_REQUEST['source'] = $source;
// $_REQUEST['verb']
// $_REQUEST['parent']
// $_REQUEST['parent_uri']
$_REQUEST['title'] = $title;
$_REQUEST['body'] = $body;
$_REQUEST['location'] = $location;
logger('fromgplus: posting for user '.$uid);
require_once('mod/item.php');
//print_r($_REQUEST);
item_post($a);
}
function fromgplus_html2bbcode($html) {
$bbcode = html_entity_decode($html, ENT_QUOTES, 'UTF-8');
$bbcode = str_replace(array("\n"), array(""), $bbcode);
$bbcode = str_replace(array("<b>", "</b>"), array("[b]", "[/b]"), $bbcode);
$bbcode = str_replace(array("<i>", "</i>"), array("[i]", "[/i]"), $bbcode);
$bbcode = str_replace(array("<s>", "</s>"), array("[s]", "[/s]"), $bbcode);
$bbcode = str_replace(array("<br />"), array("\n"), $bbcode);
$bbcode = str_ireplace(array("\n"), array(""), $bbcode);
$bbcode = str_ireplace(array("<b>", "</b>"), array("[b]", "[/b]"), $bbcode);
$bbcode = str_ireplace(array("<i>", "</i>"), array("[i]", "[/i]"), $bbcode);
$bbcode = str_ireplace(array("<s>", "</s>"), array("[s]", "[/s]"), $bbcode);
$bbcode = str_ireplace(array("<br />"), array("\n"), $bbcode);
$bbcode = str_ireplace(array("<br/>"), array("\n"), $bbcode);
$bbcode = str_ireplace(array("<br>"), array("\n"), $bbcode);
$bbcode = trim(strip_tags($bbcode));
return($bbcode);
}
function friendicapost($post) {
global $friendica;
function fromgplus_parse_query($var)
{
/**
* Use this function to parse out the query array element from
* the output of parse_url().
*/
$var = parse_url($var, PHP_URL_QUERY);
$var = html_entity_decode($var);
$var = explode('&', $var);
$arr = array();
$api = new Statusnet($friendica["user"], $friendica["pw"], "GooglePlus", $friendica["server"]);
$ret = $api->updateStatus($post);
$api->endSession();
foreach($var as $val) {
$x = explode('=', $val);
$arr[$x[0]] = $x[1];
}
unset($val, $x, $var);
return $arr;
}
function handleattachments($item) {
function fromgplus_cleanupgoogleproxy($fullImage, $image) {
$preview = "/w".$fullImage->width."-h".$fullImage->height."/";
$preview2 = "/w".$fullImage->width."-h".$fullImage->height."-p/";
$fullImage = str_replace(array($preview, $preview2), array("/", "/"), $fullImage->url);
$preview = "/w".$image->width."-h".$image->height."/";
$preview2 = "/w".$image->width."-h".$image->height."-p/";
$image = str_replace(array($preview, $preview2), array("/", "/"), $image->url);
$cleaned = array();
$queryvar = fromgplus_parse_query($fullImage);
if ($queryvar['url'] != "")
$cleaned["full"] = urldecode($queryvar['url']);
else
$cleaned["full"] = $fullImage;
if (@exif_imagetype($cleaned["full"]) == 0)
$cleaned["full"] = "";
$queryvar = fromgplus_parse_query($image);
if ($queryvar['url'] != "")
$cleaned["preview"] = urldecode($queryvar['url']);
else
$cleaned["preview"] = $image;
if (@exif_imagetype($cleaned["preview"]) == 0)
$cleaned["preview"] = "";
if ($cleaned["full"] == "") {
$cleaned["full"] = $cleaned["preview"];
$cleaned["preview"] = "";
}
if ($cleaned["full"] == $cleaned["preview"])
$cleaned["preview"] = "";
if ($cleaned["full"] == "")
if (@exif_imagetype($fullImage) != 0)
$cleaned["full"] = $fullImage;
if ($cleaned["full"] == "")
if (@exif_imagetype($image) != 0)
$cleaned["full"] = $fullImage;
return($cleaned);
}
function fromgplus_handleattachments($item) {
$post = "";
$quote = "";
foreach ($item->object->attachments as $attachment) {
switch($attachment->objectType) {
case "video":
//$post .= "\n\n[url=".$attachment->url."]".
// "[size=large][b]".html2bbcode($attachment->displayName)."[/b][/size][/url]\n";
$post .= "\n\n[bookmark=".$attachment->url."]".html2bbcode($attachment->displayName)."[/bookmark]\n";
$post .= "\n\n[bookmark=".$attachment->url."]".fromgplus_html2bbcode($attachment->displayName)."[/bookmark]\n";
//if (strpos($attachment->embed->url, "youtube.com"))
// $post .= "[youtube]".$attachment->url."[/youtube]\n";
//else
/// $post .= "[url=".$attachment->url."][img]".$attachment->image->url."[/img][/url]\n";
/*$images = cleanupgoogleproxy($attachment->fullImage, $attachment->image);
if ($images["preview"] != "")
$post .= "\n[url=".$images["full"]."][img]".$images["preview"]."[/img][/url]\n";
elseif ($images["full"] != "")
$post .= "\n[img]".$images["full"]."[/img]\n";*/
///$post .= "[quote]".trim(html2bbcode($attachment->content))."[/quote]";
break;
case "article":
//$post .= "\n\n[url=".$attachment->url."]".
// "[size=large][b]".html2bbcode($attachment->displayName)."[/b][/size][/url]\n";
$post .= "\n\n[bookmark=".$attachment->url."]".html2bbcode($attachment->displayName)."[/bookmark]\n";
$post .= "[quote]".trim(html2bbcode($attachment->content))."[/quote]";
$post .= "\n\n[bookmark=".$attachment->url."]".fromgplus_html2bbcode($attachment->displayName)."[/bookmark]\n";
$images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
if ($images["preview"] != "")
$post .= "\n[url=".$images["full"]."][img]".$images["preview"]."[/img][/url]\n";
elseif ($images["full"] != "")
$post .= "\n[img]".$images["full"]."[/img]\n";
//$post .= "[quote]".trim(fromgplus_html2bbcode($attachment->content))."[/quote]";
$quote = trim(fromgplus_html2bbcode($attachment->content));
if ($quote != "")
$quote = "\n[quote]".$quote."[/quote]";
break;
case "photo":
//$post .= "\n\n[url=".$attachment->fullImage->url."]".
// "[img]".$attachment->fullImage->url."[/img][/url]\n";
$post .= "\n\n[img]".$attachment->fullImage->url."[/img]\n";
$images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
if ($images["preview"] != "")
$post .= "\n[url=".$images["full"]."][img]".$images["preview"]."[/img][/url]\n";
elseif ($images["full"] != "")
$post .= "\n[img]".$images["full"]."[/img]\n";
if ($attachment->displayName != "")
$post .= html2bbcode($attachment->displayName)."\n";
$post .= fromgplus_html2bbcode($attachment->displayName)."\n";
break;
case "photo-album":
$post .= "\n\n[url=".$attachment->url."]".
"[size=large][b]".html2bbcode($attachment->displayName)."[/b][/size][/url]\n";
$post .= "\n\n[bookmark=".$attachment->url."]".fromgplus_html2bbcode($attachment->displayName)."[/bookmark]\n";
$images = fromgplus_cleanupgoogleproxy($attachment->fullImage, $attachment->image);
if ($images["preview"] != "")
$post .= "\n[url=".$images["full"]."][img]".$images["preview"]."[/img][/url]\n";
elseif ($images["full"] != "")
$post .= "\n[img]".$images["full"]."[/img]\n";
break;
default:
print_r($attachment);
die();
case "album":
foreach($attachment->thumbnails as $thumb) {
$preview = "/w".$thumb->image->width."-h".$thumb->image->height."/";
$preview2 = "/w".$thumb->image->width."-h".$thumb->image->height."-p/";
$image = str_replace(array($preview, $preview2), array("/", "/"), $thumb->image->url);
$post .= "\n[url=".$thumb->url."][img]".$image."[/img][/url]\n";
}
break;
//default:
// die($attachment->objectType);
}
}
return($post);
return($post.$quote);
}
$result =
file_get_contents("https://www.googleapis.com/plus/v1/people/".$google["id"]."/activities/public?alt=json&pp=1&key=".$google["key"]."&maxResults=".$google["maxfetch"]);
$activities = json_decode($result);
function fromgplus_fetch($a, $uid) {
$maxfetch = 20;
$state = array("lastid"=>'');
if (file_exists($statefile))
$state = unserialize(file_get_contents($statefile));
$account = get_pconfig($uid,'fromgplus','account');
$key = get_config('fromgplus','key');
$lastid = "";
$result = fetch_url("https://www.googleapis.com/plus/v1/people/".$account."/activities/public?alt=json&pp=1&key=".$key."&maxResults=".$maxfetch);
//$result = file_get_contents("google.txt");
//file_put_contents("google.txt", $result);
foreach($activities->items as $item) {
if ($item->id == $state["lastid"])
break;
$activities = json_decode($result);
if ($lastid == "")
$lastid = $item->id;
$initiallastdate = get_pconfig($uid,'fromgplus','lastdate');
switch($item->object->objectType) {
case "note":
$post = html2bbcode($item->object->content);
$lastdate = 0;
if (is_array($item->object->attachments))
$post .= handleattachments($item);
friendicapost($post);
break;
$reversed = array_reverse($activities->items);
case "activity":
$post = html2bbcode($item->annotation)."\n";
//$post .= html2bbcode("&#x2672; ");
$post .= html2bbcode("&#x267B; ");
$post .= "[url=".$item->object->actor->url."]".$item->object->actor->displayName."[/url]";
$post .= " \n";
//$post .= "[quote]";
foreach($reversed as $item) {
if (strtotime($item->published) <= $initiallastdate)
continue;
$post .= html2bbcode($item->object->content);
if ($lastdate < strtotime($item->published))
$lastdate = strtotime($item->published);
if (is_array($item->object->attachments))
$post .= "\n".trim(handleattachments($item));
if ($item->access->description == "Public")
switch($item->object->objectType) {
case "note":
$post = fromgplus_html2bbcode($item->object->content);
//$post .= "[/quote]";
if (is_array($item->object->attachments))
$post .= fromgplus_handleattachments($item);
friendicapost($post);
break;
// geocode, placeName
if (isset($item->address))
$location = $item->address;
else
$location = "";
default:
print_r($item);
die();
break;
fromgplus_post($a, $uid, $item->provider->title, $post, $location);
break;
case "activity":
$post = fromgplus_html2bbcode($item->annotation)."\n";
if (intval(get_config('system','new_share'))) {
$post .= "[share author='".str_replace("'", "&#039;",$item->object->actor->displayName).
"' profile='".$item->object->actor->url.
"' avatar='".$item->object->actor->image->url.
"' link='".$item->object->url."']";
$post .= fromgplus_html2bbcode($item->object->content);
if (is_array($item->object->attachments))
$post .= "\n".trim(fromgplus_handleattachments($item));
$post .= "[/share]";
} else {
$post .= fromgplus_html2bbcode("&#x2672;");
$post .= " [url=".$item->object->actor->url."]".$item->object->actor->displayName."[/url] \n";
$post .= fromgplus_html2bbcode($item->object->content);
if (is_array($item->object->attachments))
$post .= "\n".trim(fromgplus_handleattachments($item));
}
if (isset($item->address))
$location = $item->address;
else
$location = "";
fromgplus_post($a, $uid, $item->provider->title, $post, $location);
break;
}
}
if ($lastdate != 0)
set_pconfig($uid,'fromgplus','lastdate', $lastdate);
}
if ($lastid != "") {
$state['lastid'] = $lastid;
file_put_contents($statefile, serialize($state));
/*
// Test
require_once("boot.php");
if(@is_null($a)) {
$a = new App;
}
if(@is_null($db)) {
@include(".htconfig.php");
require_once("include/dba.php");
$db = new dba($db_host, $db_user, $db_pass, $db_data);
unset($db_host, $db_user, $db_pass, $db_data);
};
$test = array();
fromgplus_cron($a, $test);
*/

Binary file not shown.

View file

@ -55,7 +55,7 @@ function gravatar_lookup($a, &$b) {
* Display admin settings for this addon
*/
function gravatar_plugin_admin (&$a, &$o) {
$t = file_get_contents( dirname(__file__)."/admin.tpl");
$t = get_markup_template( "admin.tpl", "addon/gravatar/" );
$default_avatar = get_config('gravatar', 'default_img');
$rating = get_config('gravatar', 'rating');

View file

@ -0,0 +1,3 @@
{{include file="field_select.tpl" field=$default_avatar}}
{{include file="field_select.tpl" field=$rating}}
<div class="submit"><input type="submit" value="{{$submit}}" /></div>

BIN
group_text.tgz Normal file

Binary file not shown.

View file

@ -43,7 +43,7 @@ function group_text_settings_post($a,$post) {
return;
set_pconfig(local_user(),'system','groupedit_image_limit',intval($_POST['group_text']));
info( t('Editplain settings updated.') . EOL);
info( t('Group Text settings updated.') . EOL);
}

Binary file not shown.

View file

@ -29,6 +29,7 @@ function impressum_footer($a, &$b) {
$text = bbcode(get_config('impressum','footer_text'), true);
if (! $text == '') {
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'.$a->get_baseurl().'/addon/impressum/impressum.css" media="all" />';
$b .= '<div class="clear"></div>';
$b .= '<div id="impressum_footer">'.$text.'</div>';
}
}
@ -77,7 +78,7 @@ function impressum_plugin_admin_post (&$a) {
info( t('Settings updated.'). EOL );
}
function impressum_plugin_admin (&$a, &$o) {
$t = file_get_contents( dirname(__file__). "/admin.tpl" );
$t = get_markup_template( "admin.tpl", "addon/impressum/" );
$o = replace_macros($t, array(
'$submit' => t('Submit'),
'$owner' => array('owner', t('Site Owner'), get_config('impressum','owner'), t('The page operators name.')),

0
impressum/admin.tpl → impressum/view/admin.tpl Executable file → Normal file
View file

View file

@ -0,0 +1,7 @@
{{include file="field_input.tpl" field=$owner}}
{{include file="field_input.tpl" field=$ownerprofile}}
{{include file="field_textarea.tpl" field=$postal}}
{{include file="field_textarea.tpl" field=$notes}}
{{include file="field_input.tpl" field=$email}}
{{include file="field_textarea.tpl" field=$footer_text}}
<div class="submit"><input type="submit" name="page_site" value="{{$submit}}" /></div>

BIN
irc.tgz

Binary file not shown.

View file

@ -110,7 +110,7 @@ function irc_content(&$a) {
$o .= <<< EOT
<h2>IRC chat</h2>
<p><a href="http://tldp.org/HOWTO/IRC/beginners.html" target="_blank">A beginner's guide to using IRC. [en]</a></p>
<iframe src="http://webchat.freenode.net?channels=$channels" width="600" height="600"></iframe>
<iframe src="//webchat.freenode.net?channels=$channels" width="600" height="600"></iframe>
EOT;
return $o;

Binary file not shown.

View file

@ -3,7 +3,7 @@
/**
* Name: jappixmini
* Description: Provides a Facebook-like chat using Jappix Mini
* Version: 1.0
* Version: 1.0.1
* Author: leberwurscht <leberwurscht@hoegners.de>
*
*/
@ -221,6 +221,8 @@ function jappixmini_settings(&$a, &$s) {
$activate = get_pconfig(local_user(),'jappixmini','activate');
$activate = intval($activate) ? ' checked="checked"' : '';
$dontinsertchat = get_pconfig(local_user(),'jappixmini','dontinsertchat');
$insertchat = !(intval($dontinsertchat) ? ' checked="checked"' : '');
$username = get_pconfig(local_user(),'jappixmini','username');
$username = htmlentities($username);
@ -261,46 +263,49 @@ function jappixmini_settings(&$a, &$s) {
$s .= '<div class="settings-block">';
$s .= '<h3>Jappix Mini addon settings</h3>';
$s .= '<h3>'.t('Jappix Mini addon settings').'</h3>';
$s .= '<div>';
$s .= '<label for="jappixmini-activate">Activate addon</label>';
$s .= '<label for="jappixmini-activate">'.t('Activate addon').'</label>';
$s .= ' <input id="jappixmini-activate" type="checkbox" name="jappixmini-activate" value="1"'.$activate.' />';
$s .= '<br />';
$s .= '<label for="jappixmini-username">Jabber username</label>';
$s .= '<label for"jappixmini-dont-insertchat">'.t('Do <em>not</em> insert the Jappixmini Chat-Widget into the webinterface').'</label>';
$s .= '<input id="jappixmini-dont-insertchat" type="checkbox" name="jappixmini-dont-insertchat" value="1"'.$insertchat.' />';
$s .= '<br />';
$s .= '<label for="jappixmini-username">'.t('Jabber username').'</label>';
$s .= ' <input id="jappixmini-username" type="text" name="jappixmini-username" value="'.$username.'" />';
$s .= '<br />';
$s .= '<label for="jappixmini-server">Jabber server</label>';
$s .= '<label for="jappixmini-server">'.t('Jabber server').'</label>';
$s .= ' <input id="jappixmini-server" type="text" name="jappixmini-server" value="'.$server.'" />';
$s .= '<br />';
$s .= '<label for="jappixmini-bosh">Jabber BOSH host</label>';
$s .= '<label for="jappixmini-bosh">'.t('Jabber BOSH host').'</label>';
$s .= ' <input id="jappixmini-bosh" type="text" name="jappixmini-bosh" value="'.$bosh.'" />';
$s .= '<br />';
$s .= '<label for="jappixmini-password">Jabber password</label>';
$s .= '<label for="jappixmini-password">'.t('Jabber password').'</label>';
$s .= ' <input type="hidden" id="jappixmini-password" name="jappixmini-encrypted-password" value="'.$password.'" />';
$s .= ' <input id="jappixmini-clear-password" type="password" value="" onchange="jappixmini_set_password();" />';
$s .= '<br />';
$onchange = "document.getElementById('jappixmini-friendica-password').disabled = !this.checked;jappixmini_set_password();";
$s .= '<label for="jappixmini-encrypt">Encrypt Jabber password with Friendica password (recommended)</label>';
$s .= '<label for="jappixmini-encrypt">'.t('Encrypt Jabber password with Friendica password (recommended)').'</label>';
$s .= ' <input id="jappixmini-encrypt" type="checkbox" name="jappixmini-encrypt" onchange="'.$onchange.'" value="1"'.$encrypt_checked.' />';
$s .= '<br />';
$s .= '<label for="jappixmini-friendica-password">Friendica password</label>';
$s .= '<label for="jappixmini-friendica-password">'.t('Friendica password').'</label>';
$s .= ' <input id="jappixmini-friendica-password" name="jappixmini-friendica-password" type="password" onchange="jappixmini_set_password();" value=""'.$encrypt_disabled.' />';
$s .= '<br />';
$s .= '<label for="jappixmini-autoapprove">Approve subscription requests from Friendica contacts automatically</label>';
$s .= '<label for="jappixmini-autoapprove">'.t('Approve subscription requests from Friendica contacts automatically').'</label>';
$s .= ' <input id="jappixmini-autoapprove" type="checkbox" name="jappixmini-autoapprove" value="1"'.$autoapprove.' />';
$s .= '<br />';
$s .= '<label for="jappixmini-autosubscribe">Subscribe to Friendica contacts automatically</label>';
$s .= '<label for="jappixmini-autosubscribe">'.t('Subscribe to Friendica contacts automatically').'</label>';
$s .= ' <input id="jappixmini-autosubscribe" type="checkbox" name="jappixmini-autosubscribe" value="1"'.$autosubscribe.' />';
$s .= '<br />';
$s .= '<label for="jappixmini-purge">Purge internal list of jabber addresses of contacts</label>';
$s .= '<label for="jappixmini-purge">'.t('Purge internal list of jabber addresses of contacts').'</label>';
$s .= ' <input id="jappixmini-purge" type="checkbox" name="jappixmini-purge" value="1" />';
$s .= '<br />';
if ($info_text) $s .= '<br />Configuration help:<p style="margin-left:2em;">'.$info_text.'</p>';
$s .= '<br />Status:<p style="margin-left:2em;">Addon knows '.$address_cnt.' Jabber addresses of '.$contact_cnt.' Friendica contacts (takes some time, usually 10 minutes, to update).</p>';
$s .= '<input type="submit" name="jappixmini-submit" value="' . t('Submit') . '" />';
$s .= ' <input type="button" value="Add contact" onclick="jappixmini_addon_subscribe();" />';
$s .= ' <input type="button" value="'.t('Add contact').'" onclick="jappixmini_addon_subscribe();" />';
$s .= '</div>';
$s .= '</div>';
@ -379,6 +384,7 @@ function jappixmini_settings_post(&$a,&$b) {
set_pconfig($uid,'jappixmini','autosubscribe',intval($b['jappixmini-autosubscribe']));
set_pconfig($uid,'jappixmini','autoapprove',intval($b['jappixmini-autoapprove']));
set_pconfig($uid,'jappixmini','activate',intval($b['jappixmini-activate']));
set_pconfig($uid,'jappixmini','dontinsertchat',intval($b['jappixmini-dont-insertchat']));
set_pconfig($uid,'jappixmini','encrypt',$encrypt);
info( 'Jappix Mini settings saved.' );
@ -395,7 +401,8 @@ function jappixmini_script(&$a,&$s) {
if(! local_user()) return;
$activate = get_pconfig(local_user(),'jappixmini','activate');
if (!$activate) return;
$dontinsertchat = get_pconfig(local_user(), 'jappixmini','dontinsertchat');
if (!$activate or $dontinsertchat) return;
$a->page['htmlhead'] .= '<script type="text/javascript" src="' . $a->get_baseurl() . '/addon/jappixmini/jappix/php/get.php?t=js&amp;g=mini.xml"></script>'."\r\n";
$a->page['htmlhead'] .= '<script type="text/javascript" src="' . $a->get_baseurl() . '/addon/jappixmini/jappix/php/get.php?t=js&amp;f=presence.js~caps.js~name.js~roster.js"></script>'."\r\n";

Binary file not shown.

View file

@ -196,7 +196,13 @@ class qqUploadedFileXhr {
*/
function save() {
$input = fopen("php://input", "r");
$this->pathnm = tempnam(sys_get_temp_dir(),'frn');
$upload_dir = get_config('system','tempdir');
if(! $upload_dir)
$upload_dir = sys_get_temp_dir();
$this->pathnm = tempnam($upload_dir,'frn');
$temp = fopen($this->pathnm,"w");
$realSize = stream_copy_to_stream($input, $temp);

Binary file not shown.

View file

@ -60,7 +60,7 @@ function libravatar_lookup($a, &$b) {
* Display admin settings for this addon
*/
function libravatar_plugin_admin (&$a, &$o) {
$t = file_get_contents( dirname(__file__)."/admin.tpl");
$t = get_markup_template( "admin.tpl", "addon/libravatar" );
$default_avatar = get_config('libravatar', 'default_img');

View file

@ -0,0 +1,2 @@
{{include file="field_select.tpl" field=$default_avatar}}
<div class="submit"><input type="submit" value="{{$submit}}" /></div>

Binary file not shown.

View file

@ -1,6 +1,5 @@
#ljpost-enable-label, #ljpost-username-label, #ljpost-password-label, #ljpost-bydefault-label {
<<<<<<< HEAD
float: left;
width: 200px;
margin-top: 10px;
@ -15,18 +14,3 @@
margin-top: 15px;
}
=======
float: left;
width: 200px;
margin-top: 10px;
}
#ljpost-checkbox, #ljpost-username, #ljpost-password, #ljpost-bydefault {
float: left;
margin-top: 10px;
}
#ljpost-submit {
margin-top: 15px;
}
>>>>>>> 99d9fddb6af9e872266666038447771e42ce13b4

Binary file not shown.

View file

@ -66,11 +66,12 @@ function mathjax_plugin_admin_post (&$a) {
info( t('Settings updated.'). EOL);
}
function mathjax_plugin_admin (&$a, &$o) {
$t = file_get_contents( dirname(__file__)."/admin.tpl");
if (get_config('mathjax','baseurl','') == '') {
set_config('mathjax','baseurl','http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML');
}
$o = replace_macros( $t, array(
$t = get_markup_template( "admin.tpl", "addon/mathjax/" );
if (get_config('mathjax','baseurl','') == '') {
set_config('mathjax','baseurl','http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML');
}
$o = replace_macros( $t, array(
'$baseurl' => array('baseurl', t('MathJax Base URL'), get_config('mathjax','baseurl' ), t('The URL for the javascript file that should be included to use MathJax. Can be either the MathJax CDN or another installation of MathJax.')),
));
));
}

View file

@ -0,0 +1,2 @@
{{include file="field_input.tpl" field=$baseurl}}
<div class="submit"><input type="submit" name="page_site" value="{{$submit}}" /></div>

BIN
morepokes.tgz Normal file

Binary file not shown.

View file

@ -19,9 +19,8 @@ function morepokes_poke_verbs($a,&$b) {
$b['bitchslap'] = array('bitchslapped', t('bitchslap'), t('bitchslapped'));
$b['shag'] = array('shag', t('shag'), t('shagged'));
$b['somethingobscenelybiological'] = array('something obscenely biological', t('do something obscenely biological to'), t('did something obscenely biological to'));
$b['newpokefeature'] = array('pointed out the new poke feature to', t('point out the new poke feature to'), t('pointed out the new poke feature to'));
$b['newpokefeature'] = array('pointed out the poke feature to', t('point out the poke feature to'), t('pointed out the poke feature to'));
$b['declareundyinglove'] = array('declared undying love for', t('declare undying love for'), t('declared undying love for'));
$b['setfireto'] = array('set fire to', t('set fire to'), t('set fire to'));
$b['patent'] = array('patented', t('patent'), t('patented'));
$b['strokebeard'] = array('stroked their beard at', t('stroke beard'), t('stroked their beard at'));
$b['bemoan'] = array('bemoaned the declining standards of modern secondary and tertiary education to', t('bemoan the declining standards of modern secondary and tertiary education to'), t('bemoans the declining standards of modern secondary and tertiary education to'));
@ -35,4 +34,4 @@ function morepokes_poke_verbs($a,&$b) {
$b['giggleandfawn'] = array('giggled and fawned at', t('giggle and fawn at'), t('giggled and fawned at'));
$b['doubt'] = array('doubted', t('doubt'), t('doubted'));
$b['glare'] = array('glared at', t('glare'), t('glared at'));
;}
;}

BIN
nsfw.tgz

Binary file not shown.

View file

@ -24,6 +24,37 @@ function nsfw_uninstall() {
}
// This function isn't perfect and isn't trying to preserve the html structure - it's just a
// quick and dirty filter to pull out embedded photo blobs because 'nsfw' seems to come up
// inside them quite often. We don't need anything fancy, just pull out the data blob so we can
// check against the rest of the body.
function nsfw_extract_photos($body) {
$new_body = '';
$img_start = strpos($body,'src="data:');
$img_end = (($img_start !== false) ? strpos(substr($body,$img_start),'>') : false);
$cnt = 0;
while($img_end !== false) {
$img_end += $img_start;
$new_body = $new_body . substr($body,0,$img_start);
$cnt ++;
$body = substr($body,0,$img_end);
$img_start = strpos($body,'src="data:');
$img_end = (($img_start !== false) ? strpos(substr($body,$img_start),'>') : false);
}
if(! $cnt)
return $body;
return $new_body;
}
@ -77,6 +108,7 @@ function nsfw_addon_settings_post(&$a,&$b) {
function nsfw_prepare_body(&$a,&$b) {
$words = null;
if(get_pconfig(local_user(),'nsfw','disable'))
return;
@ -93,19 +125,22 @@ function nsfw_prepare_body(&$a,&$b) {
$found = false;
if(count($arr)) {
$body = nsfw_extract_photos($b['html']);
foreach($arr as $word) {
$word = trim($word);
if(! strlen($word)) {
continue;
}
if(strpos($word,'/') === 0) {
if(preg_match($word,$b['html'])) {
if(preg_match($word,$body)) {
$found = true;
break;
}
}
else {
if(stristr($b['html'],$word)) {
if(stristr($body,$word)) {
$found = true;
break;
}
@ -115,6 +150,7 @@ function nsfw_prepare_body(&$a,&$b) {
}
}
}
}
if($found) {
$rnd = random_string(8);

Binary file not shown.

View file

@ -58,7 +58,7 @@ function openstreetmap_location($a, &$item) {
function openstreetmap_plugin_admin (&$a, &$o) {
$t = file_get_contents( dirname(__file__)."/admin.tpl");
$t = get_markup_template( "admin.tpl", "addon/openstreetmap/" );
$tmsserver = get_config('openstreetmap','tmsserver');
if(! $tmsserver)
$tmsserver = 'http://openstreetmap.org';

View file

@ -0,0 +1,3 @@
{{include file="field_input.tpl" field=$tmsserver}}
{{include file="field_input.tpl" field=$zoom}}
<div class="submit"><input type="submit" name="page_site" value="{{$submit}}" /></div>

BIN
page.tgz

Binary file not shown.

View file

@ -1,7 +1,7 @@
<?php
/**
* Name: Page
* Description: Shows list of subscribed community pages/forums on network sidebar
* Description: This addon is now deprecated. Administrators should switch to forumlist instead. Developers should also add any functionality to forumlist instead of here.
* Version: 1.0
* Author: Mike Macgirvin <mike@macgirvin.com>
* based on pages plugin by
@ -38,6 +38,7 @@ function page_getpage($uid,$showhidden = true,$randomise = false) {
$contacts = q("SELECT `id`, `url`, `name`, `micro` FROM `contact`
WHERE `network`= 'dfrn' AND `forum` = 1 AND `uid` = %d
and blocked = 0 and hidden = 0 and pending = 0 and archive = 0
$order ",
intval($uid)
);

BIN
piwik.tgz

Binary file not shown.

View file

@ -65,9 +65,9 @@ function piwik_analytics($a,&$b) {
*/
if ($async) {
$a->page['htmlhead'] .= "<!-- Piwik --> <script type=\"text/javascript\">\r\nvar _paq = _paq || [];\r\n(function(){ var u=((\"https:\" == document.location.protocol) ? \"https://".$baseurl."\" : \"http://".$baseurl."\");\r\n_paq.push(['setSiteId', ".$siteid."]);\r\n_paq.push(['setTrackerUrl', u+'piwik.php']);\r\n_paq.push(['trackPageView']);\r\n_paq.push(['enableLinkTracking']);\r\nvar d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript';\r\ng.defer=true; g.async=true; g.src=u+'piwik.js';\r\ns.parentNode.insertBefore(g,s); })();\r\n </script>\r\n<!-- End Piwik Code -->\r\n";
$b .= "<div id='piwik-code-block'> <!-- Piwik -->\r\n<noscript><p><img src=\"http://".$baseurl."piwik.php?idsite=".$siteid."\" style=\"border:0\" alt=\"\" /></p></noscript>\r\n <!-- End Piwik Tracking Tag --> </div>";
$b .= "<div id='piwik-code-block'> <!-- Piwik -->\r\n<noscript><p><img src=\"//".$baseurl."piwik.php?idsite=".$siteid."\" style=\"border:0\" alt=\"\" /></p></noscript>\r\n <!-- End Piwik Tracking Tag --> </div>";
} else {
$b .= "<div id='piwik-code-block'> <!-- Piwik -->\r\n <script type=\"text/javascript\">\r\n var pkBaseURL = ((\"https:\" == document.location.protocol) ? \"https://".$baseurl."\" : \"http://".$baseurl."\");\r\n document.write(unescape(\"%3Cscript src='\" + pkBaseURL + \"piwik.js' type='text/javascript'%3E%3C/script%3E\"));\r\n </script>\r\n<script type=\"text/javascript\">\r\n try {\r\n var piwikTracker = Piwik.getTracker(pkBaseURL + \"piwik.php\", ".$siteid.");\r\n piwikTracker.trackPageView();\r\n piwikTracker.enableLinkTracking();\r\n }\r\n catch( err ) {}\r\n </script>\r\n<noscript><p><img src=\"http://".$baseurl."piwik.php?idsite=".$siteid."\" style=\"border:0\" alt=\"\" /></p></noscript>\r\n <!-- End Piwik Tracking Tag --> </div>";
$b .= "<div id='piwik-code-block'> <!-- Piwik -->\r\n <script type=\"text/javascript\">\r\n var pkBaseURL = ((\"https:\" == document.location.protocol) ? \"https://".$baseurl."\" : \"http://".$baseurl."\");\r\n document.write(unescape(\"%3Cscript src='\" + pkBaseURL + \"piwik.js' type='text/javascript'%3E%3C/script%3E\"));\r\n </script>\r\n<script type=\"text/javascript\">\r\n try {\r\n var piwikTracker = Piwik.getTracker(pkBaseURL + \"piwik.php\", ".$siteid.");\r\n piwikTracker.trackPageView();\r\n piwikTracker.enableLinkTracking();\r\n }\r\n catch( err ) {}\r\n </script>\r\n<noscript><p><img src=\"//".$baseurl."piwik.php?idsite=".$siteid."\" style=\"border:0\" alt=\"\" /></p></noscript>\r\n <!-- End Piwik Tracking Tag --> </div>";
}
/*
@ -84,7 +84,7 @@ function piwik_analytics($a,&$b) {
}
}
function piwik_plugin_admin (&$a, &$o) {
$t = file_get_contents( dirname(__file__)."/admin.tpl");
$t = get_markup_template( "admin.tpl", "addon/piwik/" );
$o = replace_macros( $t, array(
'$submit' => t('Submit'),
'$baseurl' => array('baseurl', t('Piwik Base URL'), get_config('piwik','baseurl' ), t('Absolute path to your Piwik installation. (without protocol (http/s), with trailing slash)')),

0
piwik/admin.tpl → piwik/view/admin.tpl Executable file → Normal file
View file

View file

@ -0,0 +1,5 @@
{{include file="field_input.tpl" field=$baseurl}}
{{include file="field_input.tpl" field=$siteid}}
{{include file="field_checkbox.tpl" field=$optout}}
{{include file="field_checkbox.tpl" field=$async}}
<div class="submit"><input type="submit" name="page_site" value="{{$submit}}" /></div>

Binary file not shown.

View file

@ -30,42 +30,76 @@ function privacy_image_cache_uninstall() {
function privacy_image_cache_module() {}
function privacy_image_cache_init() {
global $a;
global $a, $_SERVER;
if ($a->config["system"]["db_log"] != "")
$stamp1 = microtime(true);
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
header('HTTP/1.1 304 Not Modified');
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
header('Etag: '.$_SERVER['HTTP_IF_NONE_MATCH']);
header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
header("Cache-Control: max-age=31536000");
if(function_exists('header_remove')) {
header_remove('Last-Modified');
header_remove('Expires');
header_remove('Cache-Control');
}
exit;
}
//if ($a->config["system"]["db_log"] != "")
// $stamp1 = microtime(true);
if(function_exists('header_remove')) {
header_remove('Pragma');
header_remove('pragma');
}
$thumb = false;
// Look for filename in the arguments
if (isset($a->argv[1]) OR isset($a->argv[2])) {
if (isset($a->argv[2]))
$url = $a->argv[2];
else
$url = $a->argv[1];
$pos = strrpos($url, "==.");
if ($pos)
$url = substr($url, 0, $pos+2);
$url = base64_decode(strtr($url, '-_', '+/'), true);
if ($url)
$_REQUEST['url'] = $url;
$thumb = (isset($a->argv[3]) and ($a->argv[3] == "thumb"));
}
$urlhash = 'pic:' . sha1($_REQUEST['url']);
// Double encoded url - happens with Diaspora
$urlhash2 = 'pic:' . sha1(urldecode($_REQUEST['url']));
$cache = get_config('system','itemcache');
if (($cache != '') and is_dir($cache)) {
$cachefile = $cache."/".hash("md5", $_REQUEST['url']);
$cachefile = get_cachefile(hash("md5", $_REQUEST['url']));
if ($cachefile != '') {
if (file_exists($cachefile)) {
$img_str = file_get_contents($cachefile);
$mime = image_type_to_mime_type(exif_imagetype($cachefile));
header("Content-type: $mime");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + (3600*24)) . " GMT");
header("Cache-Control: max-age=" . (3600*24));
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
header('Etag: "'.md5($img_str).'"');
header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
header("Cache-Control: max-age=31536000");
echo $img_str;
if ($a->config["system"]["db_log"] != "") {
$stamp2 = microtime(true);
$duration = round($stamp2-$stamp1, 3);
if ($duration > $a->config["system"]["db_loglimit"])
@file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
}
//if ($a->config["system"]["db_log"] != "") {
// $stamp2 = microtime(true);
// $duration = round($stamp2-$stamp1, 3);
// if ($duration > $a->config["system"]["db_loglimit"])
// @file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
//}
killme();
}
@ -73,27 +107,21 @@ function privacy_image_cache_init() {
require_once("Photo.php");
$valid = true;
$r = q("SELECT * FROM `photo` WHERE `resource-id` in ('%s', '%s') LIMIT 1", $urlhash, $urlhash2);
if (count($r)) {
$img_str = $r[0]['data'];
$mime = $r[0]["desc"];
if ($mime == "") $mime = "image/jpeg";
// Test
//if ($mime == "image/jpeg") {
// $img = new Photo($img_str);
// if($img->is_valid()) {
// $img->scaleImage(1000);
// $img_str = $img->imageString();
// }
//}
} else {
// It shouldn't happen but it does - spaces in URL
$_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
$img_str = fetch_url($_REQUEST['url'],true);
$tempfile = tempnam("", "cache");
$tempfile = tempnam(get_config("system","temppath"), "cache");
file_put_contents($tempfile, $img_str);
$mime = image_type_to_mime_type(exif_imagetype($tempfile));
unlink($tempfile);
@ -102,6 +130,13 @@ function privacy_image_cache_init() {
if ((substr($a->get_curl_code(), 0, 1) == "4") or (!$img_str)) {
$img_str = file_get_contents("images/blank.png");
$mime = "image/png";
$cachefile = ""; // Clear the cachefile so that the dummy isn't stored
$valid = false;
$img = new Photo($img_str);
if($img->is_valid()) {
$img->scaleImage(1);
$img_str = $img->imageString();
}
//} else if (substr($img_str, 0, 6) == "GIF89a") {
} else if ($mime != "image/jpeg") {
$image = @imagecreatefromstring($img_str);
@ -129,45 +164,83 @@ function privacy_image_cache_init() {
$img = new Photo($img_str);
if($img->is_valid()) {
$img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
//$img->scaleImage(1000); // Test
if ($thumb)
$img->scaleImage(200); // Test
$img_str = $img->imageString();
}
$mime = "image/jpeg";
}
}
// Writing in cachefile
if (isset($cachefile) && ($cachefile != '') and (exif_imagetype($cachefile) > 0))
// If there is a real existing directory then put the cache file there
// advantage: real file access is really fast
// Otherwise write in cachefile
if ($valid AND is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"))
file_put_contents($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache/".privacy_image_cache_cachename($_REQUEST['url'], true), $img_str);
elseif ($cachefile != '')
file_put_contents($cachefile, $img_str);
header("Content-type: $mime");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + (3600*24)) . " GMT");
header("Cache-Control: max-age=" . (3600*24));
// Only output the cache headers when the file is valid
if ($valid) {
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
header('Etag: "'.md5($img_str).'"');
header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT");
header("Cache-Control: max-age=31536000");
}
echo $img_str;
if ($a->config["system"]["db_log"] != "") {
$stamp2 = microtime(true);
$duration = round($stamp2-$stamp1, 3);
if ($duration > $a->config["system"]["db_loglimit"])
@file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
}
//if ($a->config["system"]["db_log"] != "") {
// $stamp2 = microtime(true);
// $duration = round($stamp2-$stamp1, 3);
// if ($duration > $a->config["system"]["db_loglimit"])
// @file_put_contents($a->config["system"]["db_log"], $duration."\t".strlen($img_str)."\t".$_REQUEST['url']."\n", FILE_APPEND);
//}
killme();
}
function privacy_image_cache_cachename($url, $writemode = false) {
global $_SERVER;
$basepath = $_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache";
$path = substr(hash("md5", $url), 0, 2);
if (is_dir($basepath) and $writemode)
if (!is_dir($basepath."/".$path)) {
mkdir($basepath."/".$path);
chmod($basepath."/".$path, 0777);
}
$path .= "/".strtr(base64_encode($url), '+/', '-_');
return($path);
}
/**
* @param $url string
* @return boolean
*/
function privacy_image_cache_is_local_image($url) {
if ($url[0] == '/') return true;
if ($url[0] == '/') return true;
if (strtolower(substr($url, 0, 5)) == "data:") return true;
// Check if the cached path would be longer than 255 characters - apache doesn't like it
if (is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache")) {
$cachedurl = get_app()->get_baseurl()."/privacy_image_cache/". privacy_image_cache_cachename($url);
if (strlen($url) > 255)
return true;
}
// links normalised - bug #431
$baseurl = normalise_link(get_app()->get_baseurl());
$baseurl = normalise_link(get_app()->get_baseurl());
$url = normalise_link($url);
return (substr($url, 0, strlen($baseurl)) == $baseurl);
return (substr($url, 0, strlen($baseurl)) == $baseurl);
}
/**
@ -179,7 +252,9 @@ function privacy_image_cache_img_cb($matches) {
if (privacy_image_cache_is_local_image($matches[2]))
return $matches[1] . $matches[2] . $matches[3];
return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
//return $matches[1] . get_app()->get_baseurl() . "/privacy_image_cache/?url=" . addslashes(rawurlencode(htmlspecialchars_decode($matches[2]))) . $matches[3];
return $matches[1].get_app()->get_baseurl()."/privacy_image_cache/". privacy_image_cache_cachename(htmlspecialchars_decode($matches[2])).$matches[3];
}
/**
@ -207,9 +282,14 @@ function privacy_image_cache_bbcode_hook(&$a, &$o) {
function privacy_image_cache_display_item_hook(&$a, &$o) {
if (isset($o["output"])) {
if (isset($o["output"]["thumb"]) && !privacy_image_cache_is_local_image($o["output"]["thumb"]))
$o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["thumb"])));
$o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["thumb"]);
//$o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["thumb"])));
if (isset($o["output"]["author-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["author-avatar"]))
$o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["author-avatar"])));
$o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["author-avatar"]);
//$o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["author-avatar"])));
if (isset($o["output"]["owner-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["owner-avatar"]))
$o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["owner-avatar"]);
//$o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["owner-avatar"])));
}
}
@ -220,7 +300,8 @@ function privacy_image_cache_display_item_hook(&$a, &$o) {
*/
function privacy_image_cache_ping_xmlize_hook(&$a, &$o) {
if ($o["photo"] != "" && !privacy_image_cache_is_local_image($o["photo"]))
$o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
$o["photo"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["photo"]);
//$o["photo"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["photo"])));
}
@ -239,6 +320,8 @@ function privacy_image_cache_cron(&$a = null, &$b = null) {
logger("Purging old Cache of the Privacy Image Cache", LOGGER_DEBUG);
q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
set_config('pi_cache', 'last_delete', $time);
clear_cache($a->get_basepath(), $a->get_basepath()."/privacy_image_cache");
}

Binary file not shown.

BIN
remote_permissions.tgz Normal file

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show more