caldav_CalendarPeriod::fromIcal()   F
last analyzed

Complexity

Conditions 38
Paths 8820

Size

Total Lines 266

Duplication

Lines 27
Ratio 10.15 %

Code Coverage

Tests 110
CRAP Score 75.0331

Importance

Changes 0
Metric Value
cc 38
nc 8820
nop 2
dl 27
loc 266
rs 0
c 0
b 0
f 0
ccs 110
cts 156
cp 0.705
crap 75.0331

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
//-------------------------------------------------------------------------
3
// OVIDENTIA http://www.ovidentia.org
4
// Ovidentia is free software; you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation; either version 2, or (at your option)
7
// any later version.
8
//
9
// This program is distributed in the hope that it will be useful, but
10
// WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
// See the GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with this program; if not, write to the Free Software
16
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
17
// USA.
18
//-------------------------------------------------------------------------
19
/**
20
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
21
 * @copyright Copyright (c) 2010 by CANTICO ({@link http://www.cantico.fr})
22
 */
23
24
/* @var $inheritedBackend Func_CalendarBackend_Ovi */
25 1
$inheritedBackend = bab_functionality::get('CalendarBackend/Ovi');
26 1
$inheritedBackend->includeCalendarPeriod();
27 1
$inheritedBackend->includeCalendarAlarm();
28
29 1
bab_functionality::get('CalendarBackend/Caldav');
30
31
32
class caldav_CalendarPeriod extends bab_CalendarPeriod
33
{
34
	protected $etag = null;
35
36
37
	/**
38
	 * Returns the etag associated to the period.
39
	 *
40
	 * @return string	Or null if no etag associated
41
	 */
42
	public function getEtag()
43
	{
44
		return $this->etag;
45
	}
46
47
	/**
48
	 * Sets the etag associated to the period.
49
	 *
50
	 * @param string	$etag
51
	 */
52
	public function setEtag($etag)
53
	{
54
		$this->etag = $etag;
55
		return $this;
56
	}
57
58
59
	/**
60
	 *
61
	 * @param string $property
62
	 * @param string $key
63
	 * @return string or null if not found
64
	 */
65
	private function getAttributeFromProperty($property, $key, $valueseparator = ':')
66
	{
67
		$list = explode(';', $property);
68
		foreach($list as $param)
69
		{
70
			$colonPos = mb_strpos($param, $valueseparator);
71
			if (false !== $colonPos)
72
			{
73
				if ($key === strtoupper(substr($param, 0, $colonPos)))
74
				{
75
					return substr($param, $colonPos + 1);
76
				}
77
			}
78
		}
79
80
		return null;
81
	}
82
83
84
	/**
85
	 * get author user id from organizer
86
	 * @see utilit/bab_CalendarPeriod#getAuthorId()
87
	 */
88
	public function getAuthorId()
89
	{
90
		$organizer = $this->getOrganizer();
91
92
		if (!$organizer || !is_array($organizer))
93
		{
94
			return null;
95
		}
96
97
		return bab_getUserIdByEmailAndName($organizer['email'], $organizer['name']);
98
	}
99
100
101
102 3
	static private function getPropertyValue($name, $value)
103
	{
104 3 View Code Duplication
		if ($name === 'DESCRIPTION') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
			// From RFC 2445 :  \\ encodes \, \N or \n encodes newline,  \; encodes ;, \, encodes ,
106
			$value = str_replace('\\', '\\\\', $value);
107
			$value = str_replace(';', '\;', $value);
108
			$value = str_replace(',', '\,', $value);
109
			$value = str_replace("\n", '\n', $value);
110
			$value = str_replace("\r", '', $value);
111
		}
112 3
		if ($name === 'DTSTART' || $name === 'DTEND' || $name === 'RDATE' || $name === 'EXDATE' || $name === 'RECURRENCE-ID;VALUE=DATE-TIME') {
113 3
		    $name .= ';TZID=' . Func_CalendarBackend_Caldav::getTimezoneName();
114 3
		}
115 3
		$icalProperty = $name . ':' . $value;
116
117
		// From RFC 2445 : Unfolding is accomplished by removing the CRLF character
118
		// and the linear white space character that immediately follows.
119
		//
120
		// When parsing a content line, folded lines MUST first be unfolded
121
		// according to the unfolding procedure described above. When generating
122
		// a content line, lines longer than 75 octets SHOULD be folded
123
		// according to the folding procedure described above.
124
125 3 View Code Duplication
		if (($length = mb_strlen($icalProperty)) > 75) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
			$property = mb_substr($icalProperty, 0, 75);
127
			$pos = 75;
128
			while ($pos < $length) {
129
				$property .= "\r\n " . mb_substr($icalProperty, $pos, 75);
130
				$pos += 75;
131
			}
132
			$icalProperty = $property;
133
		}
134
135 3
		return $icalProperty;
136
	}
137
138
139
	/**
140
	 * Convert to iCal string
141
	 * @param bab_CalendarPeriod $period
142
	 * @return string
143
	 */
144 3
	static public function toIcal(bab_CalendarPeriod $period)
145
	{
146 3
		$ical =  'BEGIN:VEVENT' . "\r\n";
147
148 3
		$priority1 = '';
149 3
		$priority2 = '';
150
151
		$p1 = array(
152 3
			'UID' => 1,
153 3
			'DTSTART' => 1,
154 3
			'DTEND' => 1,
155 3
			'SUMMARY' => 1,
156
			'DESCRIPTION' => 1
157 3
		);
158
159 3
		foreach ($period->getProperties() as $icalProperty) {
160
161 3
			$colonPos = mb_strpos($icalProperty, ':');
162 3
			$iCalPropertyName = substr($icalProperty, 0, $colonPos);
163 3
			$iCalPropertyValue = substr($icalProperty, $colonPos + 1);
164 3
			list($icalPropertyStart) = explode(';', $iCalPropertyName);
165
166 3
			if (trim($iCalPropertyValue) !== '') {
167
168 3
				if (isset($p1[$icalPropertyStart]))
169 3
				{
170 3
					$priority1 .= self::getPropertyValue($iCalPropertyName, $iCalPropertyValue) . "\r\n";
171 3
				} else {
172 3
					$priority2 .= self::getPropertyValue($iCalPropertyName, $iCalPropertyValue) . "\r\n";
173
				}
174 3
			}
175 3
		}
176
177 3
		$ical .= $priority1;
178 3
		$ical .= $priority2;
179
180 3
		if ($alarm = $period->getAlarm()) {
181
			$ical .= caldav_CalendarAlarm::toIcal($alarm) . "\r\n";
182
		}
183
184 3
		$ical .= 'END:VEVENT';
185
186
187 3
		$ical = bab_convertStringFromDatabase($ical, bab_charset::UTF_8);
188
189 3
		return $ical;
190
	}
191
	
192
	
193
194
195
196
197
	/**
198
	 * Initializes the caldav_CalendarPeriod from a icalendar-formatted string.
199
	 *
200
	 * @param string	$ical		The icalendar-formatted string
201
	 * @param string	$encoding	The encoding of the icalendar-formatted string (default 'UTF-8')
202
	 */
203 5
	public function fromIcal($ical, $encoding = bab_charset::UTF_8)
204
	{
205 5
		require_once $GLOBALS['babInstallPath'] . 'utilit/dateTime.php';
206
207 5
		$start = null;
208 5
		$end = null;
209 5
		$duration = null;
210
211
212
		// Converts the (by default) UTF-8 string into encoding used in ovidentia (eg. ISO-8859-15).
213 5
		$ical = bab_getStringAccordingToDataBase($ical, $encoding);
214
215
216
		// From RFC 2445 : Unfolding is accomplished by removing the CRLF character
217
		// and the linear white space character that immediately follows.
218
		//
219
		// When parsing a content line, folded lines MUST first be unfolded
220
		// according to the unfolding procedure described above. When generating
221
		// a content line, lines longer than 75 octets SHOULD be folded
222
		// according to the folding procedure described above.
223 5
		$ical = str_replace("\n ", '', $ical);
224
225
226
		// First we extract alarms.
227 5
		$alarmsData = null;
228 5
		preg_match_all('/BEGIN:VALARM(.*)END:VALARM/Us', $ical, $alarmsData);
229
230 5
		foreach ($alarmsData[1] as $alarmData) {
231
			$alarm = new caldav_CalendarAlarm();
232
			$alarm->fromIcal($alarmData);
233
			$this->setAlarm($alarm);
234
235
			// For now, ovidentia only supports one alarm by event.
236
			break;
237 5
		}
238
239 5
		$ical = preg_replace('/BEGIN:VALARM.*END:VALARM/Us', '', $ical);
240
241
242 5
		foreach (explode("\n", $ical) as $dataLine) {
243 5
			if (empty($dataLine) || strstr($dataLine, ':') === false) {
244 5
				continue;
245
			}
246
			
247
/*
248
 
249
$dataLine example :
250
251
ORGANIZER;SENT-BY="mailto:[email protected]":mailto:clio@ubu
252
 ntu.cantico.fr
253
 
254
 
255
ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;CN=Dupont Robert:MAILTO:[email protected]
256
 
257
*/		
258
			
259
			
260
			
261 5
			$m = null;
262 5
			if (preg_match('/^([^:^;]+)/', $dataLine, $m))
263 5
			{
264 5
				$icalPropertyStart = $m[1];
265 5
			}
266
			
267 5
			$dataLine = substr($dataLine, strlen($icalPropertyStart));
0 ignored issues
show
Bug introduced by
The variable $icalPropertyStart does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
268
			
269 5
			$m = null;
270 5
			if (preg_match('/^;(.+)$/', $dataLine, $m))
271 5
			{
272 5
				$parameters = explode(';', $m[1]);
273
				
274
			
275 5
				foreach($parameters as $key => $p)
276
				{
277 5
				    $mp = null;
278 5
					if (preg_match('/^[^=]+=(?:(?:[^"][^:]+)|(?:"[^"]+"))/', $p, $mp))
279 5
					{
280 5
						$parameters[$key] = $mp[0];
281 5
						$iCalPropertyValue = substr($p, (1 + strlen($mp[0])));
282
						
283 5
					}
284 5
				}
285
				
286 5
				$iCalPropertyName = $icalPropertyStart.';'.implode(';',$parameters);
287
			
288 5
			} else {
289
			
290 5
				$colonPos = mb_strpos($dataLine, ':');
291 5
				$iCalPropertyName = $icalPropertyStart;
292 5
				$iCalPropertyValue = substr($dataLine, $colonPos + 1);
293
			}
294
			
295
296
			// From RFC 2445 :  \\ encodes \, \N or \n encodes newline,  \; encodes ;, \, encodes ,
297 5
			$iCalPropertyValue = str_replace('\n', "\n", $iCalPropertyValue);
0 ignored issues
show
Bug introduced by
The variable $iCalPropertyValue does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
298 5
			$iCalPropertyValue = str_replace('\N', "\n", $iCalPropertyValue);
299 5
			$iCalPropertyValue = str_replace('\\\\', '\\', $iCalPropertyValue);
300 5
			$iCalPropertyValue = str_replace('\;', ';', $iCalPropertyValue);
301 5
			$iCalPropertyValue = str_replace('\,', ',', $iCalPropertyValue);
302
303
304
			switch ($icalPropertyStart) {
305
306 5
				case 'DESCRIPTION':
307
					//					var_dump(bab_toHtml($iCalPropertyValue, BAB_HTML_ALL));
308
					$this->setData(array('description' => bab_toHtml($iCalPropertyValue, BAB_HTML_ALL), 'description_format' => 'html'));
309
					$this->setProperty($iCalPropertyName, $iCalPropertyValue);
310
					break;
311
312 5 View Code Duplication
				case 'DTSTART':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
313 5
					list($iCalPropertyName) = explode(';', $iCalPropertyName);
314 5
					$start = BAB_DateTime::fromICal($iCalPropertyValue);
315 5
					$this->setProperty($iCalPropertyName, $iCalPropertyValue);
316 5
					break;
317
318 5 View Code Duplication
				case 'DTEND':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
319 5
					list($iCalPropertyName) = explode(';', $iCalPropertyName);
320 5
					$end = BAB_DateTime::fromICal($iCalPropertyValue);
321 5
					$this->setProperty($iCalPropertyName, $iCalPropertyValue);
322 5
					break;
323
324 5
				case 'DURATION':
325
					list($iCalPropertyName) = explode(';', $iCalPropertyName);
326
					$duration = $iCalPropertyValue;
327
					$this->setProperty($iCalPropertyName, $iCalPropertyValue);
328
					break;
329
330 5
				case 'ATTENDEE':
331 4
				    list($role, $partstat, $cn, $email) = caldav_getAttendeeProp($iCalPropertyName, $iCalPropertyValue);
332
					
333
334 4
					if ($userId = bab_getUserIdByEmailAndName($email, $cn)) {
335
						
336 4
						if (null === $userId)
337 4
						{
338
							$userId = ''; // default
339
						}
340
						
341 4
						$calendars = bab_getICalendars($userId);
342 4
						$reftype = null;
343 4
						if ($id_calendar = $calendars->getPersonalCalendarUid($userId))
344 4
						{
345 4
							$reftype = $calendars->getUserReferenceType($userId);
346 4
						}
347
						
348
						
349 4
						if (null !== $id_calendar && null !== $reftype)
350 4
						{
351
						
352 4
							$usercal = $calendars->getEventCalendar("$reftype/$id_calendar");								
353
354 4
							if (isset($usercal))
355 4
							{
356
								try {
357 4
									$this->addAttendee($usercal, $role, $partstat);
0 ignored issues
show
Documentation introduced by
$usercal is of type object<bab_EventCalendar>, but the function expects a object<bab_PersonalCalendar>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
358 4
								} catch(Exception $e) {
359
									bab_debug($e->getMessage());
360
								}
361 4
							} else {
362
								bab_debug('missing calendar '."$reftype/$id_calendar");
363
							}
364 4
						}
365
						
366 4
					} else {
367
						$this->setProperty($iCalPropertyName, $iCalPropertyValue);
368
					}
369
370 4
					break;
371
372 5
				case 'RELATED-TO':
373 2
					$parameters = explode(';', $iCalPropertyName);
374 2
					array_shift($parameters);
375
376 2
					$reltype = null;
377 2
					$status = null;
378 2
					$wfinstance = null;
379
380 2 View Code Duplication
					foreach ($parameters as $parameter) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
381 2
						list($paramName, $paramValue) = explode('=', $parameter);
382
383
						switch ($paramName) {
384 2
							case 'RELTYPE':
385 2
								$reltype = $paramValue;
386 2
								break;
387
388
							case 'X-CTO-STATUS':
389
								$status = $paramValue;
390
								break;
391
392
							case 'X-CTO-WFINSTANCE':
393
								$wfinstance = (int) $paramValue;
394
								break;
395
						}
396 2
					}
397 2
					if (!empty($reltype)) {
398 2
						require_once $GLOBALS['babInstallPath'] . 'utilit/reference.class.php';
399
						try {
400 2
							$ref = new bab_Reference($iCalPropertyValue);
401
402 2
							$referencedCalendar = bab_getICalendars()->getEventCalendar($ref->getType().'/'.$ref->getObjectId());
403 2
							if ($referencedCalendar) {
404
								$this->addRelation($reltype, $referencedCalendar, $status, $wfinstance);
405
							}
406 2
						} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
407
						}
408 2
					}
409 2
					break;
410
411
412 5
				default:
413 5
					$this->setProperty($iCalPropertyName, $iCalPropertyValue);
414 5
					break;
415
416 5
			}
417
418 5
		}
419 5
		if (!isset($end)) {
420
		    if (isset($duration) && isset($start)) {
421
				$end = $start->cloneDate();
422
				$end->add($duration, BAB_DATETIME_ICAL);
423
			} else {
424
				throw new Exception('Missing End date or duration in calendar event '.$ical);
425
			}
426
		}
427
428 5
		if (isset($start) && isset($end))
429 5
		{
430 5
			$this->setDates($start, $end);
431 5
		}
432
433
434
		// Kerio specific:
435
		// when events selected from KERIO caldav server,
436
		// the ORGANIZER of an event is removed from the list of attendees
437
		// to fix this problem, we add X-CTO-ORGANIZER-PARTSTAT to store the PARTSTAT of the ORGANIZER
438
		// only if the organizer is in the list of attendees
439
440 5
		if ($partstat = $this->getProperty('X-CTO-ORGANIZER-PARTSTAT'))
441 5
		{
442
			$id_author = $this->getAuthorId();
443
			
444
			if (empty($id_author))
445
			{
446
				bab_debug(sprintf('Author not found in ovidentia database for event %s in the ORGANIZER property', $this->getProperty('UID')));
447
				
448
			} else {
449
			
450
				$refType = bab_getICalendars()->getUserReferenceType($id_author);
451
				if ($refType)
452
				{
453
					$id_calendar = bab_getICalendars()->getPersonalCalendarUid($id_author);
454
					$calendar = bab_getICalendars()->getEventCalendar("$refType/$id_calendar");
455
	
456
					if ($calendar)
457
					{
458
						$this->addAttendee($calendar, null, $partstat);
0 ignored issues
show
Documentation introduced by
$calendar is of type object<bab_EventCalendar>, but the function expects a object<bab_PersonalCalendar>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
459
					} else {
460
						throw new Exception('Calendar not found for organizer '.$id_author);
461
					}
462
				} else {
463
					// the organizer has no accessible calendar
464
					$this->addAttendeeByUserId($id_author, 'REQ-PARTICIPANT', $partstat);
465
				}
466
			}
467
		}
468 5
	}
469
470
471
472
	/**
473
	 * define a property with a icalendar property name
474
	 * 
475
	 *
476
	 * @param	string	$icalProperty
477
	 * @param	mixed	$value
478
	 *
479
	 * @return caldav_CalendarPeriod
480
	 */
481 5
	public function setProperty($icalProperty, $value) {
482
		/*
483
		if ((substr($icalProperty, 0, strlen('ATTENDEE')) === 'ATTENDEE')
484
		 || (substr($icalProperty, 0, strlen('RELATED-TO')) === 'RELATED-TO')) {
485
			return $this;
486
		}
487
		*/
488 5
		return parent::setProperty($icalProperty, $value);
489
	}
490
491
}
492
493
494
/**
495
 *
496
 */
497
class caldav_CalendarAlarm extends bab_CalendarAlarm
498
{
499
	static public function toIcal(bab_CalendarAlarm $alarm)
500
	{
501
		$ical =  'BEGIN:VALARM' . "\r\n";
502
503
		foreach ($alarm->getProperties() as $icalProperty) {
504
			$colonPos = mb_strpos($icalProperty, ':');
505
			$iCalPropertyName = substr($icalProperty, 0, $colonPos);
506
			$iCalPropertyValue = substr($icalProperty, $colonPos + 1);
507
			list($icalPropertyStart) = explode(';', $iCalPropertyName);
508
509
			//			var_dump($icalProperty);
510
			if (trim($iCalPropertyValue) !== '') {
511 View Code Duplication
				if ($icalPropertyStart === 'DESCRIPTION') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
512
					// From RFC 2445 :  \\ encodes \, \N or \n encodes newline,  \; encodes ;, \, encodes ,
513
					$iCalPropertyValue = str_replace('\\', '\\\\', $iCalPropertyValue);
514
					$iCalPropertyValue = str_replace(';', '\;', $iCalPropertyValue);
515
					$iCalPropertyValue = str_replace(',', '\,', $iCalPropertyValue);
516
					$iCalPropertyValue = str_replace("\n", '\n', $iCalPropertyValue);
517
					$iCalPropertyValue = str_replace("\r", '', $iCalPropertyValue);
518
				}
519
520
				$icalProperty = $iCalPropertyName . ':' . $iCalPropertyValue;
521
522
				// From RFC 2445 : Unfolding is accomplished by removing the CRLF character
523
				// and the linear white space character that immediately follows.
524
				//
525
				// When parsing a content line, folded lines MUST first be unfolded
526
				// according to the unfolding procedure described above. When generating
527
				// a content line, lines longer than 75 octets SHOULD be folded
528
				// according to the folding procedure described above.
529 View Code Duplication
				if (($length = mb_strlen($icalProperty)) > 75) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
530
					$property = mb_substr($icalProperty, 0, 75);
531
					$pos = 75;
532
					while ($pos < $length) {
533
						$property .= "\n " . mb_substr($icalProperty, $pos, 75);
534
						$pos += 75;
535
					}
536
					$icalProperty = $property;
537
				}
538
				$ical .= $icalProperty . "\r\n";
539
			}
540
		}
541
542
		$ical .= 'END:VALARM';
543
544
		$ical = iconv(bab_charset::getDatabase(), bab_charset::UTF_8, $ical);
545
546
		return $ical;
547
	}
548
549
	/**
550
	 * Initializes the caldav_CalendarPeriod from a icalendar-formatted string.
551
	 *
552
	 * @param string	$ical		The icalendar-formatted string
553
	 * @param string	$encoding	The encoding of the icalendar-formatted string (default 'UTF-8')
554
	 */
555
	public function fromIcal($ical, $encoding = bab_charset::UTF_8)
0 ignored issues
show
Unused Code introduced by
The parameter $encoding is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
556
	{
557
		foreach (explode("\n", $ical) as $dataLine) {
558
			if (empty($dataLine) || strstr($dataLine, ':') === false) {
559
				continue;
560
			}
561
			//			list($iCalPropertyName, $iCalPropertyValue) = explode(':', $dataLine);//
562
			$colonPos = mb_strpos($dataLine, ':');
563
			$iCalPropertyName = substr($dataLine, 0, $colonPos);
564
			$iCalPropertyValue = substr($dataLine, $colonPos + 1);
565
			list($icalPropertyStart) = explode(';', $iCalPropertyName);
566
567
			// From RFC 2445 :  \\ encodes \, \N or \n encodes newline,  \; encodes ;, \, encodes ,
568
			$iCalPropertyValue = str_replace('\n', "\n", $iCalPropertyValue);
569
			$iCalPropertyValue = str_replace('\N', "\n", $iCalPropertyValue);
570
			$iCalPropertyValue = str_replace('\\\\', '\\', $iCalPropertyValue);
571
			$iCalPropertyValue = str_replace('\;', ';', $iCalPropertyValue);
572
			$iCalPropertyValue = str_replace('\,', ',', $iCalPropertyValue);
573
574
575
			//			$iCalPropertyValue = iconv(bab_charset::UTF_8, bab_charset::getDatabase(), $iCalPropertyValue);
576
577
578
579
			switch ($icalPropertyStart) {
580
581
				case 'DESCRIPTION':
582
					//					var_dump(bab_toHtml($iCalPropertyValue, BAB_HTML_ALL));
583
//					$this->setData(array('description' => bab_toHtml($iCalPropertyValue, BAB_HTML_ALL), 'description_format' => 'html'));
584
					$this->setProperty($iCalPropertyName, $iCalPropertyValue);
585
					break;
586
587
				case 'ATTENDEE':
588
				    list($role, $partstat, $cn, $email) = caldav_getAttendeeProp($iCalPropertyName, $iCalPropertyValue);
589
					
590
					if ($userId = bab_getUserIdByEmailAndName($email, $cn)) {
591
						$calendars = bab_getICalendars()->getCalendars();
592
						foreach ($calendars as $cal) {
593
							if ($cal->getIdUser() == $userId) {
594
								try {
595
									$this->addAttendee($cal, $role, $partstat);
596
								} catch(Exception $e) {
597
									//								echo $e;
598
								}
599
								break;
600
							}
601
						}
602
					} else {
603
						$this->setProperty($iCalPropertyName, $iCalPropertyValue);
604
					}
605
					
606
					break;
607
608
				default:
609
					$this->setProperty($iCalPropertyName, $iCalPropertyValue);
610
					break;
611
612
			}
613
614
		}
615
616
	}
617
}