Completed
Push — 14.2 ( 8c75f3...7aeda4 )
by Ralf
108:06 queued 84:21
created
phpgwapi/inc/class.vfs_stream_wrapper.inc.php 4 patches
Doc Comments   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -454,7 +454,7 @@  discard block
 block discarded – undo
454 454
 	 *
455 455
 	 * If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now.
456 456
 	 *
457
-	 * @return booelan TRUE if the cached data was successfully stored (or if there was no data to store), or FALSE if the data could not be stored.
457
+	 * @return boolean TRUE if the cached data was successfully stored (or if there was no data to store), or FALSE if the data could not be stored.
458 458
 	 */
459 459
 	function stream_flush ( )
460 460
 	{
@@ -856,7 +856,7 @@  discard block
 block discarded – undo
856 856
 	 * This method is called immediately when your stream object is created for examining directory contents with opendir().
857 857
 	 *
858 858
 	 * @param string $path URL that was passed to opendir() and that this object is expected to explore.
859
-	 * @return booelan
859
+	 * @return boolean
860 860
 	 */
861 861
 	function dir_opendir ( $path, $options )
862 862
 	{
@@ -1213,7 +1213,7 @@  discard block
 block discarded – undo
1213 1213
 	 * It should reset the output generated by dir_readdir(). i.e.:
1214 1214
 	 * The next call to dir_readdir() should return the first entry in the location returned by dir_opendir().
1215 1215
 	 *
1216
-	 * @return boolean
1216
+	 * @return boolean|null
1217 1217
 	 */
1218 1218
 	function dir_rewinddir ( )
1219 1219
 	{
@@ -1227,7 +1227,7 @@  discard block
 block discarded – undo
1227 1227
 	 *
1228 1228
 	 * You should release any resources which were locked or allocated during the opening and use of the directory stream.
1229 1229
 	 *
1230
-	 * @return boolean
1230
+	 * @return boolean|null
1231 1231
 	 */
1232 1232
 	function dir_closedir ( )
1233 1233
 	{
Please login to merge, or discard this patch.
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -388,10 +388,10 @@  discard block
 block discarded – undo
388 388
  	 * Important: PHP 5.0 introduced a bug that wasn't fixed until 5.1: the return value has to be the oposite!
389 389
  	 *
390 390
  	 * if(version_compare(PHP_VERSION,'5.0','>=') && version_compare(PHP_VERSION,'5.1','<'))
391
-  	 * {
391
+ 	 * {
392 392
  	 * 		$eof = !$eof;
393 393
  	 * }
394
-  	 *
394
+ 	 *
395 395
  	 * @return boolean true if the read/write position is at the end of the stream and no more data availible, false otherwise
396 396
  	 */
397 397
 	function stream_eof ( )
@@ -1010,7 +1010,7 @@  discard block
 block discarded – undo
1010 1010
 		if (self::LOG_LEVEL > 1) error_log(__METHOD__."('$path',$flags,'$url'): ".function_backtrace(1));
1011 1011
 
1012 1012
 		while (($rel_path = egw_vfs::basename($url).($rel_path ? '/'.$rel_path : '')) &&
1013
-		       ($url = egw_vfs::dirname($url)))
1013
+			   ($url = egw_vfs::dirname($url)))
1014 1014
 		{
1015 1015
 			if (($stat = self::url_stat($url,0,false,false)))
1016 1016
 			{
Please login to merge, or discard this patch.
Spacing   +143 added lines, -144 removed lines patch added patch discarded remove patch
@@ -145,14 +145,14 @@  discard block
 block discarded – undo
145 145
 	 * @param array|boolean &$stat=null on return: stat of existing file or false for non-existing files
146 146
 	 * @return string|boolean false if the url cant be resolved, should not happen if fstab has a root entry
147 147
 	 */
148
-	static function resolve_url_symlinks($_path,$file_exists=true,$resolve_last_symlink=true,&$stat=null)
148
+	static function resolve_url_symlinks($_path, $file_exists = true, $resolve_last_symlink = true, &$stat = null)
149 149
 	{
150 150
 		$path = self::get_path($_path);
151 151
 
152
-		if (!($stat = self::url_stat($path,$resolve_last_symlink?0:STREAM_URL_STAT_LINK)) && !$file_exists)
152
+		if (!($stat = self::url_stat($path, $resolve_last_symlink ? 0 : STREAM_URL_STAT_LINK)) && !$file_exists)
153 153
 		{
154 154
 			$url = null;
155
-			$stat = self::check_symlink_components($path,0,$url);
155
+			$stat = self::check_symlink_components($path, 0, $url);
156 156
 			if (self::LOG_LEVEL > 1) $log = " (check_symlink_components('$path',0,'$url') = $stat)";
157 157
 		}
158 158
 		else
@@ -160,9 +160,9 @@  discard block
 block discarded – undo
160 160
 			$url = $stat['url'];
161 161
 		}
162 162
 		// if the url resolves to a symlink to the vfs, resolve this vfs:// url direct
163
-		if ($url && self::parse_url($url,PHP_URL_SCHEME) == self::SCHEME)
163
+		if ($url && self::parse_url($url, PHP_URL_SCHEME) == self::SCHEME)
164 164
 		{
165
-			$url = self::resolve_url(self::parse_url($url,PHP_URL_PATH));
165
+			$url = self::resolve_url(self::parse_url($url, PHP_URL_PATH));
166 166
 		}
167 167
 		if (self::LOG_LEVEL > 1) error_log(__METHOD__."($path,file_exists=$file_exists,resolve_last_symlink=$resolve_last_symlink) = '$url'$log");
168 168
 		return $url;
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
 	 * @param boolean $replace_user_pass_host =true replace $user,$pass,$host in url, default true, if false result is not cached
185 185
 	 * @return string|boolean false if the url cant be resolved, should not happen if fstab has a root entry
186 186
 	 */
187
-	static function resolve_url($_path,$do_symlink=true,$use_symlinkcache=true,$replace_user_pass_host=true)
187
+	static function resolve_url($_path, $do_symlink = true, $use_symlinkcache = true, $replace_user_pass_host = true)
188 188
 	{
189 189
 		$path = self::get_path($_path);
190 190
 
@@ -197,43 +197,43 @@  discard block
 block discarded – undo
197 197
 		// check if we can already resolve path (or a part of it) with a known symlinks
198 198
 		if ($use_symlinkcache)
199 199
 		{
200
-			$path = self::symlinkCache_resolve($path,$do_symlink);
200
+			$path = self::symlinkCache_resolve($path, $do_symlink);
201 201
 		}
202 202
 		// setting default user, passwd and domain, if it's not contained int the url
203
-		static $defaults=null;
203
+		static $defaults = null;
204 204
 		if (is_null($defaults))
205 205
 		{
206 206
 			$defaults = array(
207 207
 				'user' => $GLOBALS['egw_info']['user']['account_lid'],
208 208
 				'pass' => urlencode($GLOBALS['egw_info']['user']['passwd']),
209 209
 				'host' => $GLOBALS['egw_info']['user']['domain'],
210
-				'home' => str_replace(array('\\\\','\\'),array('','/'),$GLOBALS['egw_info']['user']['homedirectory']),
210
+				'home' => str_replace(array('\\\\', '\\'), array('', '/'), $GLOBALS['egw_info']['user']['homedirectory']),
211 211
 			);
212 212
 		}
213
-		$parts = array_merge(self::parse_url($path),$defaults);
214
-		if (!$parts['host']) $parts['host'] = 'default';	// otherwise we get an invalid url (scheme:///path/to/something)!
213
+		$parts = array_merge(self::parse_url($path), $defaults);
214
+		if (!$parts['host']) $parts['host'] = 'default'; // otherwise we get an invalid url (scheme:///path/to/something)!
215 215
 
216 216
 		if (!empty($parts['scheme']) && $parts['scheme'] != self::SCHEME)
217 217
 		{
218 218
 			if (self::LOG_LEVEL > 1) error_log(__METHOD__."('$path') = '$path' (path is already an url)");
219
-			return $path;	// path is already a non-vfs url --> nothing to do
219
+			return $path; // path is already a non-vfs url --> nothing to do
220 220
 		}
221 221
 		if (empty($parts['path'])) $parts['path'] = '/';
222 222
 
223
-		foreach(array_reverse(self::$fstab) as $mounted => $url)
223
+		foreach (array_reverse(self::$fstab) as $mounted => $url)
224 224
 		{
225
-			if ($mounted == '/' || $mounted == $parts['path'] || $mounted.'/' == substr($parts['path'],0,strlen($mounted)+1))
225
+			if ($mounted == '/' || $mounted == $parts['path'] || $mounted.'/' == substr($parts['path'], 0, strlen($mounted) + 1))
226 226
 			{
227
-				$scheme = self::parse_url($url,PHP_URL_SCHEME);
228
-				if (is_null(self::$wrappers) || !in_array($scheme,self::$wrappers))
227
+				$scheme = self::parse_url($url, PHP_URL_SCHEME);
228
+				if (is_null(self::$wrappers) || !in_array($scheme, self::$wrappers))
229 229
 				{
230 230
 					self::load_wrapper($scheme);
231 231
 				}
232
-				$url = egw_vfs::concat($url,substr($parts['path'],strlen($mounted)));
232
+				$url = egw_vfs::concat($url, substr($parts['path'], strlen($mounted)));
233 233
 
234 234
 				if ($replace_user_pass_host)
235 235
 				{
236
-					$url = str_replace(array('$user','$pass','$host','$home'),array($parts['user'],$parts['pass'],$parts['host'],$parts['home']),$url);
236
+					$url = str_replace(array('$user', '$pass', '$host', '$home'), array($parts['user'], $parts['pass'], $parts['host'], $parts['home']), $url);
237 237
 				}
238 238
 				if ($parts['query']) $url .= '?'.$parts['query'];
239 239
 				if ($parts['fragment']) $url .= '#'.$parts['fragment'];
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
 			}
247 247
 		}
248 248
 		if (self::LOG_LEVEL > 0) error_log(__METHOD__."('$path') can't resolve path!\n");
249
-		trigger_error(__METHOD__."($path) can't resolve path!\n",E_USER_WARNING);
249
+		trigger_error(__METHOD__."($path) can't resolve path!\n", E_USER_WARNING);
250 250
 		return false;
251 251
 	}
252 252
 
@@ -258,10 +258,10 @@  discard block
 block discarded – undo
258 258
 	 */
259 259
 	static function mount_url($fullurl)
260 260
 	{
261
-		foreach(array_reverse(self::$fstab) as $url)
261
+		foreach (array_reverse(self::$fstab) as $url)
262 262
 		{
263
-			list($url_no_query) = explode('?',$url);
264
-			if (substr($fullurl,0,1+strlen($url_no_query)) === $url_no_query.'/')
263
+			list($url_no_query) = explode('?', $url);
264
+			if (substr($fullurl, 0, 1 + strlen($url_no_query)) === $url_no_query.'/')
265 265
 			{
266 266
 				return $url;
267 267
 			}
@@ -288,13 +288,13 @@  discard block
 block discarded – undo
288 288
 	 * @param string $opened_path full path of the file/resource, if the open was successfull and STREAM_USE_PATH was set
289 289
 	 * @return boolean true if the ressource was opened successful, otherwise false
290 290
 	 */
291
-	function stream_open ( $path, $mode, $options, &$opened_path )
291
+	function stream_open($path, $mode, $options, &$opened_path)
292 292
 	{
293
-		unset($opened_path);	// not used but required by function signature
293
+		unset($opened_path); // not used but required by function signature
294 294
 		$this->opened_stream = null;
295 295
 
296 296
 		$stat = null;
297
-		if (!($url = self::resolve_url_symlinks($path,$mode[0]=='r',true,$stat)))
297
+		if (!($url = self::resolve_url_symlinks($path, $mode[0] == 'r', true, $stat)))
298 298
 		{
299 299
 			return false;
300 300
 		}
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
 		{
303 303
 			return false;
304 304
 		}
305
-		if (!($this->opened_stream = fopen($url,$mode,$options)))
305
+		if (!($this->opened_stream = fopen($url, $mode, $options)))
306 306
 		{
307 307
 			return false;
308 308
 		}
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
 	 *
329 329
 	 * VFS calls either "vfs_read", "vfs_added" or "vfs_modified" hook
330 330
 	 */
331
-	function stream_close ( )
331
+	function stream_close( )
332 332
 	{
333 333
 		$ret = fclose($this->opened_stream);
334 334
 		// clear PHP's stat cache, it contains wrong size of just closed file,
@@ -338,12 +338,11 @@  discard block
 block discarded – undo
338 338
 		if (isset($GLOBALS['egw']) && isset($GLOBALS['egw']->hooks))
339 339
 		{
340 340
 			$GLOBALS['egw']->hooks->process(array(
341
-				'location' => str_replace('b','',$this->opened_stream_mode) == 'r' ? 'vfs_read' :
342
-					($this->opened_stream_is_new ? 'vfs_added' : 'vfs_modified'),
341
+				'location' => str_replace('b', '', $this->opened_stream_mode) == 'r' ? 'vfs_read' : ($this->opened_stream_is_new ? 'vfs_added' : 'vfs_modified'),
343 342
 				'path' => $this->opened_stream_path,
344 343
 				'mode' => $this->opened_stream_mode,
345 344
 				'url'  => $this->opened_stream_url,
346
-			),'',true);
345
+			), '', true);
347 346
 		}
348 347
 		$this->opened_stream = $this->opened_stream_mode = $this->opened_stream_path = $this->opened_stream_url = $this->opened_stream_is_new = null;
349 348
 
@@ -361,9 +360,9 @@  discard block
 block discarded – undo
361 360
 	 * @param int $count
362 361
 	 * @return string/false up to count bytes read or false on EOF
363 362
 	 */
364
-	function stream_read ( $count )
363
+	function stream_read($count)
365 364
 	{
366
-		return fread($this->opened_stream,$count);
365
+		return fread($this->opened_stream, $count);
367 366
 	}
368 367
 
369 368
 	/**
@@ -377,9 +376,9 @@  discard block
 block discarded – undo
377 376
 	 * @param string $data
378 377
 	 * @return integer
379 378
 	 */
380
-	function stream_write ( $data )
379
+	function stream_write($data)
381 380
 	{
382
-		return fwrite($this->opened_stream,$data);
381
+		return fwrite($this->opened_stream, $data);
383 382
 	}
384 383
 
385 384
  	/**
@@ -394,7 +393,7 @@  discard block
 block discarded – undo
394 393
   	 *
395 394
  	 * @return boolean true if the read/write position is at the end of the stream and no more data availible, false otherwise
396 395
  	 */
397
-	function stream_eof ( )
396
+	function stream_eof( )
398 397
 	{
399 398
 		return feof($this->opened_stream);
400 399
 	}
@@ -404,7 +403,7 @@  discard block
 block discarded – undo
404 403
 	 *
405 404
 	 * @return integer current read/write position of the stream
406 405
 	 */
407
- 	function stream_tell ( )
406
+ 	function stream_tell( )
408 407
  	{
409 408
  		return ftell($this->opened_stream);
410 409
  	}
@@ -421,9 +420,9 @@  discard block
 block discarded – undo
421 420
  	 * 							SEEK_END - 2 - Set position to end-of-file plus offset. (To move to a position before the end-of-file, you need to pass a negative value in offset.)
422 421
  	 * @return boolean TRUE if the position was updated, FALSE otherwise.
423 422
  	 */
424
-	function stream_seek ( $offset, $whence )
423
+	function stream_seek($offset, $whence)
425 424
 	{
426
-		return !fseek($this->opened_stream,$offset,$whence);	// fseek returns 0 on success and -1 on failure
425
+		return !fseek($this->opened_stream, $offset, $whence); // fseek returns 0 on success and -1 on failure
427 426
 	}
428 427
 
429 428
 	/**
@@ -433,7 +432,7 @@  discard block
 block discarded – undo
433 432
 	 *
434 433
 	 * @return booelan TRUE if the cached data was successfully stored (or if there was no data to store), or FALSE if the data could not be stored.
435 434
 	 */
436
-	function stream_flush ( )
435
+	function stream_flush( )
437 436
 	{
438 437
 		return fflush($this->opened_stream);
439 438
 	}
@@ -452,7 +451,7 @@  discard block
 block discarded – undo
452 451
 	 *
453 452
 	 * @return array containing the same values as appropriate for the stream.
454 453
 	 */
455
-	function stream_stat ( )
454
+	function stream_stat( )
456 455
 	{
457 456
 		return fstat($this->opened_stream);
458 457
 	}
@@ -466,9 +465,9 @@  discard block
 block discarded – undo
466 465
 	 * @param string $path
467 466
 	 * @return boolean TRUE on success or FALSE on failure
468 467
 	 */
469
-	static function unlink ( $path )
468
+	static function unlink($path)
470 469
 	{
471
-		if (!($url = self::resolve_url_symlinks($path,true,false)))	// true,false file need to exist, but do not resolve last component
470
+		if (!($url = self::resolve_url_symlinks($path, true, false)))	// true,false file need to exist, but do not resolve last component
472 471
 		{
473 472
 			return false;
474 473
 		}
@@ -489,7 +488,7 @@  discard block
 block discarded – undo
489 488
 				'path' => $path[0] == '/' ? $path : self::parse_url($path, PHP_URL_PATH),
490 489
 				'url'  => $url,
491 490
 				'stat' => $stat,
492
-			),'',true);
491
+			), '', true);
493 492
 		}
494 493
 		return $ok;
495 494
 	}
@@ -506,22 +505,22 @@  discard block
 block discarded – undo
506 505
 	 * @param string $path_to
507 506
 	 * @return boolean TRUE on success or FALSE on failure
508 507
 	 */
509
-	static function rename ( $path_from, $path_to )
508
+	static function rename($path_from, $path_to)
510 509
 	{
511
-		if (!($url_from = self::resolve_url_symlinks($path_from,true,false)) ||
512
-			!($url_to = self::resolve_url_symlinks($path_to,false)))
510
+		if (!($url_from = self::resolve_url_symlinks($path_from, true, false)) ||
511
+			!($url_to = self::resolve_url_symlinks($path_to, false)))
513 512
 		{
514 513
 			return false;
515 514
 		}
516 515
 		// if file is moved from one filesystem / wrapper to an other --> copy it (rename fails cross wrappers)
517
-		if (self::parse_url($url_from,PHP_URL_SCHEME) == self::parse_url($url_to,PHP_URL_SCHEME))
516
+		if (self::parse_url($url_from, PHP_URL_SCHEME) == self::parse_url($url_to, PHP_URL_SCHEME))
518 517
 		{
519 518
 			self::symlinkCache_remove($path_from);
520
-			$ret = rename($url_from,$url_to);
519
+			$ret = rename($url_from, $url_to);
521 520
 		}
522
-		elseif (($from = fopen($url_from,'r')) && ($to = fopen($url_to,'w')))
521
+		elseif (($from = fopen($url_from, 'r')) && ($to = fopen($url_to, 'w')))
523 522
 		{
524
-			$ret = stream_copy_to_stream($from,$to) !== false;
523
+			$ret = stream_copy_to_stream($from, $to) !== false;
525 524
 			fclose($from);
526 525
 			fclose($to);
527 526
 			if ($ret) self::unlink($path_from);
@@ -543,7 +542,7 @@  discard block
 block discarded – undo
543 542
 				'to' => $path_to[0] == '/' ? $path_to : self::parse_url($path_to, PHP_URL_PATH),
544 543
 				'url_from' => $url_from,
545 544
 				'url_to' => $url_to,
546
-			),'',true);
545
+			), '', true);
547 546
 		}
548 547
 		return $ret;
549 548
 	}
@@ -559,13 +558,13 @@  discard block
 block discarded – undo
559 558
 	 * @param int $options Posible values include STREAM_REPORT_ERRORS and STREAM_MKDIR_RECURSIVE
560 559
 	 * @return boolean TRUE on success or FALSE on failure
561 560
 	 */
562
-	static function mkdir ( $path, $mode, $options )
561
+	static function mkdir($path, $mode, $options)
563 562
 	{
564
-		if (!($url = self::resolve_url_symlinks($path,false)))	// false = directory does not need to exists
563
+		if (!($url = self::resolve_url_symlinks($path, false)))	// false = directory does not need to exists
565 564
 		{
566 565
 			return false;
567 566
 		}
568
-		$ret = mkdir($url,$mode,$options);
567
+		$ret = mkdir($url, $mode, $options);
569 568
 
570 569
 		// call "vfs_mkdir" hook
571 570
 		if ($ret && isset($GLOBALS['egw']) && isset($GLOBALS['egw']->hooks))
@@ -574,7 +573,7 @@  discard block
 block discarded – undo
574 573
 				'location' => 'vfs_mkdir',
575 574
 				'path' => $path[0] == '/' ? $path : self::parse_url($path, PHP_URL_PATH),
576 575
 				'url' => $url,
577
-			),'',true);
576
+			), '', true);
578 577
 		}
579 578
 		return $ret;
580 579
 	}
@@ -589,9 +588,9 @@  discard block
 block discarded – undo
589 588
 	 * @param int $options Possible values include STREAM_REPORT_ERRORS.
590 589
 	 * @return boolean TRUE on success or FALSE on failure.
591 590
 	 */
592
-	static function rmdir ( $path, $options )
591
+	static function rmdir($path, $options)
593 592
 	{
594
-		unset($options);	// not uses but required by function signature
593
+		unset($options); // not uses but required by function signature
595 594
 		if (!($url = self::resolve_url_symlinks($path)))
596 595
 		{
597 596
 			return false;
@@ -613,7 +612,7 @@  discard block
 block discarded – undo
613 612
 				'path' => $path[0] == '/' ? $path : self::parse_url($path, PHP_URL_PATH),
614 613
 				'url' => $url,
615 614
 				'stat' => $stat,
616
-			),'',true);
615
+			), '', true);
617 616
 		}
618 617
 		return $ok;
619 618
 	}
@@ -630,60 +629,60 @@  discard block
 block discarded – undo
630 629
 	 * @param int $path_param_key =0 key in params containing the path, default 0
631 630
 	 * @return mixed return value of backend or false if function does not exist on backend
632 631
 	 */
633
-	static protected function _call_on_backend($name,$params,$fail_silent=false,$path_param_key=0)
632
+	static protected function _call_on_backend($name, $params, $fail_silent = false, $path_param_key = 0)
634 633
 	{
635 634
 		$pathes = $params[$path_param_key];
636 635
 
637 636
 		$scheme2urls = array();
638
-		foreach(is_array($pathes) ? $pathes : array($pathes) as $path)
637
+		foreach (is_array($pathes) ? $pathes : array($pathes) as $path)
639 638
 		{
640
-			if (!($url = self::resolve_url_symlinks($path,false,false)))
639
+			if (!($url = self::resolve_url_symlinks($path, false, false)))
641 640
 			{
642 641
 				return false;
643 642
 			}
644
-			$k=(string)self::parse_url($url,PHP_URL_SCHEME);
643
+			$k = (string)self::parse_url($url, PHP_URL_SCHEME);
645 644
 			if (!(is_array($scheme2urls[$k]))) $scheme2urls[$k] = array();
646 645
 			$scheme2urls[$k][$path] = $url;
647 646
 		}
648 647
 		$ret = array();
649
-		foreach($scheme2urls as $scheme => $urls)
648
+		foreach ($scheme2urls as $scheme => $urls)
650 649
 		{
651 650
 			if ($scheme)
652 651
 			{
653
-				if (!class_exists($class = self::scheme2class($scheme)) || !method_exists($class,$name))
652
+				if (!class_exists($class = self::scheme2class($scheme)) || !method_exists($class, $name))
654 653
 				{
655
-					if (!$fail_silent) trigger_error("Can't $name for scheme $scheme!\n",E_USER_WARNING);
654
+					if (!$fail_silent) trigger_error("Can't $name for scheme $scheme!\n", E_USER_WARNING);
656 655
 					return false;
657 656
 				}
658 657
 				if (!is_array($pathes))
659 658
 				{
660 659
 					$params[$path_param_key] = $url;
661 660
 
662
-					return call_user_func_array(array($class,$name),$params);
661
+					return call_user_func_array(array($class, $name), $params);
663 662
 				}
664 663
 				$params[$path_param_key] = $urls;
665
-				if (!is_array($r = call_user_func_array(array($class,$name),$params)))
664
+				if (!is_array($r = call_user_func_array(array($class, $name), $params)))
666 665
 				{
667 666
 					return $r;
668 667
 				}
669 668
 				// we need to re-translate the urls to pathes, as they can eg. contain symlinks
670
-				foreach($urls as $path => $url)
669
+				foreach ($urls as $path => $url)
671 670
 				{
672
-					if (isset($r[$url]) || isset($r[$url=self::parse_url($url,PHP_URL_PATH)]))
671
+					if (isset($r[$url]) || isset($r[$url = self::parse_url($url, PHP_URL_PATH)]))
673 672
 					{
674 673
 						$ret[$path] = $r[$url];
675 674
 					}
676 675
 				}
677 676
 			}
678 677
 			// call the filesystem specific function (dont allow to use arrays!)
679
-			elseif(!function_exists($name) || is_array($pathes))
678
+			elseif (!function_exists($name) || is_array($pathes))
680 679
 			{
681 680
 				return false;
682 681
 			}
683 682
 			else
684 683
 			{
685 684
 				$time = null;
686
-				return $name($url,$time);
685
+				return $name($url, $time);
687 686
 			}
688 687
 		}
689 688
 		return $ret;
@@ -697,9 +696,9 @@  discard block
 block discarded – undo
697 696
 	 * @param int $atime =null access time (unix timestamp), default null = current time, not implemented in the vfs!
698 697
 	 * @return boolean true on success, false otherwise
699 698
 	 */
700
-	static function touch($path,$time=null,$atime=null)
699
+	static function touch($path, $time = null, $atime = null)
701 700
 	{
702
-		return self::_call_on_backend('touch',array($path,$time,$atime));
701
+		return self::_call_on_backend('touch', array($path, $time, $atime));
703 702
 	}
704 703
 
705 704
 	/**
@@ -711,9 +710,9 @@  discard block
 block discarded – undo
711 710
 	 * @param string $mode mode string see egw_vfs::mode2int
712 711
 	 * @return boolean true on success, false otherwise
713 712
 	 */
714
-	static function chmod($path,$mode)
713
+	static function chmod($path, $mode)
715 714
 	{
716
-		return self::_call_on_backend('chmod',array($path,$mode));
715
+		return self::_call_on_backend('chmod', array($path, $mode));
717 716
 	}
718 717
 
719 718
 	/**
@@ -725,9 +724,9 @@  discard block
 block discarded – undo
725 724
 	 * @param int $owner numeric user id
726 725
 	 * @return boolean true on success, false otherwise
727 726
 	 */
728
-	static function chown($path,$owner)
727
+	static function chown($path, $owner)
729 728
 	{
730
-		return self::_call_on_backend('chown',array($path,$owner));
729
+		return self::_call_on_backend('chown', array($path, $owner));
731 730
 	}
732 731
 
733 732
 	/**
@@ -739,9 +738,9 @@  discard block
 block discarded – undo
739 738
 	 * @param int $group numeric group id
740 739
 	 * @return boolean true on success, false otherwise
741 740
 	 */
742
-	static function chgrp($path,$group)
741
+	static function chgrp($path, $group)
743 742
 	{
744
-		return self::_call_on_backend('chgrp',array($path,$group));
743
+		return self::_call_on_backend('chgrp', array($path, $group));
745 744
 	}
746 745
 
747 746
 	/**
@@ -754,7 +753,7 @@  discard block
 block discarded – undo
754 753
 	 */
755 754
 	static function readlink($path)
756 755
 	{
757
-		$ret = self::_call_on_backend('readlink',array($path),true);	// true = fail silent, if backend does not support readlink
756
+		$ret = self::_call_on_backend('readlink', array($path), true); // true = fail silent, if backend does not support readlink
758 757
 		//error_log(__METHOD__."('$path') returning ".array2string($ret).' '.function_backtrace());
759 758
 		return $ret;
760 759
 	}
@@ -768,9 +767,9 @@  discard block
 block discarded – undo
768 767
 	 * @param string $link path of the link to create
769 768
 	 * @return boolean true on success, false on error
770 769
 	 */
771
-	static function symlink($target,$link)
770
+	static function symlink($target, $link)
772 771
 	{
773
-		if (($ret = self::_call_on_backend('symlink',array($target,$link),false,1)))	// 1=path is in $link!
772
+		if (($ret = self::_call_on_backend('symlink', array($target, $link), false, 1)))	// 1=path is in $link!
774 773
 		{
775 774
 			self::symlinkCache_remove($link);
776 775
 		}
@@ -790,13 +789,13 @@  discard block
 block discarded – undo
790 789
 	 * @param boolean $recheck =false true = do a new check, false = rely on stored mime type (if existing)
791 790
 	 * @return string mime-type (self::DIR_MIME_TYPE for directories)
792 791
 	 */
793
-	static function mime_content_type($path,$recheck=false)
792
+	static function mime_content_type($path, $recheck = false)
794 793
 	{
795 794
 		if (!($url = self::resolve_url_symlinks($path)))
796 795
 		{
797 796
 			return false;
798 797
 		}
799
-		if (($scheme = self::parse_url($url,PHP_URL_SCHEME)) && !$recheck)
798
+		if (($scheme = self::parse_url($url, PHP_URL_SCHEME)) && !$recheck)
800 799
 		{
801 800
 			// check it it's an eGW stream wrapper returning mime-type via url_stat
802 801
 			// we need to first check if the constant is defined, as we get a fatal error in php5.3 otherwise
@@ -804,7 +803,7 @@  discard block
 block discarded – undo
804 803
 				defined($class.'::STAT_RETURN_MIME_TYPE') &&
805 804
 				($mime_attr = constant($class.'::STAT_RETURN_MIME_TYPE')))
806 805
 			{
807
-				$stat = call_user_func(array($class,'url_stat'),self::parse_url($url,PHP_URL_PATH),0);
806
+				$stat = call_user_func(array($class, 'url_stat'), self::parse_url($url, PHP_URL_PATH), 0);
808 807
 				if ($stat && $stat[$mime_attr])
809 808
 				{
810 809
 					$mime = $stat[$mime_attr];
@@ -823,7 +822,7 @@  discard block
 block discarded – undo
823 822
 		// using EGw's own mime magic (currently only checking the extension!)
824 823
 		if (!$mime)
825 824
 		{
826
-			$mime = mime_magic::filename2mime(self::parse_url($url,PHP_URL_PATH));
825
+			$mime = mime_magic::filename2mime(self::parse_url($url, PHP_URL_PATH));
827 826
 		}
828 827
 		//error_log(__METHOD__."($path,$recheck) mime=$mime");
829 828
 		return $mime;
@@ -835,7 +834,7 @@  discard block
 block discarded – undo
835 834
 	 * @param string $path URL that was passed to opendir() and that this object is expected to explore.
836 835
 	 * @return booelan
837 836
 	 */
838
-	function dir_opendir ( $path, $options )
837
+	function dir_opendir($path, $options)
839 838
 	{
840 839
 		$this->opened_dir = $this->extra_dirs = null;
841 840
 		$this->extra_dir_ptr = 0;
@@ -850,15 +849,15 @@  discard block
 block discarded – undo
850 849
 			if (self::LOG_LEVEL > 0) error_log(__METHOD__."( $path,$options) opendir($this->opened_dir_url) failed!");
851 850
 			return false;
852 851
 		}
853
-		$this->opened_dir_writable = egw_vfs::check_access($this->opened_dir_url,egw_vfs::WRITABLE);
852
+		$this->opened_dir_writable = egw_vfs::check_access($this->opened_dir_url, egw_vfs::WRITABLE);
854 853
 		// check our fstab if we need to add some of the mountpoints
855
-		$basepath = self::parse_url($path,PHP_URL_PATH);
856
-		foreach(array_keys(self::$fstab) as $mounted)
854
+		$basepath = self::parse_url($path, PHP_URL_PATH);
855
+		foreach (array_keys(self::$fstab) as $mounted)
857 856
 		{
858 857
 			if (((egw_vfs::dirname($mounted) == $basepath || egw_vfs::dirname($mounted).'/' == $basepath) && $mounted != '/') &&
859 858
 				// only return children readable by the user, if dir is not writable
860 859
 				(!self::HIDE_UNREADABLES || $this->opened_dir_writable ||
861
-					egw_vfs::check_access($mounted,egw_vfs::READABLE)))
860
+					egw_vfs::check_access($mounted, egw_vfs::READABLE)))
862 861
 			{
863 862
 				$this->extra_dirs[] = basename($mounted);
864 863
 			}
@@ -895,24 +894,24 @@  discard block
 block discarded – undo
895 894
 	 * @param boolean $check_symlink_components =true check if path contains symlinks in path components other then the last one
896 895
 	 * @return array
897 896
 	 */
898
-	static function url_stat ( $path, $flags, $try_create_home=false, $check_symlink_components=true, $check_symlink_depth=self::MAX_SYMLINK_DEPTH, $try_reconnect=true )
897
+	static function url_stat($path, $flags, $try_create_home = false, $check_symlink_components = true, $check_symlink_depth = self::MAX_SYMLINK_DEPTH, $try_reconnect = true)
899 898
 	{
900
-		if (!($url = self::resolve_url($path,!($flags & STREAM_URL_STAT_LINK), $check_symlink_components)))
899
+		if (!($url = self::resolve_url($path, !($flags&STREAM_URL_STAT_LINK), $check_symlink_components)))
901 900
 		{
902 901
 			if (self::LOG_LEVEL > 0) error_log(__METHOD__."('$path',$flags) can NOT resolve path!");
903 902
 			return false;
904 903
 		}
905 904
 
906 905
 		try {
907
-			if ($flags & STREAM_URL_STAT_LINK)
906
+			if ($flags&STREAM_URL_STAT_LINK)
908 907
 			{
909
-				$stat = @lstat($url);	// suppressed the stat failed warnings
908
+				$stat = @lstat($url); // suppressed the stat failed warnings
910 909
 			}
911 910
 			else
912 911
 			{
913
-				$stat = @stat($url);	// suppressed the stat failed warnings
912
+				$stat = @stat($url); // suppressed the stat failed warnings
914 913
 
915
-				if ($stat && ($stat['mode'] & self::MODE_LINK))
914
+				if ($stat && ($stat['mode']&self::MODE_LINK))
916 915
 				{
917 916
 					if (!$check_symlink_depth)
918 917
 					{
@@ -923,15 +922,15 @@  discard block
 block discarded – undo
923 922
 					{
924 923
 						if ($lpath[0] != '/')	// concat relative path
925 924
 						{
926
-							$lpath = egw_vfs::concat(self::parse_url($path,PHP_URL_PATH),'../'.$lpath);
925
+							$lpath = egw_vfs::concat(self::parse_url($path, PHP_URL_PATH), '../'.$lpath);
927 926
 						}
928 927
 						$url = egw_vfs::PREFIX.$lpath;
929 928
 						if (self::LOG_LEVEL > 1) error_log(__METHOD__."($path,$flags) symlif (substr($path,-1) == '/' && $path != '/') $path = substr($path,0,-1);	// remove trailing slash eg. added by WebDAVink found and resolved to $url");
930 929
 						// try reading the stat of the link
931
-						if (($stat = self::url_stat($lpath, STREAM_URL_STAT_QUIET, false, true, $check_symlink_depth-1)))
930
+						if (($stat = self::url_stat($lpath, STREAM_URL_STAT_QUIET, false, true, $check_symlink_depth - 1)))
932 931
 						{
933
-							if(isset($stat['url'])) $url = $stat['url'];	// if stat returns an url use that, as there might be more links ...
934
-							self::symlinkCache_add($path,$url);
932
+							if (isset($stat['url'])) $url = $stat['url']; // if stat returns an url use that, as there might be more links ...
933
+							self::symlinkCache_add($path, $url);
935 934
 						}
936 935
 					}
937 936
 				}
@@ -951,7 +950,7 @@  discard block
 block discarded – undo
951 950
 			throw $e;
952 951
 		}
953 952
 		// check if a failed url_stat was for a home dir, in that case silently create it
954
-		if (!$stat && $try_create_home && egw_vfs::dirname(self::parse_url($path,PHP_URL_PATH)) == '/home' &&
953
+		if (!$stat && $try_create_home && egw_vfs::dirname(self::parse_url($path, PHP_URL_PATH)) == '/home' &&
955 954
 			($id = $GLOBALS['egw']->accounts->name2id(basename($path))) &&
956 955
 			$GLOBALS['egw']->accounts->id2name($id) == basename($path))	// make sure path has the right case!
957 956
 		{
@@ -961,20 +960,20 @@  discard block
 block discarded – undo
961 960
 				'account_lid' => basename($path),
962 961
 				'account_name' => basename($path),
963 962
 			);
964
-			call_user_func(array('vfs_home_hooks',$hook_data['location']),$hook_data);
963
+			call_user_func(array('vfs_home_hooks', $hook_data['location']), $hook_data);
965 964
 			unset($hook_data);
966
-			$stat = self::url_stat($path,$flags,false);
965
+			$stat = self::url_stat($path, $flags, false);
967 966
 		}
968 967
 		if (!$stat && $check_symlink_components)	// check if there's a symlink somewhere inbetween the path
969 968
 		{
970
-			$stat = self::check_symlink_components($path,$flags,$url);
971
-			if ($stat && isset($stat['url'])) self::symlinkCache_add($path,$stat['url']);
969
+			$stat = self::check_symlink_components($path, $flags, $url);
970
+			if ($stat && isset($stat['url'])) self::symlinkCache_add($path, $stat['url']);
972 971
 		}
973
-		elseif(is_array($stat) && !isset($stat['url']))
972
+		elseif (is_array($stat) && !isset($stat['url']))
974 973
 		{
975 974
 			$stat['url'] = $url;
976 975
 		}
977
-		if (($stat['mode'] & 0222) && self::url_is_readonly($stat['url']))
976
+		if (($stat['mode']&0222) && self::url_is_readonly($stat['url']))
978 977
 		{
979 978
 			$stat['mode'] &= ~0222;
980 979
 		}
@@ -1000,7 +999,7 @@  discard block
 block discarded – undo
1000 999
 	 * @param string &$url=null already resolved path
1001 1000
 	 * @return array|boolean stat array or false if not found
1002 1001
 	 */
1003
-	static private function check_symlink_components($path,$flags=0,&$url=null)
1002
+	static private function check_symlink_components($path, $flags = 0, &$url = null)
1004 1003
 	{
1005 1004
 		if (is_null($url) && !($url = self::resolve_url($path)))
1006 1005
 		{
@@ -1012,7 +1011,7 @@  discard block
 block discarded – undo
1012 1011
 		while (($rel_path = egw_vfs::basename($url).($rel_path ? '/'.$rel_path : '')) &&
1013 1012
 		       ($url = egw_vfs::dirname($url)))
1014 1013
 		{
1015
-			if (($stat = self::url_stat($url,0,false,false)))
1014
+			if (($stat = self::url_stat($url, 0, false, false)))
1016 1015
 			{
1017 1016
 				if (is_link($url) && ($lpath = self::readlink($url)))
1018 1017
 				{
@@ -1020,20 +1019,20 @@  discard block
 block discarded – undo
1020 1019
 
1021 1020
 					if ($lpath[0] != '/')
1022 1021
 					{
1023
-						$lpath = egw_vfs::concat(self::parse_url($url,PHP_URL_PATH),'../'.$lpath);
1022
+						$lpath = egw_vfs::concat(self::parse_url($url, PHP_URL_PATH), '../'.$lpath);
1024 1023
 					}
1025 1024
 					//self::symlinkCache_add($path,egw_vfs::PREFIX.$lpath);
1026
-					$url = egw_vfs::PREFIX.egw_vfs::concat($lpath,$rel_path);
1025
+					$url = egw_vfs::PREFIX.egw_vfs::concat($lpath, $rel_path);
1027 1026
 					if (self::LOG_LEVEL > 1) error_log("$log --> lpath='$lpath', url='$url'");
1028
-					return self::url_stat($url,$flags);
1027
+					return self::url_stat($url, $flags);
1029 1028
 				}
1030
-				$url = egw_vfs::concat($url,$rel_path);
1029
+				$url = egw_vfs::concat($url, $rel_path);
1031 1030
 				if (self::LOG_LEVEL > 1) error_log(__METHOD__."('$path',$flags,'$url') returning null");
1032 1031
 				return null;
1033 1032
 			}
1034 1033
 		}
1035 1034
 		if (self::LOG_LEVEL > 1) error_log(__METHOD__."('$path',$flags,'$url') returning false");
1036
-		return false;	// $path does not exist
1035
+		return false; // $path does not exist
1037 1036
 	}
1038 1037
 
1039 1038
 	/**
@@ -1049,18 +1048,18 @@  discard block
 block discarded – undo
1049 1048
 	 * @param string $_path vfs path
1050 1049
 	 * @param string $target target path
1051 1050
 	 */
1052
-	static protected function symlinkCache_add($_path,$target)
1051
+	static protected function symlinkCache_add($_path, $target)
1053 1052
 	{
1054 1053
 		$path = self::get_path($_path);
1055 1054
 
1056
-		if (isset(self::$symlink_cache[$path])) return;	// nothing to do
1055
+		if (isset(self::$symlink_cache[$path])) return; // nothing to do
1057 1056
 
1058
-		if ($target[0] != '/') $target = self::parse_url($target,PHP_URL_PATH);
1057
+		if ($target[0] != '/') $target = self::parse_url($target, PHP_URL_PATH);
1059 1058
 
1060 1059
 		self::$symlink_cache[$path] = $target;
1061 1060
 
1062 1061
 		// sort longest path first
1063
-		uksort(self::$symlink_cache,create_function('$b,$a','return strlen($a)-strlen($b);'));
1062
+		uksort(self::$symlink_cache, create_function('$b,$a', 'return strlen($a)-strlen($b);'));
1064 1063
 		if (self::LOG_LEVEL > 1) error_log(__METHOD__."($path,$target) cache now ".array2string(self::$symlink_cache));
1065 1064
 	}
1066 1065
 
@@ -1086,25 +1085,25 @@  discard block
 block discarded – undo
1086 1085
 	 * @param boolean $do_symlink =true is a direct match allowed, default yes (must be false for a lstat or readlink!)
1087 1086
 	 * @return string target or path, if path not found
1088 1087
 	 */
1089
-	static public function symlinkCache_resolve($_path,$do_symlink=true)
1088
+	static public function symlinkCache_resolve($_path, $do_symlink = true)
1090 1089
 	{
1091 1090
 		// remove vfs scheme, but no other schemes (eg. filesystem!)
1092 1091
 		$path = self::get_path($_path);
1093 1092
 
1094 1093
 		$strlen_path = strlen($path);
1095 1094
 
1096
-		foreach(self::$symlink_cache as $p => $t)
1095
+		foreach (self::$symlink_cache as $p => $t)
1097 1096
 		{
1098
-			if (($strlen_p = strlen($p)) > $strlen_path) continue;	// $path can NOT start with $p
1097
+			if (($strlen_p = strlen($p)) > $strlen_path) continue; // $path can NOT start with $p
1099 1098
 
1100 1099
 			if ($path == $p)
1101 1100
 			{
1102 1101
 				if ($do_symlink) $target = $t;
1103 1102
 				break;
1104 1103
 			}
1105
-			elseif (substr($path,0,$strlen_p+1) == $p.'/')
1104
+			elseif (substr($path, 0, $strlen_p + 1) == $p.'/')
1106 1105
 			{
1107
-				$target = $t . substr($path,$strlen_p);
1106
+				$target = $t.substr($path, $strlen_p);
1108 1107
 				break;
1109 1108
 			}
1110 1109
 		}
@@ -1122,7 +1121,7 @@  discard block
 block discarded – undo
1122 1121
 	 *
1123 1122
 	 * @param string $path ='/' path of backend, whos cache to clear
1124 1123
 	 */
1125
-	static function clearstatcache($path='/')
1124
+	static function clearstatcache($path = '/')
1126 1125
 	{
1127 1126
 		//error_log(__METHOD__."('$path')");
1128 1127
 		self::$symlink_cache = self::$resolve_url_cache = array();
@@ -1140,7 +1139,7 @@  discard block
 block discarded – undo
1140 1139
 	 *
1141 1140
 	 * @return string
1142 1141
 	 */
1143
-	function dir_readdir ( )
1142
+	function dir_readdir( )
1144 1143
 	{
1145 1144
 		if ($this->extra_dirs && count($this->extra_dirs) > $this->extra_dir_ptr)
1146 1145
 		{
@@ -1152,10 +1151,10 @@  discard block
 block discarded – undo
1152 1151
 			do {
1153 1152
 				$file = readdir($this->opened_dir);
1154 1153
 			}
1155
-			while($file !== false &&
1156
-				(is_array($this->extra_dirs) && in_array($file,$this->extra_dirs) || // do NOT return extra_dirs twice
1154
+			while ($file !== false &&
1155
+				(is_array($this->extra_dirs) && in_array($file, $this->extra_dirs) || // do NOT return extra_dirs twice
1157 1156
 				self::HIDE_UNREADABLES && !$this->opened_dir_writable &&
1158
-				!egw_vfs::check_access(egw_vfs::concat($this->opened_dir_url,$file),egw_vfs::READABLE)));
1157
+				!egw_vfs::check_access(egw_vfs::concat($this->opened_dir_url, $file), egw_vfs::READABLE)));
1159 1158
 		}
1160 1159
 		if (self::LOG_LEVEL > 1) error_log(__METHOD__."( $this->opened_dir ) = '$file'");
1161 1160
 		return $file;
@@ -1169,7 +1168,7 @@  discard block
 block discarded – undo
1169 1168
 	 *
1170 1169
 	 * @return boolean
1171 1170
 	 */
1172
-	function dir_rewinddir ( )
1171
+	function dir_rewinddir( )
1173 1172
 	{
1174 1173
 		$this->extra_dir_ptr = 0;
1175 1174
 
@@ -1183,7 +1182,7 @@  discard block
 block discarded – undo
1183 1182
 	 *
1184 1183
 	 * @return boolean
1185 1184
 	 */
1186
-	function dir_closedir ( )
1185
+	function dir_closedir( )
1187 1186
 	{
1188 1187
 		$ret = closedir($this->opened_dir);
1189 1188
 
@@ -1200,9 +1199,9 @@  discard block
 block discarded – undo
1200 1199
 	 */
1201 1200
 	static function load_wrapper($scheme)
1202 1201
 	{
1203
-		if (!in_array($scheme,self::get_wrappers()))
1202
+		if (!in_array($scheme, self::get_wrappers()))
1204 1203
 		{
1205
-			switch($scheme)
1204
+			switch ($scheme)
1206 1205
 			{
1207 1206
 				case 'webdav':
1208 1207
 				case 'webdavs':
@@ -1210,16 +1209,16 @@  discard block
 block discarded – undo
1210 1209
 					self::$wrappers[] = $scheme;
1211 1210
 					break;
1212 1211
 				case '':
1213
-					break;	// default file, always loaded
1212
+					break; // default file, always loaded
1214 1213
 				default:
1215 1214
 					// check if scheme is buildin in php or one of our own stream wrappers
1216
-					if (in_array($scheme,stream_get_wrappers()) || class_exists(self::scheme2class($scheme)))
1215
+					if (in_array($scheme, stream_get_wrappers()) || class_exists(self::scheme2class($scheme)))
1217 1216
 					{
1218 1217
 						self::$wrappers[] = $scheme;
1219 1218
 					}
1220 1219
 					else
1221 1220
 					{
1222
-						trigger_error("Can't load stream-wrapper for scheme '$scheme'!",E_USER_WARNING);
1221
+						trigger_error("Can't load stream-wrapper for scheme '$scheme'!", E_USER_WARNING);
1223 1222
 						return false;
1224 1223
 					}
1225 1224
 			}
@@ -1252,7 +1251,7 @@  discard block
 block discarded – undo
1252 1251
 	 */
1253 1252
 	static function scheme2class($scheme)
1254 1253
 	{
1255
-		return str_replace('.','_',$scheme).'_stream_wrapper';
1254
+		return str_replace('.', '_', $scheme).'_stream_wrapper';
1256 1255
 	}
1257 1256
 
1258 1257
 	/**
@@ -1264,7 +1263,7 @@  discard block
 block discarded – undo
1264 1263
 	 * @param int $component =-1 PHP_URL_* constants
1265 1264
 	 * @return array|string|boolean on success array or string, if $component given, or false on failure
1266 1265
 	 */
1267
-	static function parse_url($url, $component=-1)
1266
+	static function parse_url($url, $component = -1)
1268 1267
 	{
1269 1268
 		static $component2str = array(
1270 1269
 			PHP_URL_SCHEME => 'scheme',
@@ -1276,9 +1275,9 @@  discard block
 block discarded – undo
1276 1275
 			PHP_URL_QUERY => 'query',
1277 1276
 			PHP_URL_FRAGMENT => 'fragment',
1278 1277
 		);
1279
-		static $cache = array();	// some caching
1278
+		static $cache = array(); // some caching
1280 1279
 
1281
-		$result =& $cache[$url];
1280
+		$result = & $cache[$url];
1282 1281
 
1283 1282
 		if (!isset($result))
1284 1283
 		{
@@ -1315,7 +1314,7 @@  discard block
 block discarded – undo
1315 1314
 	 * @param string $only_remove_scheme =self::SCHEME if given only that scheme get's removed
1316 1315
 	 * @return string path without training slash
1317 1316
 	 */
1318
-	static protected function get_path($path,$only_remove_scheme=self::SCHEME)
1317
+	static protected function get_path($path, $only_remove_scheme = self::SCHEME)
1319 1318
 	{
1320 1319
 		if ($path[0] != '/' && (!$only_remove_scheme || self::parse_url($path, PHP_URL_SCHEME) == $only_remove_scheme))
1321 1320
 		{
@@ -1326,7 +1325,7 @@  discard block
 block discarded – undo
1326 1325
 		{
1327 1326
 			while (mb_substr($path, -1) == '/' && $path != '/' && ($path[0] == '/' || self::parse_url($path, PHP_URL_PATH) != '/'))
1328 1327
 			{
1329
-				$path = mb_substr($path,0,-1);
1328
+				$path = mb_substr($path, 0, -1);
1330 1329
 			}
1331 1330
 		}
1332 1331
 		return $path;
@@ -1341,7 +1340,7 @@  discard block
 block discarded – undo
1341 1340
 	static function url_is_readonly($url)
1342 1341
 	{
1343 1342
 		static $cache = array();
1344
-		$ret =& $cache[$url];
1343
+		$ret = & $cache[$url];
1345 1344
 		if (!isset($ret))
1346 1345
 		{
1347 1346
 			$matches = null;
@@ -1356,7 +1355,7 @@  discard block
 block discarded – undo
1356 1355
 	 */
1357 1356
 	static function init_static()
1358 1357
 	{
1359
-		stream_register_wrapper(self::SCHEME,__CLASS__);
1358
+		stream_register_wrapper(self::SCHEME, __CLASS__);
1360 1359
 
1361 1360
 		if (($fstab = $GLOBALS['egw_info']['server']['vfs_fstab']) && is_array($fstab) && count($fstab))
1362 1361
 		{
Please login to merge, or discard this patch.
Braces   +180 added lines, -44 removed lines patch added patch discarded remove patch
@@ -153,7 +153,10 @@  discard block
 block discarded – undo
153 153
 		{
154 154
 			$url = null;
155 155
 			$stat = self::check_symlink_components($path,0,$url);
156
-			if (self::LOG_LEVEL > 1) $log = " (check_symlink_components('$path',0,'$url') = $stat)";
156
+			if (self::LOG_LEVEL > 1)
157
+			{
158
+				$log = " (check_symlink_components('$path',0,'$url') = $stat)";
159
+			}
157 160
 		}
158 161
 		else
159 162
 		{
@@ -164,7 +167,10 @@  discard block
 block discarded – undo
164 167
 		{
165 168
 			$url = self::resolve_url(self::parse_url($url,PHP_URL_PATH));
166 169
 		}
167
-		if (self::LOG_LEVEL > 1) error_log(__METHOD__."($path,file_exists=$file_exists,resolve_last_symlink=$resolve_last_symlink) = '$url'$log");
170
+		if (self::LOG_LEVEL > 1)
171
+		{
172
+			error_log(__METHOD__."($path,file_exists=$file_exists,resolve_last_symlink=$resolve_last_symlink) = '$url'$log");
173
+		}
168 174
 		return $url;
169 175
 	}
170 176
 
@@ -191,7 +197,10 @@  discard block
 block discarded – undo
191 197
 		// we do some caching here
192 198
 		if (isset(self::$resolve_url_cache[$path]) && $replace_user_pass_host)
193 199
 		{
194
-			if (self::LOG_LEVEL > 1) error_log(__METHOD__."('$path') = '".self::$resolve_url_cache[$path]."' (from cache)");
200
+			if (self::LOG_LEVEL > 1)
201
+			{
202
+				error_log(__METHOD__."('$path') = '".self::$resolve_url_cache[$path]."' (from cache)");
203
+			}
195 204
 			return self::$resolve_url_cache[$path];
196 205
 		}
197 206
 		// check if we can already resolve path (or a part of it) with a known symlinks
@@ -211,14 +220,24 @@  discard block
 block discarded – undo
211 220
 			);
212 221
 		}
213 222
 		$parts = array_merge(self::parse_url($path),$defaults);
214
-		if (!$parts['host']) $parts['host'] = 'default';	// otherwise we get an invalid url (scheme:///path/to/something)!
223
+		if (!$parts['host'])
224
+		{
225
+			$parts['host'] = 'default';
226
+		}
227
+		// otherwise we get an invalid url (scheme:///path/to/something)!
215 228
 
216 229
 		if (!empty($parts['scheme']) && $parts['scheme'] != self::SCHEME)
217 230
 		{
218
-			if (self::LOG_LEVEL > 1) error_log(__METHOD__."('$path') = '$path' (path is already an url)");
231
+			if (self::LOG_LEVEL > 1)
232
+			{
233
+				error_log(__METHOD__."('$path') = '$path' (path is already an url)");
234
+			}
219 235
 			return $path;	// path is already a non-vfs url --> nothing to do
220 236
 		}
221
-		if (empty($parts['path'])) $parts['path'] = '/';
237
+		if (empty($parts['path']))
238
+		{
239
+			$parts['path'] = '/';
240
+		}
222 241
 
223 242
 		foreach(array_reverse(self::$fstab) as $mounted => $url)
224 243
 		{
@@ -235,17 +254,32 @@  discard block
 block discarded – undo
235 254
 				{
236 255
 					$url = str_replace(array('$user','$pass','$host','$home'),array($parts['user'],$parts['pass'],$parts['host'],$parts['home']),$url);
237 256
 				}
238
-				if ($parts['query']) $url .= '?'.$parts['query'];
239
-				if ($parts['fragment']) $url .= '#'.$parts['fragment'];
257
+				if ($parts['query'])
258
+				{
259
+					$url .= '?'.$parts['query'];
260
+				}
261
+				if ($parts['fragment'])
262
+				{
263
+					$url .= '#'.$parts['fragment'];
264
+				}
240 265
 
241
-				if (self::LOG_LEVEL > 1) error_log(__METHOD__."('$path') = '$url'");
266
+				if (self::LOG_LEVEL > 1)
267
+				{
268
+					error_log(__METHOD__."('$path') = '$url'");
269
+				}
242 270
 
243
-				if ($replace_user_pass_host) self::$resolve_url_cache[$path] = $url;
271
+				if ($replace_user_pass_host)
272
+				{
273
+					self::$resolve_url_cache[$path] = $url;
274
+				}
244 275
 
245 276
 				return $url;
246 277
 			}
247 278
 		}
248
-		if (self::LOG_LEVEL > 0) error_log(__METHOD__."('$path') can't resolve path!\n");
279
+		if (self::LOG_LEVEL > 0)
280
+		{
281
+			error_log(__METHOD__."('$path') can't resolve path!\n");
282
+		}
249 283
 		trigger_error(__METHOD__."($path) can't resolve path!\n",E_USER_WARNING);
250 284
 		return false;
251 285
 	}
@@ -468,10 +502,13 @@  discard block
 block discarded – undo
468 502
 	 */
469 503
 	static function unlink ( $path )
470 504
 	{
471
-		if (!($url = self::resolve_url_symlinks($path,true,false)))	// true,false file need to exist, but do not resolve last component
505
+		if (!($url = self::resolve_url_symlinks($path,true,false)))
506
+		{
507
+			// true,false file need to exist, but do not resolve last component
472 508
 		{
473 509
 			return false;
474 510
 		}
511
+		}
475 512
 		if (self::url_is_readonly($url))
476 513
 		{
477 514
 			return false;
@@ -524,7 +561,10 @@  discard block
 block discarded – undo
524 561
 			$ret = stream_copy_to_stream($from,$to) !== false;
525 562
 			fclose($from);
526 563
 			fclose($to);
527
-			if ($ret) self::unlink($path_from);
564
+			if ($ret)
565
+			{
566
+				self::unlink($path_from);
567
+			}
528 568
 		}
529 569
 		else
530 570
 		{
@@ -561,10 +601,13 @@  discard block
 block discarded – undo
561 601
 	 */
562 602
 	static function mkdir ( $path, $mode, $options )
563 603
 	{
564
-		if (!($url = self::resolve_url_symlinks($path,false)))	// false = directory does not need to exists
604
+		if (!($url = self::resolve_url_symlinks($path,false)))
605
+		{
606
+			// false = directory does not need to exists
565 607
 		{
566 608
 			return false;
567 609
 		}
610
+		}
568 611
 		$ret = mkdir($url,$mode,$options);
569 612
 
570 613
 		// call "vfs_mkdir" hook
@@ -642,7 +685,10 @@  discard block
 block discarded – undo
642 685
 				return false;
643 686
 			}
644 687
 			$k=(string)self::parse_url($url,PHP_URL_SCHEME);
645
-			if (!(is_array($scheme2urls[$k]))) $scheme2urls[$k] = array();
688
+			if (!(is_array($scheme2urls[$k])))
689
+			{
690
+				$scheme2urls[$k] = array();
691
+			}
646 692
 			$scheme2urls[$k][$path] = $url;
647 693
 		}
648 694
 		$ret = array();
@@ -652,7 +698,10 @@  discard block
 block discarded – undo
652 698
 			{
653 699
 				if (!class_exists($class = self::scheme2class($scheme)) || !method_exists($class,$name))
654 700
 				{
655
-					if (!$fail_silent) trigger_error("Can't $name for scheme $scheme!\n",E_USER_WARNING);
701
+					if (!$fail_silent)
702
+					{
703
+						trigger_error("Can't $name for scheme $scheme!\n",E_USER_WARNING);
704
+					}
656 705
 					return false;
657 706
 				}
658 707
 				if (!is_array($pathes))
@@ -770,10 +819,13 @@  discard block
 block discarded – undo
770 819
 	 */
771 820
 	static function symlink($target,$link)
772 821
 	{
773
-		if (($ret = self::_call_on_backend('symlink',array($target,$link),false,1)))	// 1=path is in $link!
822
+		if (($ret = self::_call_on_backend('symlink',array($target,$link),false,1)))
823
+		{
824
+			// 1=path is in $link!
774 825
 		{
775 826
 			self::symlinkCache_remove($link);
776 827
 		}
828
+		}
777 829
 		return $ret;
778 830
 	}
779 831
 
@@ -842,12 +894,18 @@  discard block
 block discarded – undo
842 894
 
843 895
 		if (!($this->opened_dir_url = self::resolve_url_symlinks($path)))
844 896
 		{
845
-			if (self::LOG_LEVEL > 0) error_log(__METHOD__."( $path,$options) resolve_url_symlinks() failed!");
897
+			if (self::LOG_LEVEL > 0)
898
+			{
899
+				error_log(__METHOD__."( $path,$options) resolve_url_symlinks() failed!");
900
+			}
846 901
 			return false;
847 902
 		}
848 903
 		if (!($this->opened_dir = opendir($this->opened_dir_url)))
849 904
 		{
850
-			if (self::LOG_LEVEL > 0) error_log(__METHOD__."( $path,$options) opendir($this->opened_dir_url) failed!");
905
+			if (self::LOG_LEVEL > 0)
906
+			{
907
+				error_log(__METHOD__."( $path,$options) opendir($this->opened_dir_url) failed!");
908
+			}
851 909
 			return false;
852 910
 		}
853 911
 		$this->opened_dir_writable = egw_vfs::check_access($this->opened_dir_url,egw_vfs::WRITABLE);
@@ -863,7 +921,10 @@  discard block
 block discarded – undo
863 921
 				$this->extra_dirs[] = basename($mounted);
864 922
 			}
865 923
 		}
866
-		if (self::LOG_LEVEL > 1) error_log(__METHOD__."( $path,$options): opendir($this->opened_dir_url)=$this->opened_dir, extra_dirs=".array2string($this->extra_dirs).', '.function_backtrace());
924
+		if (self::LOG_LEVEL > 1)
925
+		{
926
+			error_log(__METHOD__."( $path,$options): opendir($this->opened_dir_url)=$this->opened_dir, extra_dirs=".array2string($this->extra_dirs).', '.function_backtrace());
927
+		}
867 928
 		return true;
868 929
 	}
869 930
 
@@ -899,7 +960,10 @@  discard block
 block discarded – undo
899 960
 	{
900 961
 		if (!($url = self::resolve_url($path,!($flags & STREAM_URL_STAT_LINK), $check_symlink_components)))
901 962
 		{
902
-			if (self::LOG_LEVEL > 0) error_log(__METHOD__."('$path',$flags) can NOT resolve path!");
963
+			if (self::LOG_LEVEL > 0)
964
+			{
965
+				error_log(__METHOD__."('$path',$flags) can NOT resolve path!");
966
+			}
903 967
 			return false;
904 968
 		}
905 969
 
@@ -916,21 +980,34 @@  discard block
 block discarded – undo
916 980
 				{
917 981
 					if (!$check_symlink_depth)
918 982
 					{
919
-						if (self::LOG_LEVEL > 0) error_log(__METHOD__."('$path',$flags) maximum symlink depth exceeded, might be a circular symlink!");
983
+						if (self::LOG_LEVEL > 0)
984
+						{
985
+							error_log(__METHOD__."('$path',$flags) maximum symlink depth exceeded, might be a circular symlink!");
986
+						}
920 987
 						$stat = false;
921 988
 					}
922 989
 					elseif (($lpath = self::readlink($url)))
923 990
 					{
924
-						if ($lpath[0] != '/')	// concat relative path
991
+						if ($lpath[0] != '/')
992
+						{
993
+							// concat relative path
925 994
 						{
926 995
 							$lpath = egw_vfs::concat(self::parse_url($path,PHP_URL_PATH),'../'.$lpath);
927 996
 						}
997
+						}
928 998
 						$url = egw_vfs::PREFIX.$lpath;
929
-						if (self::LOG_LEVEL > 1) error_log(__METHOD__."($path,$flags) symlif (substr($path,-1) == '/' && $path != '/') $path = substr($path,0,-1);	// remove trailing slash eg. added by WebDAVink found and resolved to $url");
999
+						if (self::LOG_LEVEL > 1)
1000
+						{
1001
+							error_log(__METHOD__."($path,$flags) symlif (substr($path,-1) == '/' && $path != '/') $path = substr($path,0,-1);	// remove trailing slash eg. added by WebDAVink found and resolved to $url");
1002
+						}
930 1003
 						// try reading the stat of the link
931 1004
 						if (($stat = self::url_stat($lpath, STREAM_URL_STAT_QUIET, false, true, $check_symlink_depth-1)))
932 1005
 						{
933
-							if(isset($stat['url'])) $url = $stat['url'];	// if stat returns an url use that, as there might be more links ...
1006
+							if(isset($stat['url']))
1007
+							{
1008
+								$url = $stat['url'];
1009
+							}
1010
+							// if stat returns an url use that, as there might be more links ...
934 1011
 							self::symlinkCache_add($path,$url);
935 1012
 						}
936 1013
 					}
@@ -953,7 +1030,9 @@  discard block
 block discarded – undo
953 1030
 		// check if a failed url_stat was for a home dir, in that case silently create it
954 1031
 		if (!$stat && $try_create_home && egw_vfs::dirname(self::parse_url($path,PHP_URL_PATH)) == '/home' &&
955 1032
 			($id = $GLOBALS['egw']->accounts->name2id(basename($path))) &&
956
-			$GLOBALS['egw']->accounts->id2name($id) == basename($path))	// make sure path has the right case!
1033
+			$GLOBALS['egw']->accounts->id2name($id) == basename($path))
1034
+		{
1035
+			// make sure path has the right case!
957 1036
 		{
958 1037
 			$hook_data = array(
959 1038
 				'location' => $GLOBALS['egw']->accounts->get_type($id) == 'g' ? 'addgroup' : 'addaccount',
@@ -961,14 +1040,21 @@  discard block
 block discarded – undo
961 1040
 				'account_lid' => basename($path),
962 1041
 				'account_name' => basename($path),
963 1042
 			);
1043
+		}
964 1044
 			call_user_func(array('vfs_home_hooks',$hook_data['location']),$hook_data);
965 1045
 			unset($hook_data);
966 1046
 			$stat = self::url_stat($path,$flags,false);
967 1047
 		}
968
-		if (!$stat && $check_symlink_components)	// check if there's a symlink somewhere inbetween the path
1048
+		if (!$stat && $check_symlink_components)
1049
+		{
1050
+			// check if there's a symlink somewhere inbetween the path
969 1051
 		{
970 1052
 			$stat = self::check_symlink_components($path,$flags,$url);
971
-			if ($stat && isset($stat['url'])) self::symlinkCache_add($path,$stat['url']);
1053
+		}
1054
+			if ($stat && isset($stat['url']))
1055
+			{
1056
+				self::symlinkCache_add($path,$stat['url']);
1057
+			}
972 1058
 		}
973 1059
 		elseif(is_array($stat) && !isset($stat['url']))
974 1060
 		{
@@ -978,7 +1064,10 @@  discard block
 block discarded – undo
978 1064
 		{
979 1065
 			$stat['mode'] &= ~0222;
980 1066
 		}
981
-		if (self::LOG_LEVEL > 1) error_log(__METHOD__."('$path',$flags,try_create_home=$try_create_home,check_symlink_components=$check_symlink_components) returning ".array2string($stat));
1067
+		if (self::LOG_LEVEL > 1)
1068
+		{
1069
+			error_log(__METHOD__."('$path',$flags,try_create_home=$try_create_home,check_symlink_components=$check_symlink_components) returning ".array2string($stat));
1070
+		}
982 1071
 
983 1072
 		return $stat;
984 1073
 
@@ -1004,10 +1093,16 @@  discard block
 block discarded – undo
1004 1093
 	{
1005 1094
 		if (is_null($url) && !($url = self::resolve_url($path)))
1006 1095
 		{
1007
-			if (self::LOG_LEVEL > 0) error_log(__METHOD__."('$path',$flags,'$url') can NOT resolve path: ".function_backtrace(1));
1096
+			if (self::LOG_LEVEL > 0)
1097
+			{
1098
+				error_log(__METHOD__."('$path',$flags,'$url') can NOT resolve path: ".function_backtrace(1));
1099
+			}
1008 1100
 			return false;
1009 1101
 		}
1010
-		if (self::LOG_LEVEL > 1) error_log(__METHOD__."('$path',$flags,'$url'): ".function_backtrace(1));
1102
+		if (self::LOG_LEVEL > 1)
1103
+		{
1104
+			error_log(__METHOD__."('$path',$flags,'$url'): ".function_backtrace(1));
1105
+		}
1011 1106
 
1012 1107
 		while (($rel_path = egw_vfs::basename($url).($rel_path ? '/'.$rel_path : '')) &&
1013 1108
 		       ($url = egw_vfs::dirname($url)))
@@ -1016,7 +1111,10 @@  discard block
 block discarded – undo
1016 1111
 			{
1017 1112
 				if (is_link($url) && ($lpath = self::readlink($url)))
1018 1113
 				{
1019
-					if (self::LOG_LEVEL > 1) $log = "rel_path='$rel_path', url='$url': lpath='$lpath'";
1114
+					if (self::LOG_LEVEL > 1)
1115
+					{
1116
+						$log = "rel_path='$rel_path', url='$url': lpath='$lpath'";
1117
+					}
1020 1118
 
1021 1119
 					if ($lpath[0] != '/')
1022 1120
 					{
@@ -1024,15 +1122,24 @@  discard block
 block discarded – undo
1024 1122
 					}
1025 1123
 					//self::symlinkCache_add($path,egw_vfs::PREFIX.$lpath);
1026 1124
 					$url = egw_vfs::PREFIX.egw_vfs::concat($lpath,$rel_path);
1027
-					if (self::LOG_LEVEL > 1) error_log("$log --> lpath='$lpath', url='$url'");
1125
+					if (self::LOG_LEVEL > 1)
1126
+					{
1127
+						error_log("$log --> lpath='$lpath', url='$url'");
1128
+					}
1028 1129
 					return self::url_stat($url,$flags);
1029 1130
 				}
1030 1131
 				$url = egw_vfs::concat($url,$rel_path);
1031
-				if (self::LOG_LEVEL > 1) error_log(__METHOD__."('$path',$flags,'$url') returning null");
1132
+				if (self::LOG_LEVEL > 1)
1133
+				{
1134
+					error_log(__METHOD__."('$path',$flags,'$url') returning null");
1135
+				}
1032 1136
 				return null;
1033 1137
 			}
1034 1138
 		}
1035
-		if (self::LOG_LEVEL > 1) error_log(__METHOD__."('$path',$flags,'$url') returning false");
1139
+		if (self::LOG_LEVEL > 1)
1140
+		{
1141
+			error_log(__METHOD__."('$path',$flags,'$url') returning false");
1142
+		}
1036 1143
 		return false;	// $path does not exist
1037 1144
 	}
1038 1145
 
@@ -1053,15 +1160,25 @@  discard block
 block discarded – undo
1053 1160
 	{
1054 1161
 		$path = self::get_path($_path);
1055 1162
 
1056
-		if (isset(self::$symlink_cache[$path])) return;	// nothing to do
1163
+		if (isset(self::$symlink_cache[$path]))
1164
+		{
1165
+			return;
1166
+		}
1167
+		// nothing to do
1057 1168
 
1058
-		if ($target[0] != '/') $target = self::parse_url($target,PHP_URL_PATH);
1169
+		if ($target[0] != '/')
1170
+		{
1171
+			$target = self::parse_url($target,PHP_URL_PATH);
1172
+		}
1059 1173
 
1060 1174
 		self::$symlink_cache[$path] = $target;
1061 1175
 
1062 1176
 		// sort longest path first
1063 1177
 		uksort(self::$symlink_cache,create_function('$b,$a','return strlen($a)-strlen($b);'));
1064
-		if (self::LOG_LEVEL > 1) error_log(__METHOD__."($path,$target) cache now ".array2string(self::$symlink_cache));
1178
+		if (self::LOG_LEVEL > 1)
1179
+		{
1180
+			error_log(__METHOD__."($path,$target) cache now ".array2string(self::$symlink_cache));
1181
+		}
1065 1182
 	}
1066 1183
 
1067 1184
 	/**
@@ -1074,7 +1191,10 @@  discard block
 block discarded – undo
1074 1191
 		$path = self::get_path($_path);
1075 1192
 
1076 1193
 		unset(self::$symlink_cache[$path]);
1077
-		if (self::LOG_LEVEL > 1) error_log(__METHOD__."($path) cache now ".array2string(self::$symlink_cache));
1194
+		if (self::LOG_LEVEL > 1)
1195
+		{
1196
+			error_log(__METHOD__."($path) cache now ".array2string(self::$symlink_cache));
1197
+		}
1078 1198
 	}
1079 1199
 
1080 1200
 	/**
@@ -1095,11 +1215,18 @@  discard block
 block discarded – undo
1095 1215
 
1096 1216
 		foreach(self::$symlink_cache as $p => $t)
1097 1217
 		{
1098
-			if (($strlen_p = strlen($p)) > $strlen_path) continue;	// $path can NOT start with $p
1218
+			if (($strlen_p = strlen($p)) > $strlen_path)
1219
+			{
1220
+				continue;
1221
+			}
1222
+			// $path can NOT start with $p
1099 1223
 
1100 1224
 			if ($path == $p)
1101 1225
 			{
1102
-				if ($do_symlink) $target = $t;
1226
+				if ($do_symlink)
1227
+				{
1228
+					$target = $t;
1229
+				}
1103 1230
 				break;
1104 1231
 			}
1105 1232
 			elseif (substr($path,0,$strlen_p+1) == $p.'/')
@@ -1108,7 +1235,10 @@  discard block
 block discarded – undo
1108 1235
 				break;
1109 1236
 			}
1110 1237
 		}
1111
-		if (self::LOG_LEVEL > 1 && isset($target)) error_log(__METHOD__."($path) = $target");
1238
+		if (self::LOG_LEVEL > 1 && isset($target))
1239
+		{
1240
+			error_log(__METHOD__."($path) = $target");
1241
+		}
1112 1242
 		return isset($target) ? $target : $path;
1113 1243
 	}
1114 1244
 
@@ -1157,7 +1287,10 @@  discard block
 block discarded – undo
1157 1287
 				self::HIDE_UNREADABLES && !$this->opened_dir_writable &&
1158 1288
 				!egw_vfs::check_access(egw_vfs::concat($this->opened_dir_url,$file),egw_vfs::READABLE)));
1159 1289
 		}
1160
-		if (self::LOG_LEVEL > 1) error_log(__METHOD__."( $this->opened_dir ) = '$file'");
1290
+		if (self::LOG_LEVEL > 1)
1291
+		{
1292
+			error_log(__METHOD__."( $this->opened_dir ) = '$file'");
1293
+		}
1161 1294
 		return $file;
1162 1295
 	}
1163 1296
 
@@ -1286,7 +1419,10 @@  discard block
 block discarded – undo
1286 1419
 			static $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%24', '%2C', '%2F', '%3F', '%23', '%5B', '%5D');
1287 1420
 			static $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "$", ",", "/", "?", "#", "[", "]");
1288 1421
 			static $str_replace = null;
1289
-			if (!isset($str_replace)) $str_replace = function_exists('mb_str_replace') ? 'mb_str_replace' : 'str_replace';
1422
+			if (!isset($str_replace))
1423
+			{
1424
+				$str_replace = function_exists('mb_str_replace') ? 'mb_str_replace' : 'str_replace';
1425
+			}
1290 1426
 
1291 1427
 			// Create encoded URL with special URL characters decoded so it can be parsed
1292 1428
 			// All other characters will be encoded
Please login to merge, or discard this patch.
phpgwapi/inc/class.vfs_webdav_server.inc.php 5 patches
Doc Comments   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 	* Reimplemented to not check our vfs base path with realpath and connect to mysql DB
58 58
 	*
59 59
 	* @access public
60
-    * @param  $prefix =null prefix filesystem path with given path, eg. "/webdav" for owncloud 4.5 remote.php
60
+    * @param  string $prefix =null prefix filesystem path with given path, eg. "/webdav" for owncloud 4.5 remote.php
61 61
 	*/
62 62
 	function ServeRequest($prefix=null)
63 63
 	{
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	* DELETE method handler
77 77
 	*
78 78
 	* @param  array  general parameter passing array
79
-	* @return bool   true on success
79
+	* @return string   true on success
80 80
 	*/
81 81
 	function DELETE($options)
82 82
 	{
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
      * Reimplemented to NOT use dirname/basename, which has problems with utf-8 chars
117 117
      *
118 118
      * @param  array  general parameter passing array
119
-     * @return bool   true on success
119
+     * @return string   true on success
120 120
      */
121 121
     function MKCOL($options)
122 122
     {
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
      * COPY method handler
152 152
      *
153 153
      * @param  array  general parameter passing array
154
-     * @return bool   true on success
154
+     * @return string   true on success
155 155
      */
156 156
     function COPY($options, $del=false)
157 157
     {
@@ -477,7 +477,7 @@  discard block
 block discarded – undo
477 477
 	 * but in the regular vfs attributes.
478 478
 	 *
479 479
 	 * @param  array  general parameter passing array
480
-	 * @return bool   true on success
480
+	 * @return string   true on success
481 481
 	 */
482 482
 	function PROPPATCH(&$options)
483 483
 	{
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
 	 * LOCK method handler
558 558
 	 *
559 559
 	 * @param  array  general parameter passing array
560
-	 * @return bool   true on success
560
+	 * @return string|boolean   true on success
561 561
 	 */
562 562
 	function LOCK(&$options)
563 563
 	{
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
 	 * UNLOCK method handler
584 584
 	 *
585 585
 	 * @param  array  general parameter passing array
586
-	 * @return bool   true on success
586
+	 * @return string   true on success
587 587
 	 */
588 588
 	function UNLOCK(&$options)
589 589
 	{
@@ -640,7 +640,7 @@  discard block
 block discarded – undo
640 640
 	 * Reimplement to add a Content-Disposition header, if ?download is appended to the REQUEST_URI
641 641
 	 *
642 642
 	 * @param  array  parameter passing array
643
-	 * @return bool   true on success
643
+	 * @return boolean|null   true on success
644 644
 	 */
645 645
 	function GET(&$options)
646 646
 	{
Please login to merge, or discard this patch.
Indentation   +200 added lines, -200 removed lines patch added patch discarded remove patch
@@ -51,13 +51,13 @@  discard block
 block discarded – undo
51 51
 	var $debug = 0;
52 52
 
53 53
 	/**
54
-	* Serve a webdav request
55
-	*
56
-	* Reimplemented to not check our vfs base path with realpath and connect to mysql DB
57
-	*
58
-	* @access public
59
-    * @param  $prefix =null prefix filesystem path with given path, eg. "/webdav" for owncloud 4.5 remote.php
60
-	*/
54
+	 * Serve a webdav request
55
+	 *
56
+	 * Reimplemented to not check our vfs base path with realpath and connect to mysql DB
57
+	 *
58
+	 * @access public
59
+	 * @param  $prefix =null prefix filesystem path with given path, eg. "/webdav" for owncloud 4.5 remote.php
60
+	 */
61 61
 	function ServeRequest($prefix=null)
62 62
 	{
63 63
 		// special treatment for litmus compliance test
@@ -72,11 +72,11 @@  discard block
 block discarded – undo
72 72
 	}
73 73
 
74 74
 	/**
75
-	* DELETE method handler
76
-	*
77
-	* @param  array  general parameter passing array
78
-	* @return bool   true on success
79
-	*/
75
+	 * DELETE method handler
76
+	 *
77
+	 * @param  array  general parameter passing array
78
+	 * @return bool   true on success
79
+	 */
80 80
 	function DELETE($options)
81 81
 	{
82 82
 		$path = $this->base . $options['path'];
@@ -109,166 +109,166 @@  discard block
 block discarded – undo
109 109
 		return '204 No Content';
110 110
 	}
111 111
 
112
-    /**
113
-     * MKCOL method handler
114
-     *
115
-     * Reimplemented to NOT use dirname/basename, which has problems with utf-8 chars
116
-     *
117
-     * @param  array  general parameter passing array
118
-     * @return bool   true on success
119
-     */
120
-    function MKCOL($options)
121
-    {
122
-        $path   = $this->_unslashify($this->base .$options["path"]);
123
-        $parent = egw_vfs::dirname($path);
124
-        $name   = egw_vfs::basename($path);
125
-
126
-        if (!file_exists($parent)) {
127
-            return "409 Conflict";
128
-        }
129
-
130
-        if (!is_dir($parent)) {
131
-            return "403 Forbidden";
132
-        }
133
-
134
-        if ( file_exists($path) ) {
135
-            return "405 Method not allowed";
136
-        }
137
-
138
-        if (!empty($this->_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
139
-            return "415 Unsupported media type";
140
-        }
141
-
142
-        $stat = mkdir($path, 0777);
143
-        if (!$stat) {
144
-            return "403 Forbidden";
145
-        }
146
-
147
-        return ("201 Created");
148
-    }
112
+	/**
113
+	 * MKCOL method handler
114
+	 *
115
+	 * Reimplemented to NOT use dirname/basename, which has problems with utf-8 chars
116
+	 *
117
+	 * @param  array  general parameter passing array
118
+	 * @return bool   true on success
119
+	 */
120
+	function MKCOL($options)
121
+	{
122
+		$path   = $this->_unslashify($this->base .$options["path"]);
123
+		$parent = egw_vfs::dirname($path);
124
+		$name   = egw_vfs::basename($path);
125
+
126
+		if (!file_exists($parent)) {
127
+			return "409 Conflict";
128
+		}
129
+
130
+		if (!is_dir($parent)) {
131
+			return "403 Forbidden";
132
+		}
133
+
134
+		if ( file_exists($path) ) {
135
+			return "405 Method not allowed";
136
+		}
137
+
138
+		if (!empty($this->_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
139
+			return "415 Unsupported media type";
140
+		}
141
+
142
+		$stat = mkdir($path, 0777);
143
+		if (!$stat) {
144
+			return "403 Forbidden";
145
+		}
146
+
147
+		return ("201 Created");
148
+	}
149 149
 
150 150
 	/**
151
-     * COPY method handler
152
-     *
153
-     * @param  array  general parameter passing array
154
-     * @return bool   true on success
155
-     */
156
-    function COPY($options, $del=false)
157
-    {
158
-        // TODO Property updates still broken (Litmus should detect this?)
159
-
160
-        if (!empty($this->_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
161
-            return "415 Unsupported media type";
162
-        }
163
-
164
-        // no copying to different WebDAV Servers yet
165
-        if (isset($options["dest_url"])) {
166
-            return "502 bad gateway";
167
-        }
168
-
169
-        $source = $this->base .$options["path"];
170
-        if (!file_exists($source)) return "404 Not found";
171
-
172
-        if (is_dir($source)) { // resource is a collection
173
-            switch ($options["depth"]) {
174
-            case "infinity": // valid
175
-                break;
176
-            case "0": // valid for COPY only
177
-                if ($del) { // MOVE?
178
-                    return "400 Bad request";
179
-                }
180
-                break;
181
-            case "1": // invalid for both COPY and MOVE
182
-            default:
183
-                return "400 Bad request";
184
-            }
185
-        }
186
-
187
-        $dest         = $this->base . $options["dest"];
188
-        $destdir      = dirname($dest);
189
-
190
-        if (!file_exists($destdir) || !is_dir($destdir)) {
191
-            return "409 Conflict";
192
-        }
193
-
194
-        $new          = !file_exists($dest);
195
-        $existing_col = false;
196
-
197
-        if (!$new) {
198
-            if ($del && is_dir($dest)) {
199
-                if (!$options["overwrite"]) {
200
-                    return "412 precondition failed";
201
-                }
202
-                $dest .= basename($source);
203
-                if (file_exists($dest)) {
204
-                    $options["dest"] .= basename($source);
205
-                } else {
206
-                    $new          = true;
207
-                    $existing_col = true;
208
-                }
209
-            }
210
-        }
211
-
212
-        if (!$new) {
213
-            if ($options["overwrite"]) {
214
-                $stat = $this->DELETE(array("path" => $options["dest"]));
215
-                if (($stat{0} != "2") && (substr($stat, 0, 3) != "404")) {
216
-                    return $stat;
217
-                }
218
-            } else {
219
-                return "412 precondition failed";
220
-            }
221
-        }
222
-
223
-        if ($del) {
224
-            if (!rename($source, $dest)) {
225
-                return "500 Internal server error";
226
-            }
227
-        } else {
228
-            if (is_dir($source) && $options['depth'] == 'infinity') {
229
-            	$files = egw_vfs::find($source,array('depth' => true,'url' => true));	// depth=true: return dirs first, url=true: allow urls!
230
-            } else {
231
-                $files = array($source);
232
-            }
233
-
234
-            if (!is_array($files) || empty($files)) {
235
-                return "500 Internal server error";
236
-            }
237
-
238
-
239
-            foreach ($files as $file) {
240
-                if (is_dir($file)) {
241
-                    $file = $this->_slashify($file);
242
-                }
243
-
244
-                $destfile = str_replace($source, $dest, $file);
245
-
246
-                if (is_dir($file)) {
247
-                    if (!is_dir($destfile)) {
248
-                        // TODO "mkdir -p" here? (only natively supported by PHP 5)
249
-                        if (!@mkdir($destfile)) {
250
-                            return "409 Conflict";
251
-                        }
252
-                    }
253
-                } else {
254
-                    if (!@copy($file, $destfile)) {
255
-                        return "409 Conflict";
256
-                    }
257
-                }
258
-            }
259
-        }
260
-        // adding Location header as shown in example in rfc2518 section 8.9.5
151
+	 * COPY method handler
152
+	 *
153
+	 * @param  array  general parameter passing array
154
+	 * @return bool   true on success
155
+	 */
156
+	function COPY($options, $del=false)
157
+	{
158
+		// TODO Property updates still broken (Litmus should detect this?)
159
+
160
+		if (!empty($this->_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
161
+			return "415 Unsupported media type";
162
+		}
163
+
164
+		// no copying to different WebDAV Servers yet
165
+		if (isset($options["dest_url"])) {
166
+			return "502 bad gateway";
167
+		}
168
+
169
+		$source = $this->base .$options["path"];
170
+		if (!file_exists($source)) return "404 Not found";
171
+
172
+		if (is_dir($source)) { // resource is a collection
173
+			switch ($options["depth"]) {
174
+			case "infinity": // valid
175
+				break;
176
+			case "0": // valid for COPY only
177
+				if ($del) { // MOVE?
178
+					return "400 Bad request";
179
+				}
180
+				break;
181
+			case "1": // invalid for both COPY and MOVE
182
+			default:
183
+				return "400 Bad request";
184
+			}
185
+		}
186
+
187
+		$dest         = $this->base . $options["dest"];
188
+		$destdir      = dirname($dest);
189
+
190
+		if (!file_exists($destdir) || !is_dir($destdir)) {
191
+			return "409 Conflict";
192
+		}
193
+
194
+		$new          = !file_exists($dest);
195
+		$existing_col = false;
196
+
197
+		if (!$new) {
198
+			if ($del && is_dir($dest)) {
199
+				if (!$options["overwrite"]) {
200
+					return "412 precondition failed";
201
+				}
202
+				$dest .= basename($source);
203
+				if (file_exists($dest)) {
204
+					$options["dest"] .= basename($source);
205
+				} else {
206
+					$new          = true;
207
+					$existing_col = true;
208
+				}
209
+			}
210
+		}
211
+
212
+		if (!$new) {
213
+			if ($options["overwrite"]) {
214
+				$stat = $this->DELETE(array("path" => $options["dest"]));
215
+				if (($stat{0} != "2") && (substr($stat, 0, 3) != "404")) {
216
+					return $stat;
217
+				}
218
+			} else {
219
+				return "412 precondition failed";
220
+			}
221
+		}
222
+
223
+		if ($del) {
224
+			if (!rename($source, $dest)) {
225
+				return "500 Internal server error";
226
+			}
227
+		} else {
228
+			if (is_dir($source) && $options['depth'] == 'infinity') {
229
+				$files = egw_vfs::find($source,array('depth' => true,'url' => true));	// depth=true: return dirs first, url=true: allow urls!
230
+			} else {
231
+				$files = array($source);
232
+			}
233
+
234
+			if (!is_array($files) || empty($files)) {
235
+				return "500 Internal server error";
236
+			}
237
+
238
+
239
+			foreach ($files as $file) {
240
+				if (is_dir($file)) {
241
+					$file = $this->_slashify($file);
242
+				}
243
+
244
+				$destfile = str_replace($source, $dest, $file);
245
+
246
+				if (is_dir($file)) {
247
+					if (!is_dir($destfile)) {
248
+						// TODO "mkdir -p" here? (only natively supported by PHP 5)
249
+						if (!@mkdir($destfile)) {
250
+							return "409 Conflict";
251
+						}
252
+					}
253
+				} else {
254
+					if (!@copy($file, $destfile)) {
255
+						return "409 Conflict";
256
+					}
257
+				}
258
+			}
259
+		}
260
+		// adding Location header as shown in example in rfc2518 section 8.9.5
261 261
 		header('Location: '.$this->base_uri.$options['dest']);
262 262
 
263
-        return ($new && !$existing_col) ? "201 Created" : "204 No Content";
264
-    }
263
+		return ($new && !$existing_col) ? "201 Created" : "204 No Content";
264
+	}
265 265
 
266
-    /**
267
-	* Get properties for a single file/resource
268
-	*
269
-	* @param  string  $_path resource path
270
-	* @return array   resource properties
271
-	*/
266
+	/**
267
+	 * Get properties for a single file/resource
268
+	 *
269
+	 * @param  string  $_path resource path
270
+	 * @return array   resource properties
271
+	 */
272 272
 	function fileinfo($_path)
273 273
 	{
274 274
 		// internally we require some url-encoding, as vfs_stream_wrapper uses URL's internally
@@ -296,9 +296,9 @@  discard block
 block discarded – undo
296 296
 		$info['props'][] = HTTP_WebDAV_Server::mkprop	('creationdate',    filectime($fspath));
297 297
 		$info['props'][] = HTTP_WebDAV_Server::mkprop	('getlastmodified', filemtime($fspath));
298 298
 
299
-        // Microsoft extensions: last access time and 'hidden' status
300
-        $info["props"][] = HTTP_WebDAV_Server::mkprop("lastaccessed",    fileatime($fspath));
301
-        $info["props"][] = HTTP_WebDAV_Server::mkprop("ishidden",        egw_vfs::is_hidden($fspath));
299
+		// Microsoft extensions: last access time and 'hidden' status
300
+		$info["props"][] = HTTP_WebDAV_Server::mkprop("lastaccessed",    fileatime($fspath));
301
+		$info["props"][] = HTTP_WebDAV_Server::mkprop("ishidden",        egw_vfs::is_hidden($fspath));
302 302
 
303 303
 		// type and size (caller already made sure that path exists)
304 304
 		if (is_dir($fspath)) {
@@ -436,38 +436,38 @@  discard block
 block discarded – undo
436 436
 	}
437 437
 
438 438
  	/**
439
-	 * Used eg. by get
440
-	 *
441
-	 * @todo replace all calls to _mimetype with egw_vfs::mime_content_type()
442
-	 * @param string $path
443
-	 * @return string
444
-	 */
439
+ 	 * Used eg. by get
440
+ 	 *
441
+ 	 * @todo replace all calls to _mimetype with egw_vfs::mime_content_type()
442
+ 	 * @param string $path
443
+ 	 * @return string
444
+ 	 */
445 445
 	function _mimetype($path)
446 446
 	{
447 447
 		return egw_vfs::mime_content_type($path);
448 448
 	}
449 449
 
450
-    /**
451
-     * Check if path is readable by current user
452
-     *
453
-     * @param string $fspath
454
-     * @return boolean
455
-     */
456
-    function _is_readable($fspath)
457
-    {
458
-    	return egw_vfs::is_readable($fspath);
459
-    }
460
-
461
-    /**
462
-     * Check if path is writable by current user
463
-     *
464
-     * @param string $fspath
465
-     * @return boolean
466
-     */
467
-    function _is_writable($fspath)
468
-    {
469
-    	return egw_vfs::is_writable($fspath);
470
-    }
450
+	/**
451
+	 * Check if path is readable by current user
452
+	 *
453
+	 * @param string $fspath
454
+	 * @return boolean
455
+	 */
456
+	function _is_readable($fspath)
457
+	{
458
+		return egw_vfs::is_readable($fspath);
459
+	}
460
+
461
+	/**
462
+	 * Check if path is writable by current user
463
+	 *
464
+	 * @param string $fspath
465
+	 * @return boolean
466
+	 */
467
+	function _is_writable($fspath)
468
+	{
469
+		return egw_vfs::is_writable($fspath);
470
+	}
471 471
 
472 472
 	/**
473 473
 	 * PROPPATCH method handler
@@ -610,13 +610,13 @@  discard block
 block discarded – undo
610 610
 	 * @param  string  directory path
611 611
 	 * @return void    function has to handle HTTP response itself
612 612
 	 */
613
-    function GetDir($fspath, &$options)
614
-    {
613
+	function GetDir($fspath, &$options)
614
+	{
615 615
 		// add a content-type header to overwrite an existing default charset in apache (AddDefaultCharset directiv)
616 616
 		header('Content-type: text/html; charset='.translation::charset());
617 617
 
618 618
 		parent::GetDir($fspath, $options);
619
-    }
619
+	}
620 620
 
621 621
 	private $force_download = false;
622 622
 
Please login to merge, or discard this patch.
Switch Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -171,16 +171,16 @@
 block discarded – undo
171 171
 
172 172
         if (is_dir($source)) { // resource is a collection
173 173
             switch ($options["depth"]) {
174
-            case "infinity": // valid
175
-                break;
176
-            case "0": // valid for COPY only
177
-                if ($del) { // MOVE?
178
-                    return "400 Bad request";
179
-                }
180
-                break;
181
-            case "1": // invalid for both COPY and MOVE
182
-            default:
183
-                return "400 Bad request";
174
+            	case "infinity": // valid
175
+                	break;
176
+            	case "0": // valid for COPY only
177
+                	if ($del) { // MOVE?
178
+                    	return "400 Bad request";
179
+                	}
180
+                	break;
181
+            	case "1": // invalid for both COPY and MOVE
182
+            	default:
183
+                	return "400 Bad request";
184 184
             }
185 185
         }
186 186
 
Please login to merge, or discard this patch.
Spacing   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 	* @access public
59 59
     * @param  $prefix =null prefix filesystem path with given path, eg. "/webdav" for owncloud 4.5 remote.php
60 60
 	*/
61
-	function ServeRequest($prefix=null)
61
+	function ServeRequest($prefix = null)
62 62
 	{
63 63
 		// special treatment for litmus compliance test
64 64
 		// reply on its identifier header
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 	*/
80 80
 	function DELETE($options)
81 81
 	{
82
-		$path = $this->base . $options['path'];
82
+		$path = $this->base.$options['path'];
83 83
 
84 84
 		if (!file_exists($path))
85 85
 		{
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
      */
120 120
     function MKCOL($options)
121 121
     {
122
-        $path   = $this->_unslashify($this->base .$options["path"]);
122
+        $path   = $this->_unslashify($this->base.$options["path"]);
123 123
         $parent = egw_vfs::dirname($path);
124 124
         $name   = egw_vfs::basename($path);
125 125
 
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
             return "403 Forbidden";
132 132
         }
133 133
 
134
-        if ( file_exists($path) ) {
134
+        if (file_exists($path)) {
135 135
             return "405 Method not allowed";
136 136
         }
137 137
 
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
      * @param  array  general parameter passing array
154 154
      * @return bool   true on success
155 155
      */
156
-    function COPY($options, $del=false)
156
+    function COPY($options, $del = false)
157 157
     {
158 158
         // TODO Property updates still broken (Litmus should detect this?)
159 159
 
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
             return "502 bad gateway";
167 167
         }
168 168
 
169
-        $source = $this->base .$options["path"];
169
+        $source = $this->base.$options["path"];
170 170
         if (!file_exists($source)) return "404 Not found";
171 171
 
172 172
         if (is_dir($source)) { // resource is a collection
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
             }
185 185
         }
186 186
 
187
-        $dest         = $this->base . $options["dest"];
187
+        $dest         = $this->base.$options["dest"];
188 188
         $destdir      = dirname($dest);
189 189
 
190 190
         if (!file_exists($destdir) || !is_dir($destdir)) {
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
             }
227 227
         } else {
228 228
             if (is_dir($source) && $options['depth'] == 'infinity') {
229
-            	$files = egw_vfs::find($source,array('depth' => true,'url' => true));	// depth=true: return dirs first, url=true: allow urls!
229
+            	$files = egw_vfs::find($source, array('depth' => true, 'url' => true)); // depth=true: return dirs first, url=true: allow urls!
230 230
             } else {
231 231
                 $files = array($source);
232 232
             }
@@ -272,16 +272,16 @@  discard block
 block discarded – undo
272 272
 	function fileinfo($_path)
273 273
 	{
274 274
 		// internally we require some url-encoding, as vfs_stream_wrapper uses URL's internally
275
-		$path = str_replace(array('#','?'),array('%23','%3F'),$_path);
275
+		$path = str_replace(array('#', '?'), array('%23', '%3F'), $_path);
276 276
 
277 277
 		//error_log(__METHOD__."($path)");
278 278
 		// map URI path to filesystem path
279
-		$fspath = $this->base . $path;
279
+		$fspath = $this->base.$path;
280 280
 
281 281
 		// create result array
282 282
 		$info = array();
283 283
 		// TODO remove slash append code when base class is able to do it itself
284
-		$info['path']  = is_dir($fspath) ? $this->_slashify($path) : $path;
284
+		$info['path'] = is_dir($fspath) ? $this->_slashify($path) : $path;
285 285
 
286 286
 		// remove all urlencoding we need internally in EGw, HTTP_WebDAV_Server will add it's own!
287 287
 		// rawurldecode does NOT touch +
@@ -290,32 +290,32 @@  discard block
 block discarded – undo
290 290
 		$info['props'] = array();
291 291
 
292 292
 		// no special beautified displayname here ...
293
-		$info['props'][] = HTTP_WebDAV_Server::mkprop	('displayname', egw_vfs::basename(self::_unslashify($info['path'])));
293
+		$info['props'][] = HTTP_WebDAV_Server::mkprop('displayname', egw_vfs::basename(self::_unslashify($info['path'])));
294 294
 
295 295
 		// creation and modification time
296
-		$info['props'][] = HTTP_WebDAV_Server::mkprop	('creationdate',    filectime($fspath));
297
-		$info['props'][] = HTTP_WebDAV_Server::mkprop	('getlastmodified', filemtime($fspath));
296
+		$info['props'][] = HTTP_WebDAV_Server::mkprop('creationdate', filectime($fspath));
297
+		$info['props'][] = HTTP_WebDAV_Server::mkprop('getlastmodified', filemtime($fspath));
298 298
 
299 299
         // Microsoft extensions: last access time and 'hidden' status
300
-        $info["props"][] = HTTP_WebDAV_Server::mkprop("lastaccessed",    fileatime($fspath));
301
-        $info["props"][] = HTTP_WebDAV_Server::mkprop("ishidden",        egw_vfs::is_hidden($fspath));
300
+        $info["props"][] = HTTP_WebDAV_Server::mkprop("lastaccessed", fileatime($fspath));
301
+        $info["props"][] = HTTP_WebDAV_Server::mkprop("ishidden", egw_vfs::is_hidden($fspath));
302 302
 
303 303
 		// type and size (caller already made sure that path exists)
304 304
 		if (is_dir($fspath)) {
305 305
 			// directory (WebDAV collection)
306
-			$info['props'][] = HTTP_WebDAV_Server::mkprop	('resourcetype', array(
306
+			$info['props'][] = HTTP_WebDAV_Server::mkprop('resourcetype', array(
307 307
 			 	HTTP_WebDAV_Server::mkprop('collection', '')));
308
-			$info['props'][] = HTTP_WebDAV_Server::mkprop	('getcontenttype', 'httpd/unix-directory');
308
+			$info['props'][] = HTTP_WebDAV_Server::mkprop('getcontenttype', 'httpd/unix-directory');
309 309
 		} else {
310 310
 			// plain file (WebDAV resource)
311
-			$info['props'][] = HTTP_WebDAV_Server::mkprop	('resourcetype', '');
311
+			$info['props'][] = HTTP_WebDAV_Server::mkprop('resourcetype', '');
312 312
 			if (egw_vfs::is_readable($path)) {
313
-				$info['props'][] = HTTP_WebDAV_Server::mkprop	('getcontenttype', egw_vfs::mime_content_type($path));
313
+				$info['props'][] = HTTP_WebDAV_Server::mkprop('getcontenttype', egw_vfs::mime_content_type($path));
314 314
 			} else {
315 315
 				error_log(__METHOD__."($path) $fspath is not readable!");
316
-				$info['props'][] = HTTP_WebDAV_Server::mkprop	('getcontenttype', 'application/x-non-readable');
316
+				$info['props'][] = HTTP_WebDAV_Server::mkprop('getcontenttype', 'application/x-non-readable');
317 317
 			}
318
-			$info['props'][] = HTTP_WebDAV_Server::mkprop	('getcontentlength', filesize($fspath));
318
+			$info['props'][] = HTTP_WebDAV_Server::mkprop('getcontentlength', filesize($fspath));
319 319
 		}
320 320
 		// generate etag from inode (sqlfs: fs_id), modification time and size
321 321
 		$stat = stat($fspath);
@@ -369,21 +369,21 @@  discard block
 block discarded – undo
369 369
 	 */
370 370
 	function PROPFIND(&$options, &$files)
371 371
 	{
372
-		if (!parent::PROPFIND($options,$files))
372
+		if (!parent::PROPFIND($options, $files))
373 373
 		{
374 374
 			return false;
375 375
 		}
376 376
 		$path2n = array();
377
-		foreach($files['files'] as $n => $info)
377
+		foreach ($files['files'] as $n => $info)
378 378
 		{
379 379
 			// do NOT report /clientsync/.favorites/, as it fails
380
-			if (strpos($info['path'],'/clientsync/.favorites/') === 0)
380
+			if (strpos($info['path'], '/clientsync/.favorites/') === 0)
381 381
 			{
382 382
 				unset($files['files'][$n]);
383 383
 				continue;
384 384
 			}
385 385
 			$_path = $info['path'];
386
-			if (!$n && $info['path'] != '/' && substr($info['path'],-1) == '/') $_path = substr($info['path'],0,-1);
386
+			if (!$n && $info['path'] != '/' && substr($info['path'], -1) == '/') $_path = substr($info['path'], 0, -1);
387 387
 
388 388
 			// need to encode path again, as $info['path'] is NOT encoded, but egw_vfs::(stat|propfind) require it
389 389
 			// otherwise pathes containing url special chars like ? or # will not stat
@@ -393,21 +393,21 @@  discard block
 block discarded – undo
393 393
 			// adding some properties used instead of regular DAV times
394 394
 			if (($stat = egw_vfs::stat($path)))
395 395
 			{
396
-				$fileprops =& $files['files'][$path2n[$path]]['props'];
397
-				foreach(self::$auto_props as $attr => $props)
396
+				$fileprops = & $files['files'][$path2n[$path]]['props'];
397
+				foreach (self::$auto_props as $attr => $props)
398 398
 				{
399
-					switch($attr)
399
+					switch ($attr)
400 400
 					{
401 401
 						case 'ctime':
402 402
 						case 'mtime':
403 403
 						case 'atime':
404
-							$value = gmdate('D, d M Y H:i:s T',$stat[$attr]);
404
+							$value = gmdate('D, d M Y H:i:s T', $stat[$attr]);
405 405
 							break;
406 406
 
407 407
 						default:
408 408
 							continue 2;
409 409
 					}
410
-					foreach($props as $prop)
410
+					foreach ($props as $prop)
411 411
 					{
412 412
 						$prop['val'] = $value;
413 413
 						$fileprops[] = $prop;
@@ -415,17 +415,17 @@  discard block
 block discarded – undo
415 415
 				}
416 416
 			}
417 417
 		}
418
-		if ($path2n && ($path2props = egw_vfs::propfind(array_keys($path2n),null)))
418
+		if ($path2n && ($path2props = egw_vfs::propfind(array_keys($path2n), null)))
419 419
 		{
420
-			foreach($path2props as $path => $props)
420
+			foreach ($path2props as $path => $props)
421 421
 			{
422
-				$fileprops =& $files['files'][$path2n[$path]]['props'];
423
-				foreach($props as $prop)
422
+				$fileprops = & $files['files'][$path2n[$path]]['props'];
423
+				foreach ($props as $prop)
424 424
 				{
425 425
 					if ($prop['ns'] == egw_vfs::DEFAULT_PROP_NAMESPACE && $prop['name'][0] == '#')	// eGW's customfields
426 426
 					{
427 427
 						$prop['ns'] .= 'customfields/';
428
-						$prop['name'] = substr($prop['name'],1);
428
+						$prop['name'] = substr($prop['name'], 1);
429 429
 					}
430 430
 					$fileprops[] = $prop;
431 431
 				}
@@ -481,36 +481,36 @@  discard block
 block discarded – undo
481 481
 	 */
482 482
 	function PROPPATCH(&$options)
483 483
 	{
484
-		$path = translation::convert($options['path'],'utf-8');
484
+		$path = translation::convert($options['path'], 'utf-8');
485 485
 
486 486
 		foreach ($options['props'] as $key => $prop) {
487 487
 			$attributes = array();
488
-			switch($prop['ns'])
488
+			switch ($prop['ns'])
489 489
 			{
490 490
 				// allow Webdrive to set creation and modification time
491 491
 				case 'http://www.southrivertech.com/':
492
-					switch($prop['name'])
492
+					switch ($prop['name'])
493 493
 					{
494 494
 						case 'srt_modifiedtime':
495 495
 						case 'getlastmodified':
496
-							egw_vfs::touch($path,strtotime($prop['val']));
496
+							egw_vfs::touch($path, strtotime($prop['val']));
497 497
 							break;
498 498
 						//case 'srt_creationtime':
499 499
 							// no streamwrapper interface / php function to set the ctime currently
500 500
 							//$attributes['created'] = strtotime($prop['val']);
501 501
 							//break;
502 502
 						default:
503
-							if (!egw_vfs::proppatch($path,array($prop))) $options['props'][$key]['status'] = '403 Forbidden';
503
+							if (!egw_vfs::proppatch($path, array($prop))) $options['props'][$key]['status'] = '403 Forbidden';
504 504
 							break;
505 505
 					}
506 506
 					break;
507 507
 
508 508
 				case 'DAV:':
509
-					switch($prop['name'])
509
+					switch ($prop['name'])
510 510
 					{
511 511
 						// allow netdrive to change the modification time
512 512
 						case 'getlastmodified':
513
-							egw_vfs::touch($path,strtotime($prop['val']));
513
+							egw_vfs::touch($path, strtotime($prop['val']));
514 514
 							break;
515 515
 						// not sure why, the filesystem example of the WebDAV class does it ...
516 516
 						default:
@@ -520,16 +520,16 @@  discard block
 block discarded – undo
520 520
 					break;
521 521
 
522 522
 				case 'urn:schemas-microsoft-com:':
523
-					switch($prop['name'])
523
+					switch ($prop['name'])
524 524
 					{
525 525
 						case 'Win32LastModifiedTime':
526
-							egw_vfs::touch($path,strtotime($prop['val']));
526
+							egw_vfs::touch($path, strtotime($prop['val']));
527 527
 							break;
528 528
 						case 'Win32CreationTime':	// eg. "Wed, 14 Sep 2011 15:48:26 GMT"
529 529
 						case 'Win32LastAccessTime':
530 530
 						case 'Win32FileAttributes':	// not sure what that is, it was always "00000000"
531 531
 						default:
532
-							if (!egw_vfs::proppatch($path,array($prop))) $options['props'][$key]['status'] = '403 Forbidden';
532
+							if (!egw_vfs::proppatch($path, array($prop))) $options['props'][$key]['status'] = '403 Forbidden';
533 533
 							break;
534 534
 					}
535 535
 					break;
@@ -539,18 +539,18 @@  discard block
 block discarded – undo
539 539
 					$prop['name'] = '#'.$prop['name'];
540 540
 					// fall through
541 541
 				default:
542
-					if (!egw_vfs::proppatch($path,array($prop))) $options['props'][$key]['status'] = '403 Forbidden';
542
+					if (!egw_vfs::proppatch($path, array($prop))) $options['props'][$key]['status'] = '403 Forbidden';
543 543
 					break;
544 544
 			}
545 545
 			if ($this->debug) $props[] = '('.$prop['ns'].')'.$prop['name'].'='.$prop['val'];
546 546
 		}
547 547
 		if ($this->debug)
548 548
 		{
549
-			error_log(__METHOD__.": path=$options[path], props=".implode(', ',$props));
550
-			if ($attributes) error_log(__METHOD__.": path=$options[path], set attributes=".str_replace("\n",' ',print_r($attributes,true)));
549
+			error_log(__METHOD__.": path=$options[path], props=".implode(', ', $props));
550
+			if ($attributes) error_log(__METHOD__.": path=$options[path], set attributes=".str_replace("\n", ' ', print_r($attributes, true)));
551 551
 		}
552 552
 
553
-		return '';	// this is as the filesystem example handler does it, no true or false ...
553
+		return ''; // this is as the filesystem example handler does it, no true or false ...
554 554
 	}
555 555
 
556 556
 	/**
@@ -561,18 +561,18 @@  discard block
 block discarded – undo
561 561
 	 */
562 562
 	function LOCK(&$options)
563 563
 	{
564
-		if ($this->debug) error_log(__METHOD__.'('.str_replace(array("\n",'    '),'',print_r($options,true)).')');
564
+		if ($this->debug) error_log(__METHOD__.'('.str_replace(array("\n", '    '), '', print_r($options, true)).')');
565 565
 		// TODO recursive locks on directories not supported yet
566
-		if (is_dir($this->base . $options['path']) && !empty($options['depth']))
566
+		if (is_dir($this->base.$options['path']) && !empty($options['depth']))
567 567
 		{
568 568
 			return '409 Conflict';
569 569
 		}
570
-		$options['timeout'] = time()+300; // 5min. hardcoded
570
+		$options['timeout'] = time() + 300; // 5min. hardcoded
571 571
 
572 572
 		// dont know why, but HTTP_WebDAV_Server passes the owner in D:href tags, which get's passed unchanged to checkLock/PROPFIND
573 573
 		// that's wrong according to the standard and cadaver does not show it on discover --> strip_tags removes eventual tags
574
-		if (($ret = egw_vfs::lock($options['path'],$options['locktoken'],$options['timeout'],strip_tags($options['owner']),
575
-			$options['scope'],$options['type'],isset($options['update']))) && !isset($options['update']))
574
+		if (($ret = egw_vfs::lock($options['path'], $options['locktoken'], $options['timeout'], strip_tags($options['owner']),
575
+			$options['scope'], $options['type'], isset($options['update']))) && !isset($options['update']))
576 576
 		{
577 577
 			return $ret ? '200 OK' : '409 Conflict';
578 578
 		}
@@ -587,8 +587,8 @@  discard block
 block discarded – undo
587 587
 	 */
588 588
 	function UNLOCK(&$options)
589 589
 	{
590
-		if ($this->debug) error_log(__METHOD__.'('.str_replace(array("\n",'    '),'',print_r($options,true)).')');
591
-		return egw_vfs::unlock($options['path'],$options['token']) ? '204 No Content' : '409 Conflict';
590
+		if ($this->debug) error_log(__METHOD__.'('.str_replace(array("\n", '    '), '', print_r($options, true)).')');
591
+		return egw_vfs::unlock($options['path'], $options['token']) ? '204 No Content' : '409 Conflict';
592 592
 	}
593 593
 
594 594
 	/**
@@ -627,9 +627,9 @@  discard block
 block discarded – undo
627 627
 	 */
628 628
 	function __construct()
629 629
 	{
630
-		if ($_SERVER['REQUEST_METHOD'] == 'GET' && (($this->force_download = strpos($_SERVER['REQUEST_URI'],'?download')) !== false))
630
+		if ($_SERVER['REQUEST_METHOD'] == 'GET' && (($this->force_download = strpos($_SERVER['REQUEST_URI'], '?download')) !== false))
631 631
 		{
632
-			$_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'],0,$this->force_download);
632
+			$_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], 0, $this->force_download);
633 633
 		}
634 634
 		parent::HTTP_WebDAV_Server();
635 635
 	}
@@ -644,7 +644,7 @@  discard block
 block discarded – undo
644 644
 	 */
645 645
 	function GET(&$options)
646 646
 	{
647
-		if (is_dir($this->base . $options["path"]))
647
+		if (is_dir($this->base.$options["path"]))
648 648
 		{
649 649
 			return $this->autoindex($options);
650 650
 		}
@@ -652,11 +652,11 @@  discard block
 block discarded – undo
652 652
 		{
653 653
 			// mitigate risks of serving javascript or css from our domain
654 654
 			html::safe_content_header($options['stream'], $options['path'], $options['mimetype'], $options['size'], false,
655
-				$this->force_download, true);	// true = do not send content-type and content-length header, but modify values
655
+				$this->force_download, true); // true = do not send content-type and content-length header, but modify values
656 656
 
657 657
 			if (!is_resource($options['stream']))
658 658
 			{
659
-				$options['data'] =& $options['stream'];
659
+				$options['data'] = & $options['stream'];
660 660
 				unset($options['stream']);
661 661
 			}
662 662
 		}
@@ -675,9 +675,9 @@  discard block
 block discarded – undo
675 675
 			'depth' => 1,
676 676
 		);
677 677
 		$files = array();
678
-		if (($ret = $this->PROPFIND($propfind_options,$files)) !== true)
678
+		if (($ret = $this->PROPFIND($propfind_options, $files)) !== true)
679 679
 		{
680
-			return $ret;	// no collection
680
+			return $ret; // no collection
681 681
 		}
682 682
 		header('Content-type: text/html; charset='.translation::charset());
683 683
 		echo "<html>\n<head>\n\t<title>".'EGroupware WebDAV server '.htmlspecialchars($options['path'])."</title>\n";
@@ -689,10 +689,10 @@  discard block
 block discarded – undo
689 689
 		echo '<h1>WebDAV ';
690 690
 		list(,$base) = explode(parse_url($GLOBALS['egw_info']['server']['webserver_url'], PHP_URL_PATH), $this->base_uri, 2);
691 691
 		$path = $base;
692
-		foreach(explode('/',$this->_unslashify($options['path'])) as $n => $name)
692
+		foreach (explode('/', $this->_unslashify($options['path'])) as $n => $name)
693 693
 		{
694 694
 			$path .= ($n != 1 ? '/' : '').$name;
695
-			echo html::a_href(htmlspecialchars($name.'/'),$path);
695
+			echo html::a_href(htmlspecialchars($name.'/'), $path);
696 696
 		}
697 697
 		echo "</h1>\n";
698 698
 
@@ -709,18 +709,18 @@  discard block
 block discarded – undo
709 709
 		);
710 710
 		$n = 0;
711 711
 		$collection_props = null;
712
-		foreach($files['files'] as $file)
712
+		foreach ($files['files'] as $file)
713 713
 		{
714 714
 			if (!isset($collection_props))
715 715
 			{
716 716
 				$collection_props = $this->props2array($file['props']);
717 717
 				echo '<h3>'.lang('Collection listing').': '.htmlspecialchars($collection_props['DAV:displayname'])."</h3>\n";
718
-				continue;	// own entry --> displaying properies later
718
+				continue; // own entry --> displaying properies later
719 719
 			}
720
-			if(!$n++)
720
+			if (!$n++)
721 721
 			{
722 722
 				echo "<table>\n\t<tr class='th'>\n\t\t<th>#</th>\n\t\t<th>".lang('Name')."</th>";
723
-				foreach($props2show as $label)
723
+				foreach ($props2show as $label)
724 724
 				{
725 725
 					echo "\t\t<th>".lang($label)."</th>\n";
726 726
 				}
@@ -730,9 +730,9 @@  discard block
 block discarded – undo
730 730
 			//echo $file['path']; _debug_array($props);
731 731
 			$class = $class == 'row_on' ? 'row_off' : 'row_on';
732 732
 
733
-			if (substr($file['path'],-1) == '/')
733
+			if (substr($file['path'], -1) == '/')
734 734
 			{
735
-				$name = basename(substr($file['path'],0,-1)).'/';
735
+				$name = basename(substr($file['path'], 0, -1)).'/';
736 736
 			}
737 737
 			else
738 738
 			{
@@ -740,14 +740,14 @@  discard block
 block discarded – undo
740 740
 			}
741 741
 
742 742
 			echo "\t<tr class='$class'>\n\t\t<td>$n</td>\n\t\t<td>".
743
-				html::a_href(htmlspecialchars($name),$base.strtr($file['path'], array(
743
+				html::a_href(htmlspecialchars($name), $base.strtr($file['path'], array(
744 744
 					'%' => '%25',
745 745
 					'#' => '%23',
746 746
 					'?' => '%3F',
747 747
 				)))."</td>\n";
748
-			foreach($props2show as $prop => $label)
748
+			foreach ($props2show as $prop => $label)
749 749
 			{
750
-				echo "\t\t<td>".($prop=='DAV:getlastmodified'&&!empty($props[$prop])?date('Y-m-d H:i:s',$props[$prop]):$props[$prop])."</td>\n";
750
+				echo "\t\t<td>".($prop == 'DAV:getlastmodified' && !empty($props[$prop]) ? date('Y-m-d H:i:s', $props[$prop]) : $props[$prop])."</td>\n";
751 751
 			}
752 752
 			echo "\t</tr>\n";
753 753
 		}
@@ -761,12 +761,12 @@  discard block
 block discarded – undo
761 761
 		}
762 762
 		echo '<h3>'.lang('Properties')."</h3>\n";
763 763
 		echo "<table>\n\t<tr class='th'><th>".lang('Namespace')."</th><th>".lang('Name')."</th><th>".lang('Value')."</th></tr>\n";
764
-		foreach($collection_props as $name => $value)
764
+		foreach ($collection_props as $name => $value)
765 765
 		{
766 766
 			$class = $class == 'row_on' ? 'row_off' : 'row_on';
767
-			$parts = explode(':',$name);
767
+			$parts = explode(':', $name);
768 768
 			$name = array_pop($parts);
769
-			$ns = implode(':',$parts);
769
+			$ns = implode(':', $parts);
770 770
 			echo "\t<tr class='$class'>\n\t\t<td>".htmlspecialchars($ns)."</td><td style='white-space: nowrap'>".htmlspecialchars($name)."</td>\n";
771 771
 			echo "\t\t<td>".$value."</td>\n\t</tr>\n";
772 772
 		}
@@ -809,11 +809,11 @@  discard block
 block discarded – undo
809 809
 				'wrap'            => 0,
810 810
 			));
811 811
 		}
812
-		if (($href=preg_match('/\<(D:)?href\>[^<]+\<\/(D:)?href\>/i',$value)))
812
+		if (($href = preg_match('/\<(D:)?href\>[^<]+\<\/(D:)?href\>/i', $value)))
813 813
 		{
814
-			$value = preg_replace('/\<(D:)?href\>('.preg_quote($this->base_uri.'/','/').')?([^<]+)\<\/(D:)?href\>/i','<\\1href><a href="\\2\\3">\\3</a></\\4href>',$value);
814
+			$value = preg_replace('/\<(D:)?href\>('.preg_quote($this->base_uri.'/', '/').')?([^<]+)\<\/(D:)?href\>/i', '<\\1href><a href="\\2\\3">\\3</a></\\4href>', $value);
815 815
 		}
816
-		$ret = $value[0] == '<'  || strpos($value, "\n") !== false ?
816
+		$ret = $value[0] == '<' || strpos($value, "\n") !== false ?
817 817
 			'<pre>'.htmlspecialchars($value).'</pre>' : htmlspecialchars($value);
818 818
 
819 819
 		if ($href)
@@ -833,10 +833,10 @@  discard block
 block discarded – undo
833 833
 	protected function props2array(array $props)
834 834
 	{
835 835
 		$arr = array();
836
-		foreach($props as $prop)
836
+		foreach ($props as $prop)
837 837
 		{
838 838
 			$ns_hash = array('DAV:' => 'D');
839
-			switch($prop['ns'])
839
+			switch ($prop['ns'])
840 840
 			{
841 841
 				case 'DAV:';
842 842
 					$ns = 'DAV';
@@ -846,10 +846,10 @@  discard block
 block discarded – undo
846 846
 			}
847 847
 			if (is_array($prop['val']))
848 848
 			{
849
-				$prop['val'] = $this->_hierarchical_prop_encode($prop['val'], $prop['ns'], $ns_defs='', $ns_hash);
849
+				$prop['val'] = $this->_hierarchical_prop_encode($prop['val'], $prop['ns'], $ns_defs = '', $ns_hash);
850 850
 				// hack to show real namespaces instead of not (visibly) defined shortcuts
851 851
 				unset($ns_hash['DAV:']);
852
-				$value = strtr($v=$this->prop_value($prop['val']),array_flip($ns_hash));
852
+				$value = strtr($v = $this->prop_value($prop['val']), array_flip($ns_hash));
853 853
 			}
854 854
 			else
855 855
 			{
Please login to merge, or discard this patch.
Braces   +133 added lines, -50 removed lines patch added patch discarded remove patch
@@ -63,7 +63,8 @@  discard block
 block discarded – undo
63 63
 		// special treatment for litmus compliance test
64 64
 		// reply on its identifier header
65 65
 		// not needed for the test itself but eases debugging
66
-		if (isset($this->_SERVER['HTTP_X_LITMUS'])) {
66
+		if (isset($this->_SERVER['HTTP_X_LITMUS']))
67
+		{
67 68
 			error_log("Litmus test ".$this->_SERVER['HTTP_X_LITMUS']);
68 69
 			header("X-Litmus-reply: ".$this->_SERVER['HTTP_X_LITMUS']);
69 70
 		}
@@ -123,24 +124,30 @@  discard block
 block discarded – undo
123 124
         $parent = egw_vfs::dirname($path);
124 125
         $name   = egw_vfs::basename($path);
125 126
 
126
-        if (!file_exists($parent)) {
127
+        if (!file_exists($parent))
128
+        {
127 129
             return "409 Conflict";
128 130
         }
129 131
 
130
-        if (!is_dir($parent)) {
132
+        if (!is_dir($parent))
133
+        {
131 134
             return "403 Forbidden";
132 135
         }
133 136
 
134
-        if ( file_exists($path) ) {
137
+        if ( file_exists($path) )
138
+        {
135 139
             return "405 Method not allowed";
136 140
         }
137 141
 
138
-        if (!empty($this->_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
142
+        if (!empty($this->_SERVER["CONTENT_LENGTH"]))
143
+        {
144
+// no body parsing yet
139 145
             return "415 Unsupported media type";
140 146
         }
141 147
 
142 148
         $stat = mkdir($path, 0777);
143
-        if (!$stat) {
149
+        if (!$stat)
150
+        {
144 151
             return "403 Forbidden";
145 152
         }
146 153
 
@@ -157,24 +164,35 @@  discard block
 block discarded – undo
157 164
     {
158 165
         // TODO Property updates still broken (Litmus should detect this?)
159 166
 
160
-        if (!empty($this->_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
167
+        if (!empty($this->_SERVER["CONTENT_LENGTH"]))
168
+        {
169
+// no body parsing yet
161 170
             return "415 Unsupported media type";
162 171
         }
163 172
 
164 173
         // no copying to different WebDAV Servers yet
165
-        if (isset($options["dest_url"])) {
174
+        if (isset($options["dest_url"]))
175
+        {
166 176
             return "502 bad gateway";
167 177
         }
168 178
 
169 179
         $source = $this->base .$options["path"];
170
-        if (!file_exists($source)) return "404 Not found";
180
+        if (!file_exists($source))
181
+        {
182
+        	return "404 Not found";
183
+        }
171 184
 
172
-        if (is_dir($source)) { // resource is a collection
173
-            switch ($options["depth"]) {
185
+        if (is_dir($source))
186
+        {
187
+// resource is a collection
188
+            switch ($options["depth"])
189
+            {
174 190
             case "infinity": // valid
175 191
                 break;
176 192
             case "0": // valid for COPY only
177
-                if ($del) { // MOVE?
193
+                if ($del)
194
+                {
195
+// MOVE?
178 196
                     return "400 Bad request";
179 197
                 }
180 198
                 break;
@@ -187,71 +205,99 @@  discard block
 block discarded – undo
187 205
         $dest         = $this->base . $options["dest"];
188 206
         $destdir      = dirname($dest);
189 207
 
190
-        if (!file_exists($destdir) || !is_dir($destdir)) {
208
+        if (!file_exists($destdir) || !is_dir($destdir))
209
+        {
191 210
             return "409 Conflict";
192 211
         }
193 212
 
194 213
         $new          = !file_exists($dest);
195 214
         $existing_col = false;
196 215
 
197
-        if (!$new) {
198
-            if ($del && is_dir($dest)) {
199
-                if (!$options["overwrite"]) {
216
+        if (!$new)
217
+        {
218
+            if ($del && is_dir($dest))
219
+            {
220
+                if (!$options["overwrite"])
221
+                {
200 222
                     return "412 precondition failed";
201 223
                 }
202 224
                 $dest .= basename($source);
203
-                if (file_exists($dest)) {
225
+                if (file_exists($dest))
226
+                {
204 227
                     $options["dest"] .= basename($source);
205
-                } else {
228
+                }
229
+                else
230
+                {
206 231
                     $new          = true;
207 232
                     $existing_col = true;
208 233
                 }
209 234
             }
210 235
         }
211 236
 
212
-        if (!$new) {
213
-            if ($options["overwrite"]) {
237
+        if (!$new)
238
+        {
239
+            if ($options["overwrite"])
240
+            {
214 241
                 $stat = $this->DELETE(array("path" => $options["dest"]));
215
-                if (($stat{0} != "2") && (substr($stat, 0, 3) != "404")) {
242
+                if (($stat{0} != "2") && (substr($stat, 0, 3) != "404"))
243
+                {
216 244
                     return $stat;
217 245
                 }
218
-            } else {
246
+            }
247
+            else
248
+            {
219 249
                 return "412 precondition failed";
220 250
             }
221 251
         }
222 252
 
223
-        if ($del) {
224
-            if (!rename($source, $dest)) {
253
+        if ($del)
254
+        {
255
+            if (!rename($source, $dest))
256
+            {
225 257
                 return "500 Internal server error";
226 258
             }
227
-        } else {
228
-            if (is_dir($source) && $options['depth'] == 'infinity') {
259
+        }
260
+        else
261
+        {
262
+            if (is_dir($source) && $options['depth'] == 'infinity')
263
+            {
229 264
             	$files = egw_vfs::find($source,array('depth' => true,'url' => true));	// depth=true: return dirs first, url=true: allow urls!
230
-            } else {
265
+            }
266
+            else
267
+            {
231 268
                 $files = array($source);
232 269
             }
233 270
 
234
-            if (!is_array($files) || empty($files)) {
271
+            if (!is_array($files) || empty($files))
272
+            {
235 273
                 return "500 Internal server error";
236 274
             }
237 275
 
238 276
 
239
-            foreach ($files as $file) {
240
-                if (is_dir($file)) {
277
+            foreach ($files as $file)
278
+            {
279
+                if (is_dir($file))
280
+                {
241 281
                     $file = $this->_slashify($file);
242 282
                 }
243 283
 
244 284
                 $destfile = str_replace($source, $dest, $file);
245 285
 
246
-                if (is_dir($file)) {
247
-                    if (!is_dir($destfile)) {
286
+                if (is_dir($file))
287
+                {
288
+                    if (!is_dir($destfile))
289
+                    {
248 290
                         // TODO "mkdir -p" here? (only natively supported by PHP 5)
249
-                        if (!@mkdir($destfile)) {
291
+                        if (!@mkdir($destfile))
292
+                        {
250 293
                             return "409 Conflict";
251 294
                         }
252 295
                     }
253
-                } else {
254
-                    if (!@copy($file, $destfile)) {
296
+                }
297
+                else
298
+                {
299
+                    if (!@copy($file, $destfile))
300
+                    {
255 301
                         return "409 Conflict";
256 302
                     }
257 303
                 }
@@ -301,17 +347,23 @@  discard block
 block discarded – undo
301 347
         $info["props"][] = HTTP_WebDAV_Server::mkprop("ishidden",        egw_vfs::is_hidden($fspath));
302 348
 
303 349
 		// type and size (caller already made sure that path exists)
304
-		if (is_dir($fspath)) {
350
+		if (is_dir($fspath))
351
+		{
305 352
 			// directory (WebDAV collection)
306 353
 			$info['props'][] = HTTP_WebDAV_Server::mkprop	('resourcetype', array(
307 354
 			 	HTTP_WebDAV_Server::mkprop('collection', '')));
308 355
 			$info['props'][] = HTTP_WebDAV_Server::mkprop	('getcontenttype', 'httpd/unix-directory');
309
-		} else {
356
+		}
357
+		else
358
+		{
310 359
 			// plain file (WebDAV resource)
311 360
 			$info['props'][] = HTTP_WebDAV_Server::mkprop	('resourcetype', '');
312
-			if (egw_vfs::is_readable($path)) {
361
+			if (egw_vfs::is_readable($path))
362
+			{
313 363
 				$info['props'][] = HTTP_WebDAV_Server::mkprop	('getcontenttype', egw_vfs::mime_content_type($path));
314
-			} else {
364
+			}
365
+			else
366
+			{
315 367
 				error_log(__METHOD__."($path) $fspath is not readable!");
316 368
 				$info['props'][] = HTTP_WebDAV_Server::mkprop	('getcontenttype', 'application/x-non-readable');
317 369
 			}
@@ -383,7 +435,10 @@  discard block
 block discarded – undo
383 435
 				continue;
384 436
 			}
385 437
 			$_path = $info['path'];
386
-			if (!$n && $info['path'] != '/' && substr($info['path'],-1) == '/') $_path = substr($info['path'],0,-1);
438
+			if (!$n && $info['path'] != '/' && substr($info['path'],-1) == '/')
439
+			{
440
+				$_path = substr($info['path'],0,-1);
441
+			}
387 442
 
388 443
 			// need to encode path again, as $info['path'] is NOT encoded, but egw_vfs::(stat|propfind) require it
389 444
 			// otherwise pathes containing url special chars like ? or # will not stat
@@ -422,16 +477,22 @@  discard block
 block discarded – undo
422 477
 				$fileprops =& $files['files'][$path2n[$path]]['props'];
423 478
 				foreach($props as $prop)
424 479
 				{
425
-					if ($prop['ns'] == egw_vfs::DEFAULT_PROP_NAMESPACE && $prop['name'][0] == '#')	// eGW's customfields
480
+					if ($prop['ns'] == egw_vfs::DEFAULT_PROP_NAMESPACE && $prop['name'][0] == '#')
481
+					{
482
+						// eGW's customfields
426 483
 					{
427 484
 						$prop['ns'] .= 'customfields/';
485
+					}
428 486
 						$prop['name'] = substr($prop['name'],1);
429 487
 					}
430 488
 					$fileprops[] = $prop;
431 489
 				}
432 490
 			}
433 491
 		}
434
-		if ($this->debug) error_log(__METHOD__."() props=".array2string($files['files']));
492
+		if ($this->debug)
493
+		{
494
+			error_log(__METHOD__."() props=".array2string($files['files']));
495
+		}
435 496
 		return true;
436 497
 	}
437 498
 
@@ -483,7 +544,8 @@  discard block
 block discarded – undo
483 544
 	{
484 545
 		$path = translation::convert($options['path'],'utf-8');
485 546
 
486
-		foreach ($options['props'] as $key => $prop) {
547
+		foreach ($options['props'] as $key => $prop)
548
+		{
487 549
 			$attributes = array();
488 550
 			switch($prop['ns'])
489 551
 			{
@@ -500,7 +562,10 @@  discard block
 block discarded – undo
500 562
 							//$attributes['created'] = strtotime($prop['val']);
501 563
 							//break;
502 564
 						default:
503
-							if (!egw_vfs::proppatch($path,array($prop))) $options['props'][$key]['status'] = '403 Forbidden';
565
+							if (!egw_vfs::proppatch($path,array($prop)))
566
+							{
567
+								$options['props'][$key]['status'] = '403 Forbidden';
568
+							}
504 569
 							break;
505 570
 					}
506 571
 					break;
@@ -529,7 +594,10 @@  discard block
 block discarded – undo
529 594
 						case 'Win32LastAccessTime':
530 595
 						case 'Win32FileAttributes':	// not sure what that is, it was always "00000000"
531 596
 						default:
532
-							if (!egw_vfs::proppatch($path,array($prop))) $options['props'][$key]['status'] = '403 Forbidden';
597
+							if (!egw_vfs::proppatch($path,array($prop)))
598
+							{
599
+								$options['props'][$key]['status'] = '403 Forbidden';
600
+							}
533 601
 							break;
534 602
 					}
535 603
 					break;
@@ -539,15 +607,24 @@  discard block
 block discarded – undo
539 607
 					$prop['name'] = '#'.$prop['name'];
540 608
 					// fall through
541 609
 				default:
542
-					if (!egw_vfs::proppatch($path,array($prop))) $options['props'][$key]['status'] = '403 Forbidden';
610
+					if (!egw_vfs::proppatch($path,array($prop)))
611
+					{
612
+						$options['props'][$key]['status'] = '403 Forbidden';
613
+					}
543 614
 					break;
544 615
 			}
545
-			if ($this->debug) $props[] = '('.$prop['ns'].')'.$prop['name'].'='.$prop['val'];
616
+			if ($this->debug)
617
+			{
618
+				$props[] = '('.$prop['ns'].')'.$prop['name'].'='.$prop['val'];
619
+			}
546 620
 		}
547 621
 		if ($this->debug)
548 622
 		{
549 623
 			error_log(__METHOD__.": path=$options[path], props=".implode(', ',$props));
550
-			if ($attributes) error_log(__METHOD__.": path=$options[path], set attributes=".str_replace("\n",' ',print_r($attributes,true)));
624
+			if ($attributes)
625
+			{
626
+				error_log(__METHOD__.": path=$options[path], set attributes=".str_replace("\n",' ',print_r($attributes,true)));
627
+			}
551 628
 		}
552 629
 
553 630
 		return '';	// this is as the filesystem example handler does it, no true or false ...
@@ -561,7 +638,10 @@  discard block
 block discarded – undo
561 638
 	 */
562 639
 	function LOCK(&$options)
563 640
 	{
564
-		if ($this->debug) error_log(__METHOD__.'('.str_replace(array("\n",'    '),'',print_r($options,true)).')');
641
+		if ($this->debug)
642
+		{
643
+			error_log(__METHOD__.'('.str_replace(array("\n",'    '),'',print_r($options,true)).')');
644
+		}
565 645
 		// TODO recursive locks on directories not supported yet
566 646
 		if (is_dir($this->base . $options['path']) && !empty($options['depth']))
567 647
 		{
@@ -587,7 +667,10 @@  discard block
 block discarded – undo
587 667
 	 */
588 668
 	function UNLOCK(&$options)
589 669
 	{
590
-		if ($this->debug) error_log(__METHOD__.'('.str_replace(array("\n",'    '),'',print_r($options,true)).')');
670
+		if ($this->debug)
671
+		{
672
+			error_log(__METHOD__.'('.str_replace(array("\n",'    '),'',print_r($options,true)).')');
673
+		}
591 674
 		return egw_vfs::unlock($options['path'],$options['token']) ? '204 No Content' : '409 Conflict';
592 675
 	}
593 676
 
Please login to merge, or discard this patch.
phpgwapi/inc/common_functions.inc.php 5 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -959,7 +959,7 @@  discard block
 block discarded – undo
959 959
  * @author skeeter
960 960
  * This function is used to retrieve a value from a user defined order of methods.
961 961
  * $this->id = get_var('id',array('HTTP_POST_VARS'||'POST','HTTP_GET_VARS'||'GET','HTTP_COOKIE_VARS'||'COOKIE','GLOBAL','DEFAULT'));
962
- * @param $variable name
962
+ * @param string $variable name
963 963
  * @param $method ordered array of methods to search for supplied variable
964 964
  * @param $default_value (optional)
965 965
  */
@@ -1186,7 +1186,7 @@  discard block
 block discarded – undo
1186 1186
  * This is completely unnecessary, as you can use forward slashes in php under every OS -- RalfBecker 2005/11/09
1187 1187
  *
1188 1188
  * @deprecated just use forward slashes supported by PHP on all OS
1189
- * @return file system separator
1189
+ * @return string system separator
1190 1190
  */
1191 1191
 function filesystem_separator()
1192 1192
 {
Please login to merge, or discard this patch.
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -470,11 +470,11 @@
 block discarded – undo
470 470
 }
471 471
 
472 472
 /**
473
-  * Allows for array and direct function params as well as sanatization.
474
-  *
475
-  * @author seek3r
476
-  * This function is used to validate param data as well as offer flexible function usage.
477
-  *
473
+ * Allows for array and direct function params as well as sanatization.
474
+ *
475
+ * @author seek3r
476
+ * This function is used to validate param data as well as offer flexible function usage.
477
+ *
478 478
 	function somefunc()
479 479
 	{
480 480
 		$expected_args[0] = Array('name'=>'fname','default'=>'joe', 'type'=>'string');
Please login to merge, or discard this patch.
Spacing   +202 added lines, -202 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 spl_autoload_register(function($class)
38 38
 {
39 39
 	$parts = explode('\\', $class);
40
-	if (array_shift($parts) != 'EGroupware') return;	// not our prefix
40
+	if (array_shift($parts) != 'EGroupware') return; // not our prefix
41 41
 
42 42
 	$app = lcfirst(array_shift($parts));
43 43
 	$base = EGW_INCLUDE_ROOT.'/'.$app.'/src/';
@@ -65,14 +65,14 @@  discard block
 block discarded – undo
65 65
 	// fixing warnings generated by php 5.3.8 is_a($obj) trying to autoload huge strings
66 66
 	if (strlen($class) > 64 || strpos($class, '.') !== false) return;
67 67
 
68
-	$components = explode('_',$class);
68
+	$components = explode('_', $class);
69 69
 	$app = array_shift($components);
70 70
 	// classes using the new naming schema app_class_name, eg. admin_cmd
71 71
 	if (file_exists($file = EGW_INCLUDE_ROOT.'/'.$app.'/inc/class.'.$class.'.inc.php') ||
72 72
 		// classes using the new naming schema app_class_name, eg. admin_cmd
73 73
 		isset($components[0]) && file_exists($file = EGW_INCLUDE_ROOT.'/'.$app.'/inc/class.'.$app.'_'.$components[0].'.inc.php') ||
74 74
 		// classes with an underscore in their name
75
-		!isset($GLOBALS['egw_info']['apps'][$app]) && isset($GLOBALS['egw_info']['apps'][$app . '_' . $components[0]]) &&
75
+		!isset($GLOBALS['egw_info']['apps'][$app]) && isset($GLOBALS['egw_info']['apps'][$app.'_'.$components[0]]) &&
76 76
 			file_exists($file = EGW_INCLUDE_ROOT.'/'.$app.'_'.$components[0].'/inc/class.'.$class.'.inc.php') ||
77 77
 		// eGW api classes using the old naming schema, eg. html
78 78
 		file_exists($file = EGW_API_INC.'/class.'.$class.'.inc.php') ||
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 		// include_once('Horde/String.php') to return true, even if the former was included with an absolute path
86 86
 		// only use include_path, if no Composer vendor directory exists
87 87
 		!isset($GLOBALS['egw_info']['apps'][$app]) && !file_exists(EGW_SERVER_ROOT.'/vendor') &&
88
-			@include($file = strtr($class, array('_'=>'/','\\'=>'/')).'.php'))
88
+			@include($file = strtr($class, array('_'=>'/', '\\'=>'/')).'.php'))
89 89
 	{
90 90
 		include_once($file);
91 91
 		//if (!class_exists($class, false) && !interface_exists($class, false)) error_log("autoloading class $class by include_once($file) failed!");
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 	// allow apps to define an own autoload method
94 94
 	elseif (isset($GLOBALS['egw_info']['flags']['autoload']) && is_callable($GLOBALS['egw_info']['flags']['autoload']))
95 95
 	{
96
-		call_user_func($GLOBALS['egw_info']['flags']['autoload'],$class);
96
+		call_user_func($GLOBALS['egw_info']['flags']['autoload'], $class);
97 97
 	}
98 98
 });
99 99
 
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 	{
116 116
 		return stripslashes($var);
117 117
 	}
118
-	foreach($var as $key => $val)
118
+	foreach ($var as $key => $val)
119 119
 	{
120 120
 		$var[$key] = is_array($val) ? array_stripslashes($val) : stripslashes($val);
121 121
 	}
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
 
136 136
 	if (is_null($func_overload)) $func_overload = extension_loaded('mbstring') ? ini_get('mbstring.func_overload') : 0;
137 137
 
138
-	return $func_overload & 2 ? mb_strlen($str,'ascii') : strlen($str);
138
+	return $func_overload&2 ? mb_strlen($str, 'ascii') : strlen($str);
139 139
 }
140 140
 
141 141
 /**
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
  * @param int $len
147 147
  * @return string
148 148
  */
149
-function cut_bytes(&$data,$offset,$len=null)
149
+function cut_bytes(&$data, $offset, $len = null)
150 150
 {
151 151
 	static $func_overload = null;
152 152
 
@@ -154,9 +154,9 @@  discard block
 block discarded – undo
154 154
 
155 155
 	if (is_null($len))
156 156
 	{
157
-		return $func_overload & 2 ? mb_substr($data,$offset,bytes($data),'ascii') : substr($data,$offset);
157
+		return $func_overload&2 ? mb_substr($data, $offset, bytes($data), 'ascii') : substr($data, $offset);
158 158
 	}
159
-	return $func_overload & 2 ? mb_substr($data,$offset,$len,'ascii') : substr($data,$offset,$len);
159
+	return $func_overload&2 ? mb_substr($data, $offset, $len, 'ascii') : substr($data, $offset, $len);
160 160
 }
161 161
 
162 162
 if (!function_exists('imap_rfc822_parse_adrlist'))
@@ -188,10 +188,10 @@  discard block
 block discarded – undo
188 188
 	{
189 189
 		$addresses = array();
190 190
 		$pending = '';
191
-		foreach(explode(',', $address) as $part)
191
+		foreach (explode(',', $address) as $part)
192 192
 		{
193 193
 			$trimmed = trim(($pending ? $pending.',' : '').$part);
194
-			if (($trimmed[0] == '"' && substr($trimmed, -1) != '>')||strpos($part, '@')===false)
194
+			if (($trimmed[0] == '"' && substr($trimmed, -1) != '>') || strpos($part, '@') === false)
195 195
 			{
196 196
 				$pending .= ($pending ? $pending.',' : '').$part;
197 197
 				continue;
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
 		//if (!preg_match('/^[!#$%&\'*+/0-9=?A-Z^_`a-z{|}~-]+$/u', $personal))	// that's how I read the rfc(2)822
245 245
 		if ($personal && !preg_match('/^[0-9A-Z -]*$/iu', $personal))	// but quoting is never wrong, so quote more then necessary
246 246
 		{
247
-			$personal = '"'.str_replace(array('\\', '"'),array('\\\\', '\\"'), $personal).'"';
247
+			$personal = '"'.str_replace(array('\\', '"'), array('\\\\', '\\"'), $personal).'"';
248 248
 		}
249 249
 		return ($personal ? $personal.' <' : '').$mailbox.($host ? '@'.$host : '').($personal ? '>' : '');
250 250
 	}
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 	{
266 266
 		return array((object)array(
267 267
 			'text' => Horde_Mime::decode($text),
268
-			'charset' => translation::charset(),	// is already in our internal encoding!
268
+			'charset' => translation::charset(), // is already in our internal encoding!
269 269
 		));
270 270
 	}
271 271
 }
@@ -294,7 +294,7 @@  discard block
 block discarded – undo
294 294
 	 * @param int $len
295 295
 	 * @return string
296 296
 	 */
297
-	function mb_substr(&$data, $offset, $len=null)
297
+	function mb_substr(&$data, $offset, $len = null)
298 298
 	{
299 299
 		return is_null($len) ? substr($data, $offset) : substr($data, $offset, $len);
300 300
 	}
@@ -322,7 +322,7 @@  discard block
 block discarded – undo
322 322
 			return 'NULL';
323 323
 		case 'object':
324 324
 		case 'array':
325
-			return str_replace(array("\n",'    '/*,'Array'*/),'',print_r($var,true));
325
+			return str_replace(array("\n", '    '/*,'Array'*/), '', print_r($var, true));
326 326
 	}
327 327
 	return 'UNKNOWN TYPE!';
328 328
 }
@@ -334,18 +334,18 @@  discard block
 block discarded – undo
334 334
  * @param boolean $throw =false should we throw an exception, if $extension could not be loaded, default false = no
335 335
  * @return boolean true if loaded now, false otherwise
336 336
  */
337
-function check_load_extension($extension,$throw=false)
337
+function check_load_extension($extension, $throw = false)
338 338
 {
339 339
 	if (!defined('PHP_SHLIB_PREFIX'))
340 340
 	{
341
-		define('PHP_SHLIB_PREFIX',PHP_SHLIB_SUFFIX == 'dll' ? 'php_' : '');
341
+		define('PHP_SHLIB_PREFIX', PHP_SHLIB_SUFFIX == 'dll' ? 'php_' : '');
342 342
 	}
343 343
 	// we check for the existens of 'dl', as multithreaded webservers dont have it and some hosters disable it !!!
344
-	$loaded = extension_loaded($extension) || function_exists('dl') && @dl($dl=PHP_SHLIB_PREFIX.$extension.'.'.PHP_SHLIB_SUFFIX);
344
+	$loaded = extension_loaded($extension) || function_exists('dl') && @dl($dl = PHP_SHLIB_PREFIX.$extension.'.'.PHP_SHLIB_SUFFIX);
345 345
 
346 346
 	if (!$loaded && $throw)
347 347
 	{
348
-		throw new Exception ("PHP extension '$extension' not loaded AND can NOT be loaded via dl('$dl')!");
348
+		throw new Exception("PHP extension '$extension' not loaded AND can NOT be loaded via dl('$dl')!");
349 349
 	}
350 350
 	return $loaded;
351 351
 }
@@ -355,7 +355,7 @@  discard block
 block discarded – undo
355 355
  */
356 356
 function print_debug_subarray($array)
357 357
 {
358
-	foreach($array as $key => $value)
358
+	foreach ($array as $key => $value)
359 359
 	{
360 360
 		if (is_array($value))
361 361
 		{
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
  * This function is used to debugging data.
377 377
  * print_debug('this is some debugging data',$somevar);
378 378
  */
379
-function print_debug($message,$var = 'messageonly',$part = 'app', $level = 3)
379
+function print_debug($message, $var = 'messageonly', $part = 'app', $level = 3)
380 380
 {
381 381
 	if (($part == 'app' && DEBUG_APP == True) || ($part == 'api' && DEBUG_API == True))
382 382
 	{
@@ -405,12 +405,12 @@  discard block
 block discarded – undo
405 405
 				}
406 406
 
407 407
 				/* Bit 1 means to output to screen */
408
-				if (!!(DEBUG_OUTPUT & 1))
408
+				if (!!(DEBUG_OUTPUT&1))
409 409
 				{
410 410
 					echo "$output<br>\n";
411 411
 				}
412 412
 				/* Bit 2 means to output to sql */
413
-				if (!!(DEBUG_OUTPUT & 2))
413
+				if (!!(DEBUG_OUTPUT&2))
414 414
 				{
415 415
 					/* Need to flesh this out still. I dont have a table to dump this in yet.*/
416 416
 					/* So the SQL statement will go here*/
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 			}
431 431
 			else
432 432
 			{
433
-				if (floor(phpversion()) > 3 && !!(DEBUG_OUTPUT & 2))
433
+				if (floor(phpversion()) > 3 && !!(DEBUG_OUTPUT&2))
434 434
 				{
435 435
 					ob_start();
436 436
 				}
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
 				print_r($var);
439 439
 				if (DEBUG_DATATYPES)
440 440
 				{
441
-					foreach($var as $key => $value)
441
+					foreach ($var as $key => $value)
442 442
 					{
443 443
 						if (is_array($value))
444 444
 						{
@@ -453,13 +453,13 @@  discard block
 block discarded – undo
453 453
 					print_r($vartypes);
454 454
 				}
455 455
 				echo "\n<pre>\n";
456
-				if (floor(phpversion()) > 3 && !!(DEBUG_OUTPUT & 2))
456
+				if (floor(phpversion()) > 3 && !!(DEBUG_OUTPUT&2))
457 457
 				{
458 458
 					$output .= ob_get_contents();
459 459
 					ob_end_clean();
460 460
 					/* Need to flesh this out still. I dont have a table to dump this in yet.*/
461 461
 					/* So the SQL statement will go here*/
462
-					if (!!(DEBUG_OUTPUT & 1))
462
+					if (!!(DEBUG_OUTPUT&1))
463 463
 					{
464 464
 						echo "$output<br>\n";
465 465
 					}
@@ -507,7 +507,7 @@  discard block
 block discarded – undo
507 507
 	Its using the default value for the second param.
508 508
 	Of course if you have the second param as a required field it will fail to work.
509 509
  */
510
-function safe_args($expected, $recieved, $line='??', $file='??')
510
+function safe_args($expected, $recieved, $line = '??', $file = '??')
511 511
 {
512 512
 	/* This array will contain all the required fields */
513 513
 	$required = Array();
@@ -530,16 +530,16 @@  discard block
 block discarded – undo
530 530
 	}
531 531
 
532 532
 	/* Make sure they passed at least one param */
533
-	if(count($recieved) != 0)
533
+	if (count($recieved) != 0)
534 534
 	{
535 535
 		/* if used as standard function we loop thru and set by position */
536
-		if(!is_array($recieved[0]))
536
+		if (!is_array($recieved[0]))
537 537
 		{
538 538
 		for ($i = 0; $i < $num; $i++)
539 539
 			{
540
-				if(isset($recieved[$i]) && $recieved[$i] !== '##DEFAULT##')
540
+				if (isset($recieved[$i]) && $recieved[$i] !== '##DEFAULT##')
541 541
 				{
542
-					if(sanitize($recieved[$i],$expected[$i]['type']))
542
+					if (sanitize($recieved[$i], $expected[$i]['type']))
543 543
 					{
544 544
 						$args[$expected[$i]['name']] = $recieved[$i];
545 545
 						unset($required[$expected[$i]['name']]);
@@ -559,11 +559,11 @@  discard block
 block discarded – undo
559 559
 			{
560 560
 				$types[$expected[$i]['name']] = $expected[$i]['type'];
561 561
 			}
562
-			while(list($key,$val) = each($recieved[0]))
562
+			while (list($key, $val) = each($recieved[0]))
563 563
 			{
564
-				if($val !== '##DEFAULT##')
564
+				if ($val !== '##DEFAULT##')
565 565
 				{
566
-					if(sanitize($val,$types[$key]) == True)
566
+					if (sanitize($val, $types[$key]) == True)
567 567
 					{
568 568
 						$args[$key] = $val;
569 569
 						unset($required[$key]);
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
 			}
578 578
 		}
579 579
 	}
580
-	if(count($required) != 0)
580
+	if (count($required) != 0)
581 581
 	{
582 582
 		while (list($key) = each($required))
583 583
 		{
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
  * This function is used to validate input data.
596 596
  * sanitize('number',$somestring);
597 597
  */
598
-function sanitize($string,$type)
598
+function sanitize($string, $type)
599 599
 {
600 600
 	switch ($type)
601 601
 	{
@@ -647,10 +647,10 @@  discard block
 block discarded – undo
647 647
 			}
648 648
 			break;
649 649
 		case 'ip':
650
-			if (preg_match('/'."^[0-9]{1,3}(\.[0-9]{1,3}){3}$".'/i',$string))
650
+			if (preg_match('/'."^[0-9]{1,3}(\.[0-9]{1,3}){3}$".'/i', $string))
651 651
 			{
652
-				$octets = preg_split('/\./',$string);
653
-				for ($i=0; $i != count($octets); $i++)
652
+				$octets = preg_split('/\./', $string);
653
+				for ($i = 0; $i != count($octets); $i++)
654 654
 				{
655 655
 					if ($octets[$i] < 0 || $octets[$i] > 255)
656 656
 					{
@@ -668,17 +668,17 @@  discard block
 block discarded – undo
668 668
 			}
669 669
 			break;
670 670
 		case 'email':
671
-			if (preg_match('/'."^([[:alnum:]_%+=.-]+)@([[:alnum:]_.-]+)\.([a-z]{2,3}|[0-9]{1,3})$".'/i',$string))
671
+			if (preg_match('/'."^([[:alnum:]_%+=.-]+)@([[:alnum:]_.-]+)\.([a-z]{2,3}|[0-9]{1,3})$".'/i', $string))
672 672
 			{
673 673
 				return True;
674 674
 			}
675 675
 			break;
676 676
 		case 'password':
677 677
 			$password_length = strlen($string);
678
-			$password_numbers = Array('0','1','2','3','4','5','6','7','8','9');
679
-			$password_special_chars = Array(' ','~','`','!','@','#','$','%','^','&','*','(',')','_','+','-','=','{','}','|','[',']',"\\",':','"',';',"'",'<','>','?',',','.','/');
678
+			$password_numbers = Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
679
+			$password_special_chars = Array(' ', '~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '-', '=', '{', '}', '|', '[', ']', "\\", ':', '"', ';', "'", '<', '>', '?', ',', '.', '/');
680 680
 
681
-			if(@isset($GLOBALS['egw_info']['server']['pass_min_length']) && is_int($GLOBALS['egw_info']['server']['pass_min_length']) && $GLOBALS['egw_info']['server']['pass_min_length'] > 1)
681
+			if (@isset($GLOBALS['egw_info']['server']['pass_min_length']) && is_int($GLOBALS['egw_info']['server']['pass_min_length']) && $GLOBALS['egw_info']['server']['pass_min_length'] > 1)
682 682
 			{
683 683
 				$min_length = $GLOBALS['egw_info']['server']['pass_min_length'];
684 684
 			}
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
 				$min_length = 1;
688 688
 			}
689 689
 
690
-			if(@isset($GLOBALS['egw_info']['server']['pass_require_non_alpha']) && $GLOBALS['egw_info']['server']['pass_require_non_alpha'] == True)
690
+			if (@isset($GLOBALS['egw_info']['server']['pass_require_non_alpha']) && $GLOBALS['egw_info']['server']['pass_require_non_alpha'] == True)
691 691
 			{
692 692
 				$pass_verify_non_alpha = False;
693 693
 			}
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
 				$pass_verify_non_alpha = True;
697 697
 			}
698 698
 
699
-			if(@isset($GLOBALS['egw_info']['server']['pass_require_numbers']) && $GLOBALS['egw_info']['server']['pass_require_numbers'] == True)
699
+			if (@isset($GLOBALS['egw_info']['server']['pass_require_numbers']) && $GLOBALS['egw_info']['server']['pass_require_numbers'] == True)
700 700
 			{
701 701
 				$pass_verify_num = False;
702 702
 			}
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
 				$pass_verify_num = True;
706 706
 			}
707 707
 
708
-			if(@isset($GLOBALS['egw_info']['server']['pass_require_special_char']) && $GLOBALS['egw_info']['server']['pass_require_special_char'] == True)
708
+			if (@isset($GLOBALS['egw_info']['server']['pass_require_special_char']) && $GLOBALS['egw_info']['server']['pass_require_special_char'] == True)
709 709
 			{
710 710
 				$pass_verify_special_char = False;
711 711
 			}
@@ -716,7 +716,7 @@  discard block
 block discarded – undo
716 716
 
717 717
 			if ($password_length >= $min_length)
718 718
 			{
719
-				for ($i=0; $i != $password_length; $i++)
719
+				for ($i = 0; $i != $password_length; $i++)
720 720
 				{
721 721
 					$cur_test_string = substr($string, $i, 1);
722 722
 					if (in_array($cur_test_string, $password_numbers) || in_array($cur_test_string, $password_special_chars))
@@ -735,17 +735,17 @@  discard block
 block discarded – undo
735 735
 
736 736
 				if ($pass_verify_num == False)
737 737
 				{
738
-					$GLOBALS['egw_info']['flags']['msgbox_data']['Password requires at least one non-alpha character']=False;
738
+					$GLOBALS['egw_info']['flags']['msgbox_data']['Password requires at least one non-alpha character'] = False;
739 739
 				}
740 740
 
741 741
 				if ($pass_verify_num == False)
742 742
 				{
743
-					$GLOBALS['egw_info']['flags']['msgbox_data']['Password requires at least one numeric character']=False;
743
+					$GLOBALS['egw_info']['flags']['msgbox_data']['Password requires at least one numeric character'] = False;
744 744
 				}
745 745
 
746 746
 				if ($pass_verify_special_char == False)
747 747
 				{
748
-					$GLOBALS['egw_info']['flags']['msgbox_data']['Password requires at least one special character (non-letter and non-number)']=False;
748
+					$GLOBALS['egw_info']['flags']['msgbox_data']['Password requires at least one special character (non-letter and non-number)'] = False;
749 749
 				}
750 750
 
751 751
 				if ($pass_verify_num == True && $pass_verify_special_char == True)
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
 				}
755 755
 				return False;
756 756
 			}
757
-			$GLOBALS['egw_info']['flags']['msgbox_data']['Password must be at least '.$min_length.' characters']=False;
757
+			$GLOBALS['egw_info']['flags']['msgbox_data']['Password must be at least '.$min_length.' characters'] = False;
758 758
 			return False;
759 759
 
760 760
 		case 'any':
@@ -772,40 +772,40 @@  discard block
 block discarded – undo
772 772
 	}
773 773
 }
774 774
 
775
-function reg_var($varname, $method='any', $valuetype='alphanumeric',$default_value='',$register=True)
775
+function reg_var($varname, $method = 'any', $valuetype = 'alphanumeric', $default_value = '', $register = True)
776 776
 {
777
-	if($method == 'any' || $method == array('any'))
777
+	if ($method == 'any' || $method == array('any'))
778 778
 	{
779
-		$method = Array('POST','GET','COOKIE','SERVER','FILES','GLOBAL','DEFAULT');
779
+		$method = Array('POST', 'GET', 'COOKIE', 'SERVER', 'FILES', 'GLOBAL', 'DEFAULT');
780 780
 	}
781
-	elseif(!is_array($method))
781
+	elseif (!is_array($method))
782 782
 	{
783 783
 		$method = Array($method);
784 784
 	}
785 785
 	$cnt = count($method);
786
-	for($i=0;$i<$cnt;$i++)
786
+	for ($i = 0; $i < $cnt; $i++)
787 787
 	{
788
-		switch(strtoupper($method[$i]))
788
+		switch (strtoupper($method[$i]))
789 789
 		{
790 790
 			case 'DEFAULT':
791
-				if($default_value)
791
+				if ($default_value)
792 792
 				{
793 793
 					$value = $default_value;
794
-					$i = $cnt+1; /* Found what we were looking for, now we end the loop */
794
+					$i = $cnt + 1; /* Found what we were looking for, now we end the loop */
795 795
 				}
796 796
 				break;
797 797
 			case 'GLOBAL':
798
-				if(@isset($GLOBALS[$varname]))
798
+				if (@isset($GLOBALS[$varname]))
799 799
 				{
800 800
 					$value = $GLOBALS[$varname];
801
-					$i = $cnt+1;
801
+					$i = $cnt + 1;
802 802
 				}
803 803
 				break;
804 804
 			case 'POST':
805 805
 			case 'GET':
806 806
 			case 'COOKIE':
807 807
 			case 'SERVER':
808
-				if(phpversion() >= '4.1.0')
808
+				if (phpversion() >= '4.1.0')
809 809
 				{
810 810
 					$meth = '_'.strtoupper($method[$i]);
811 811
 				}
@@ -813,30 +813,30 @@  discard block
 block discarded – undo
813 813
 				{
814 814
 					$meth = 'HTTP_'.strtoupper($method[$i]).'_VARS';
815 815
 				}
816
-				if(@isset($GLOBALS[$meth][$varname]))
816
+				if (@isset($GLOBALS[$meth][$varname]))
817 817
 				{
818 818
 					$value = $GLOBALS[$meth][$varname];
819
-					$i = $cnt+1;
819
+					$i = $cnt + 1;
820 820
 				}
821
-				if(get_magic_quotes_gpc() && isset($value))
821
+				if (get_magic_quotes_gpc() && isset($value))
822 822
 				{
823 823
 					// we need to stripslash 3 levels of arrays
824 824
 					// because of the password function in preferences
825 825
 					// it's named ['user']['variablename']['pw']
826 826
 					// or something like this in projects
827 827
 					// $values['budgetBegin']['1']['year']
828
-					if(@is_array($value))
828
+					if (@is_array($value))
829 829
 					{
830 830
 						/* stripslashes on the first level of array values */
831
-						foreach($value as $name => $val)
831
+						foreach ($value as $name => $val)
832 832
 						{
833
-							if(@is_array($val))
833
+							if (@is_array($val))
834 834
 							{
835
-								foreach($val as $name2 => $val2)
835
+								foreach ($val as $name2 => $val2)
836 836
 								{
837
-									if(@is_array($val2))
837
+									if (@is_array($val2))
838 838
 									{
839
-										foreach($val2 as $name3 => $val3)
839
+										foreach ($val2 as $name3 => $val3)
840 840
 										{
841 841
 											$value[$name][$name2][$name3] = stripslashes($val3);
842 842
 										}
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
 				}
862 862
 				break;
863 863
 			case 'FILES':
864
-				if(phpversion() >= '4.1.0')
864
+				if (phpversion() >= '4.1.0')
865 865
 				{
866 866
 					$meth = '_FILES';
867 867
 				}
@@ -869,17 +869,17 @@  discard block
 block discarded – undo
869 869
 				{
870 870
 					$meth = 'HTTP_POST_FILES';
871 871
 				}
872
-				if(@isset($GLOBALS[$meth][$varname]))
872
+				if (@isset($GLOBALS[$meth][$varname]))
873 873
 				{
874 874
 					$value = $GLOBALS[$meth][$varname];
875
-					$i = $cnt+1;
875
+					$i = $cnt + 1;
876 876
 				}
877 877
 				break;
878 878
 			default:
879
-				if(@isset($GLOBALS[strtoupper($method[$i])][$varname]))
879
+				if (@isset($GLOBALS[strtoupper($method[$i])][$varname]))
880 880
 				{
881 881
 					$value = $GLOBALS[strtoupper($method[$i])][$varname];
882
-					$i = $cnt+1;
882
+					$i = $cnt + 1;
883 883
 				}
884 884
 				break;
885 885
 		}
@@ -898,7 +898,7 @@  discard block
 block discarded – undo
898 898
 		}
899 899
 		else
900 900
 		{
901
-			if (sanitize($value,$valuetype) == 1)
901
+			if (sanitize($value, $valuetype) == 1)
902 902
 			{
903 903
 				$result = $value;
904 904
 			}
@@ -911,7 +911,7 @@  discard block
 block discarded – undo
911 911
 	else
912 912
 	{
913 913
 		reset($value);
914
-		while(list($k, $v) = each($value))
914
+		while (list($k, $v) = each($value))
915 915
 		{
916 916
 			if ($v == '')
917 917
 			{
@@ -928,7 +928,7 @@  discard block
 block discarded – undo
928 928
 					$vt = $valuetype;
929 929
 				}
930 930
 
931
-				if (sanitize($v,$vt) == 1)
931
+				if (sanitize($v, $vt) == 1)
932 932
 				{
933 933
 					$result[$k] = $v;
934 934
 				}
@@ -946,7 +946,7 @@  discard block
 block discarded – undo
946 946
 			}
947 947
 		}
948 948
 	}
949
-	if($register)
949
+	if ($register)
950 950
 	{
951 951
 		$GLOBALS['egw_info'][$GLOBALS['egw_info']['flags']['currentapp']][$varname] = $result;
952 952
 	}
@@ -963,13 +963,13 @@  discard block
 block discarded – undo
963 963
  * @param $method ordered array of methods to search for supplied variable
964 964
  * @param $default_value (optional)
965 965
  */
966
-function get_var($variable,$method='any',$default_value='')
966
+function get_var($variable, $method = 'any', $default_value = '')
967 967
 {
968
-	if(!@is_array($method))
968
+	if (!@is_array($method))
969 969
 	{
970 970
 		$method = array($method);
971 971
 	}
972
-	return reg_var($variable,$method,'any',$default_value,False);
972
+	return reg_var($variable, $method, 'any', $default_value, False);
973 973
 }
974 974
 
975 975
 /**
@@ -985,7 +985,7 @@  discard block
 block discarded – undo
985 985
  */
986 986
 function &CreateObject($class)
987 987
 {
988
-	list($appname,$classname) = explode('.',$class);
988
+	list($appname, $classname) = explode('.', $class);
989 989
 
990 990
 	if (!class_exists($classname))
991 991
 	{
@@ -1011,7 +1011,7 @@  discard block
 block discarded – undo
1011 1011
 				$classname = $replace[$classname];
1012 1012
 			}
1013 1013
 		}
1014
-		if (!file_exists($f=EGW_INCLUDE_ROOT.'/'.$appname.'/inc/class.'.$classname.'.inc.php'))
1014
+		if (!file_exists($f = EGW_INCLUDE_ROOT.'/'.$appname.'/inc/class.'.$classname.'.inc.php'))
1015 1015
 		{
1016 1016
 			throw new egw_exception_assertion_failed(__FUNCTION__."($classname) file $f not found!");
1017 1017
 		}
@@ -1019,7 +1019,7 @@  discard block
 block discarded – undo
1019 1019
 		require_once(EGW_INCLUDE_ROOT.'/'.$appname.'/inc/class.'.$classname.'.inc.php');
1020 1020
 	}
1021 1021
 	$args = func_get_args();
1022
-	switch(count($args))
1022
+	switch (count($args))
1023 1023
 	{
1024 1024
 		case 1:
1025 1025
 			$obj = new $classname;
@@ -1028,18 +1028,18 @@  discard block
 block discarded – undo
1028 1028
 			$obj = new $classname($args[1]);
1029 1029
 			break;
1030 1030
 		case 3:
1031
-			$obj = new $classname($args[1],$args[2]);
1031
+			$obj = new $classname($args[1], $args[2]);
1032 1032
 			break;
1033 1033
 		case 4:
1034
-			$obj = new $classname($args[1],$args[2],$args[3]);
1034
+			$obj = new $classname($args[1], $args[2], $args[3]);
1035 1035
 			break;
1036 1036
 		default:
1037
-			$code = '$obj = new ' . $classname . '(';
1038
-			foreach(array_keys($args) as $n)
1037
+			$code = '$obj = new '.$classname.'(';
1038
+			foreach (array_keys($args) as $n)
1039 1039
 			{
1040 1040
 				if ($n)
1041 1041
 				{
1042
-					$code .= ($n > 1 ? ',' : '') . '$args[' . $n . ']';
1042
+					$code .= ($n > 1 ? ',' : '').'$args['.$n.']';
1043 1043
 				}
1044 1044
 			}
1045 1045
 			$code .= ');';
@@ -1064,30 +1064,30 @@  discard block
 block discarded – undo
1064 1064
 function &ExecMethod2($acm)
1065 1065
 {
1066 1066
 	// class::method is php5.2.3+
1067
-	if (strpos($acm,'::') !== false && version_compare(PHP_VERSION,'5.2.3','<'))
1067
+	if (strpos($acm, '::') !== false && version_compare(PHP_VERSION, '5.2.3', '<'))
1068 1068
 	{
1069
-		list($class,$method) = explode('::',$acm);
1070
-		$acm = array($class,$method);
1069
+		list($class, $method) = explode('::', $acm);
1070
+		$acm = array($class, $method);
1071 1071
 	}
1072 1072
 	if (!is_callable($acm))
1073 1073
 	{
1074
-		list(,$class,$method) = explode('.',$acm);
1075
-		if (!is_object($obj =& $GLOBALS[$class]))
1074
+		list(,$class, $method) = explode('.', $acm);
1075
+		if (!is_object($obj = & $GLOBALS[$class]))
1076 1076
 		{
1077
-			$obj =& CreateObject($acm);
1077
+			$obj = & CreateObject($acm);
1078 1078
 		}
1079 1079
 
1080
-		if (!method_exists($obj,$method))
1080
+		if (!method_exists($obj, $method))
1081 1081
 		{
1082 1082
 			echo "<p><b>".function_backtrace()."</b>: no methode '$method' in class '$class'</p>\n";
1083 1083
 			return False;
1084 1084
 		}
1085
-		$acm = array($obj,$method);
1085
+		$acm = array($obj, $method);
1086 1086
 	}
1087 1087
 	$args = func_get_args();
1088 1088
 	unset($args[0]);
1089 1089
 
1090
-	return call_user_func_array($acm,$args);
1090
+	return call_user_func_array($acm, $args);
1091 1091
 }
1092 1092
 
1093 1093
 /**
@@ -1104,13 +1104,13 @@  discard block
 block discarded – undo
1104 1104
  */
1105 1105
 function ExecMethod($method, $functionparam = '_UNDEF_', $loglevel = 3, $classparams = '_UNDEF_')
1106 1106
 {
1107
-	unset($loglevel);	// not used
1107
+	unset($loglevel); // not used
1108 1108
 	/* Need to make sure this is working against a single dimensional object */
1109
-	$partscount = count(explode('.',$method)) - 1;
1109
+	$partscount = count(explode('.', $method)) - 1;
1110 1110
 
1111 1111
 	if (!is_callable($method) && $partscount == 2)
1112 1112
 	{
1113
-		list($appname,$classname,$functionname) = explode(".", $method);
1113
+		list($appname, $classname, $functionname) = explode(".", $method);
1114 1114
 		if (!is_object($GLOBALS[$classname]))
1115 1115
 		{
1116 1116
 			// please note: no reference assignment (=&) here, as $GLOBALS is a reference itself!!!
@@ -1124,16 +1124,16 @@  discard block
 block discarded – undo
1124 1124
 			}
1125 1125
 		}
1126 1126
 
1127
-		if (!method_exists($GLOBALS[$classname],$functionname))
1127
+		if (!method_exists($GLOBALS[$classname], $functionname))
1128 1128
 		{
1129 1129
 			error_log("ExecMethod('$method', ...) No methode '$functionname' in class '$classname'! ".function_backtrace());
1130 1130
 			return false;
1131 1131
 		}
1132
-		$method = array($GLOBALS[$classname],$functionname);
1132
+		$method = array($GLOBALS[$classname], $functionname);
1133 1133
 	}
1134 1134
 	if (is_callable($method))
1135 1135
 	{
1136
-		return $functionparam != '_UNDEF_' ? call_user_func($method,$functionparam) : call_user_func($method);
1136
+		return $functionparam != '_UNDEF_' ? call_user_func($method, $functionparam) : call_user_func($method);
1137 1137
 	}
1138 1138
 	error_log("ExecMethod('$method', ...) Error in parts! ".function_backtrace());
1139 1139
 	return false;
@@ -1149,7 +1149,7 @@  discard block
 block discarded – undo
1149 1149
  * @param int/string $default_id either a name or an id
1150 1150
  * @return int account_id
1151 1151
  */
1152
-function get_account_id($account_id = '',$default_id = '')
1152
+function get_account_id($account_id = '', $default_id = '')
1153 1153
 {
1154 1154
 	if (gettype($account_id) == 'integer')
1155 1155
 	{
@@ -1159,7 +1159,7 @@  discard block
 block discarded – undo
1159 1159
 	{
1160 1160
 		if ($default_id == '')
1161 1161
 		{
1162
-			return (isset($GLOBALS['egw_info']['user']['account_id'])?$GLOBALS['egw_info']['user']['account_id']:0);
1162
+			return (isset($GLOBALS['egw_info']['user']['account_id']) ? $GLOBALS['egw_info']['user']['account_id'] : 0);
1163 1163
 		}
1164 1164
 		elseif (is_string($default_id))
1165 1165
 		{
@@ -1169,7 +1169,7 @@  discard block
 block discarded – undo
1169 1169
 	}
1170 1170
 	elseif (is_string($account_id))
1171 1171
 	{
1172
-		if($GLOBALS['egw']->accounts->exists((int)$account_id) == True)
1172
+		if ($GLOBALS['egw']->accounts->exists((int)$account_id) == True)
1173 1173
 		{
1174 1174
 			return (int)$account_id;
1175 1175
 		}
@@ -1190,7 +1190,7 @@  discard block
 block discarded – undo
1190 1190
  */
1191 1191
 function filesystem_separator()
1192 1192
 {
1193
-	if(PHP_OS == 'Windows' || PHP_OS == 'OS/2' || PHP_OS == 'WINNT')
1193
+	if (PHP_OS == 'Windows' || PHP_OS == 'OS/2' || PHP_OS == 'WINNT')
1194 1194
 	{
1195 1195
 		return '\\';
1196 1196
 	}
@@ -1212,9 +1212,9 @@  discard block
 block discarded – undo
1212 1212
  * @param boolean $print =true print or return the content
1213 1213
  * @return string if !$print
1214 1214
  */
1215
-function _debug_array($array,$print=True)
1215
+function _debug_array($array, $print = True)
1216 1216
 {
1217
-	$output = '<pre>'.print_r($array,true)."</pre>\n";
1217
+	$output = '<pre>'.print_r($array, true)."</pre>\n";
1218 1218
 
1219 1219
 	if ($print)
1220 1220
 	{
@@ -1233,44 +1233,44 @@  discard block
 block discarded – undo
1233 1233
  * @param string $b egw version number to check $a against
1234 1234
  * @return boolean True if $a < $b
1235 1235
  */
1236
-function alessthanb($a,$b,$DEBUG=False)
1236
+function alessthanb($a, $b, $DEBUG = False)
1237 1237
 {
1238
-	$num = array('1st','2nd','3rd','4th');
1238
+	$num = array('1st', '2nd', '3rd', '4th');
1239 1239
 
1240 1240
 	if ($DEBUG)
1241 1241
 	{
1242
-		echo'<br>Input values: ' . 'A="'.$a.'", B="'.$b.'"';
1242
+		echo'<br>Input values: '.'A="'.$a.'", B="'.$b.'"';
1243 1243
 	}
1244
-	$newa = str_replace('pre','.',$a);
1245
-	$newb = str_replace('pre','.',$b);
1246
-	$testa = explode('.',$newa);
1247
-	if(@$testa[1] == '')
1244
+	$newa = str_replace('pre', '.', $a);
1245
+	$newb = str_replace('pre', '.', $b);
1246
+	$testa = explode('.', $newa);
1247
+	if (@$testa[1] == '')
1248 1248
 	{
1249 1249
 		$testa[1] = 0;
1250 1250
 	}
1251
-	if(@$testa[3] == '')
1251
+	if (@$testa[3] == '')
1252 1252
 	{
1253 1253
 		$testa[3] = 0;
1254 1254
 	}
1255
-	$testb = explode('.',$newb);
1256
-	if(@$testb[1] == '')
1255
+	$testb = explode('.', $newb);
1256
+	if (@$testb[1] == '')
1257 1257
 	{
1258 1258
 		$testb[1] = 0;
1259 1259
 	}
1260
-	if(@$testb[3] == '')
1260
+	if (@$testb[3] == '')
1261 1261
 	{
1262 1262
 		$testb[3] = 0;
1263 1263
 	}
1264 1264
 	$less = 0;
1265 1265
 
1266
-	for ($i=0;$i<count($testa);$i++)
1266
+	for ($i = 0; $i < count($testa); $i++)
1267 1267
 	{
1268
-		if ($DEBUG) { echo'<br>Checking if '. (int)$testa[$i] . ' is less than ' . (int)$testb[$i] . ' ...'; }
1268
+		if ($DEBUG) { echo'<br>Checking if '.(int)$testa[$i].' is less than '.(int)$testb[$i].' ...'; }
1269 1269
 		if ((int)$testa[$i] < (int)$testb[$i])
1270 1270
 		{
1271 1271
 			if ($DEBUG) { echo ' yes.'; }
1272 1272
 			$less++;
1273
-			if ($i<3)
1273
+			if ($i < 3)
1274 1274
 			{
1275 1275
 				/* Ensure that this is definitely smaller */
1276 1276
 				if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely less than B."; }
@@ -1278,11 +1278,11 @@  discard block
 block discarded – undo
1278 1278
 				break;
1279 1279
 			}
1280 1280
 		}
1281
-		elseif((int)$testa[$i] > (int)$testb[$i])
1281
+		elseif ((int)$testa[$i] > (int)$testb[$i])
1282 1282
 		{
1283 1283
 			if ($DEBUG) { echo ' no.'; }
1284 1284
 			$less--;
1285
-			if ($i<2)
1285
+			if ($i < 2)
1286 1286
 			{
1287 1287
 				/* Ensure that this is definitely greater */
1288 1288
 				if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely greater than B."; }
@@ -1297,12 +1297,12 @@  discard block
 block discarded – undo
1297 1297
 		}
1298 1298
 	}
1299 1299
 	if ($DEBUG) { echo '<br>Check value is: "'.$less.'"'; }
1300
-	if ($less>0)
1300
+	if ($less > 0)
1301 1301
 	{
1302 1302
 		if ($DEBUG) { echo '<br>A is less than B'; }
1303 1303
 		return True;
1304 1304
 	}
1305
-	elseif($less<0)
1305
+	elseif ($less < 0)
1306 1306
 	{
1307 1307
 		if ($DEBUG) { echo '<br>A is greater than B'; }
1308 1308
 		return False;
@@ -1321,36 +1321,36 @@  discard block
 block discarded – undo
1321 1321
  * @param string $b eGW version number to check check $a against
1322 1322
  * @return boolean True if $a > $b
1323 1323
  */
1324
-function amorethanb($a,$b,$DEBUG=False)
1324
+function amorethanb($a, $b, $DEBUG = False)
1325 1325
 {
1326
-	$num = array('1st','2nd','3rd','4th');
1326
+	$num = array('1st', '2nd', '3rd', '4th');
1327 1327
 
1328 1328
 	if ($DEBUG)
1329 1329
 	{
1330
-		echo'<br>Input values: ' . 'A="'.$a.'", B="'.$b.'"';
1330
+		echo'<br>Input values: '.'A="'.$a.'", B="'.$b.'"';
1331 1331
 	}
1332
-	$newa = str_replace('pre','.',$a);
1333
-	$newb = str_replace('pre','.',$b);
1334
-	$testa = explode('.',$newa);
1335
-	if($testa[3] == '')
1332
+	$newa = str_replace('pre', '.', $a);
1333
+	$newb = str_replace('pre', '.', $b);
1334
+	$testa = explode('.', $newa);
1335
+	if ($testa[3] == '')
1336 1336
 	{
1337 1337
 		$testa[3] = 0;
1338 1338
 	}
1339
-	$testb = explode('.',$newb);
1340
-	if($testb[3] == '')
1339
+	$testb = explode('.', $newb);
1340
+	if ($testb[3] == '')
1341 1341
 	{
1342 1342
 		$testb[3] = 0;
1343 1343
 	}
1344 1344
 	$less = 0;
1345 1345
 
1346
-	for ($i=0;$i<count($testa);$i++)
1346
+	for ($i = 0; $i < count($testa); $i++)
1347 1347
 	{
1348
-		if ($DEBUG) { echo'<br>Checking if '. (int)$testa[$i] . ' is more than ' . (int)$testb[$i] . ' ...'; }
1348
+		if ($DEBUG) { echo'<br>Checking if '.(int)$testa[$i].' is more than '.(int)$testb[$i].' ...'; }
1349 1349
 		if ((int)$testa[$i] > (int)$testb[$i])
1350 1350
 		{
1351 1351
 			if ($DEBUG) { echo ' yes.'; }
1352 1352
 			$less++;
1353
-			if ($i<3)
1353
+			if ($i < 3)
1354 1354
 			{
1355 1355
 				/* Ensure that this is definitely greater */
1356 1356
 				if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely greater than B."; }
@@ -1358,11 +1358,11 @@  discard block
 block discarded – undo
1358 1358
 				break;
1359 1359
 			}
1360 1360
 		}
1361
-		elseif((int)$testa[$i] < (int)$testb[$i])
1361
+		elseif ((int)$testa[$i] < (int)$testb[$i])
1362 1362
 		{
1363 1363
 			if ($DEBUG) { echo ' no.'; }
1364 1364
 			$less--;
1365
-			if ($i<2)
1365
+			if ($i < 2)
1366 1366
 			{
1367 1367
 				/* Ensure that this is definitely smaller */
1368 1368
 				if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely less than B."; }
@@ -1377,12 +1377,12 @@  discard block
 block discarded – undo
1377 1377
 		}
1378 1378
 	}
1379 1379
 	if ($DEBUG) { echo '<br>Check value is: "'.$less.'"'; }
1380
-	if ($less>0)
1380
+	if ($less > 0)
1381 1381
 	{
1382 1382
 		if ($DEBUG) { echo '<br>A is greater than B'; }
1383 1383
 		return True;
1384 1384
 	}
1385
-	elseif($less<0)
1385
+	elseif ($less < 0)
1386 1386
 	{
1387 1387
 		if ($DEBUG) { echo '<br>A is less than B'; }
1388 1388
 		return False;
@@ -1402,9 +1402,9 @@  discard block
 block discarded – undo
1402 1402
  * @param	$tables	and array of tables to have the prefix prepended to
1403 1403
  * @return array of table names with the prefix prepended
1404 1404
  */
1405
-function prepend_tables_prefix($prefix,$tables)
1405
+function prepend_tables_prefix($prefix, $tables)
1406 1406
 {
1407
-	foreach($tables as $key => $value)
1407
+	foreach ($tables as $key => $value)
1408 1408
 	{
1409 1409
 		$tables[$key] = $prefix.$value;
1410 1410
 	}
@@ -1418,28 +1418,28 @@  discard block
 block discarded – undo
1418 1418
  * @param int $remove =0 number of levels to remove
1419 1419
  * @return string function-names separated by slashes (beginning with the calling function not this one)
1420 1420
  */
1421
-function function_backtrace($remove=0)
1421
+function function_backtrace($remove = 0)
1422 1422
 {
1423 1423
 	if (function_exists('debug_backtrace'))
1424 1424
 	{
1425 1425
 		$backtrace = debug_backtrace();
1426 1426
 		//echo "function_backtrace($remove)<pre>".print_r($backtrace,True)."</pre>\n";
1427
-		foreach($backtrace as $n => $level)
1427
+		foreach ($backtrace as $n => $level)
1428 1428
 		{
1429 1429
 			if ($remove-- < 0)
1430 1430
 			{
1431
-				$ret[] = (isset($level['class'])?$level['class'].$level['type']:'').$level['function'].
1432
-					($n > 0 && isset($backtrace[$n-1]['line']) ? ':'.$backtrace[$n-1]['line'] : '').	// add line number of call
1431
+				$ret[] = (isset($level['class']) ? $level['class'].$level['type'] : '').$level['function'].
1432
+					($n > 0 && isset($backtrace[$n - 1]['line']) ? ':'.$backtrace[$n - 1]['line'] : '').// add line number of call
1433 1433
 					(!$level['class'] && !is_object($level['args'][0]) && $level['function'] != 'unserialize' ?
1434
-					'('.substr(str_replace(EGW_SERVER_ROOT,'',(string)$level['args'][0]),0,64).')' : '');
1434
+					'('.substr(str_replace(EGW_SERVER_ROOT, '', (string)$level['args'][0]), 0, 64).')' : '');
1435 1435
 			}
1436 1436
 		}
1437 1437
 		if (is_array($ret))
1438 1438
 		{
1439
-			return implode(' / ',$ret);
1439
+			return implode(' / ', $ret);
1440 1440
 		}
1441 1441
 	}
1442
-	return $_GET['menuaction'] ? $_GET['menuaction'] : str_replace(EGW_SERVER_ROOT,'',$_SERVER['SCRIPT_FILENAME']);
1442
+	return $_GET['menuaction'] ? $_GET['menuaction'] : str_replace(EGW_SERVER_ROOT, '', $_SERVER['SCRIPT_FILENAME']);
1443 1443
 }
1444 1444
 
1445 1445
 /**
@@ -1449,9 +1449,9 @@  discard block
 block discarded – undo
1449 1449
  * @param array &$var reference of array to check
1450 1450
  * @param string $name ='' name of the array
1451 1451
  */
1452
-function _check_script_tag(&$var,$name='')
1452
+function _check_script_tag(&$var, $name = '')
1453 1453
 {
1454
-	static $preg=null;
1454
+	static $preg = null;
1455 1455
 	//old: '/<\/?[^>]*\b(iframe|script|javascript|on(before)?(abort|blur|change|click|dblclick|error|focus|keydown|keypress|keyup|load|mousedown|mousemove|mouseout|mouseover|mouseup|reset|select|submit|unload))\b[^>]*>/i';
1456 1456
 	if (!isset($preg)) $preg =
1457 1457
 		// forbidden tags like iframe or script
@@ -1464,15 +1464,15 @@  discard block
 block discarded – undo
1464 1464
 		'<[^>]+style\s*=\s*("|\')[^>]*(behavior\s*:\s*url|expression)\s*\()/i';
1465 1465
 	if (is_array($var))
1466 1466
 	{
1467
-		foreach($var as $key => $val)
1467
+		foreach ($var as $key => $val)
1468 1468
 		{
1469 1469
 			if (is_array($val))
1470 1470
 			{
1471
-				_check_script_tag($var[$key],$name.'['.$key.']');
1471
+				_check_script_tag($var[$key], $name.'['.$key.']');
1472 1472
 			}
1473
-			elseif(strpos($val, '<') !== false)	// speedup: ignore everything without <
1473
+			elseif (strpos($val, '<') !== false)	// speedup: ignore everything without <
1474 1474
 			{
1475
-				if (preg_match($preg,$val))
1475
+				if (preg_match($preg, $val))
1476 1476
 				{
1477 1477
 					// special handling for $_POST[json_data], to decend into it's decoded content, fixing json direct might break json syntax
1478 1478
 					if ($name == '_POST' && $key == 'json_data' && ($json_data = json_decode($val, true)))
@@ -1486,7 +1486,7 @@  discard block
 block discarded – undo
1486 1486
 					// attempt to clean the thing
1487 1487
 					$var[$key] = $val = html::purify($val);
1488 1488
 					// check if we succeeded, if not drop the var anyway, keep the egw_unset_var in any case
1489
-					if (preg_match($preg,$val))
1489
+					if (preg_match($preg, $val))
1490 1490
 					{
1491 1491
 						error_log("*** _check_script_tag($name): unset(${name}[$key]) with value $val***");
1492 1492
 						unset($var[$key]);
@@ -1598,15 +1598,15 @@  discard block
 block discarded – undo
1598 1598
 	die("<p style='color: ".($num_failed?'red':'black')."'>Tests finished: $num_failed / $total failed</p>");
1599 1599
 }*/
1600 1600
 
1601
-foreach(array('_GET','_POST','_REQUEST','HTTP_GET_VARS','HTTP_POST_VARS') as $n => $where)
1601
+foreach (array('_GET', '_POST', '_REQUEST', 'HTTP_GET_VARS', 'HTTP_POST_VARS') as $n => $where)
1602 1602
 {
1603 1603
 	$pregs = array(
1604 1604
 		'order' => '/^[a-zA-Z0-9_,]*$/',
1605 1605
 		'sort'  => '/^(ASC|DESC|asc|desc|0|1|2|3|4|5|6|7){0,1}$/',
1606 1606
 	);
1607
-	foreach(array('order','sort') as $name)
1607
+	foreach (array('order', 'sort') as $name)
1608 1608
 	{
1609
-		if (isset($GLOBALS[$where][$name]) && !is_array($GLOBALS[$where][$name]) && !preg_match($pregs[$name],$GLOBALS[$where][$name]))
1609
+		if (isset($GLOBALS[$where][$name]) && !is_array($GLOBALS[$where][$name]) && !preg_match($pregs[$name], $GLOBALS[$where][$name]))
1610 1610
 		{
1611 1611
 			$GLOBALS[$where][$name] = '';
1612 1612
 		}
@@ -1615,14 +1615,14 @@  discard block
 block discarded – undo
1615 1615
 	// speeds up the execusion a bit
1616 1616
 	if (isset($GLOBALS[$where]) && is_array($GLOBALS[$where]) && ($n < 2 || isset($GLOBALS['egw_unset_vars'])))
1617 1617
 	{
1618
-		_check_script_tag($GLOBALS[$where],$where);
1618
+		_check_script_tag($GLOBALS[$where], $where);
1619 1619
 	}
1620 1620
 }
1621 1621
 //if (is_array($GLOBALS['egw_unset_vars'])) { echo "egw_unset_vars=<pre>".htmlspecialchars(print_r($GLOBALS['egw_unset_vars'],true))."</pre>"; exit; }
1622 1622
 
1623 1623
 // $GLOBALS[egw_info][flags][currentapp] and die  if it contains something nasty or unexpected
1624 1624
 if (isset($GLOBALS['egw_info']) && isset($GLOBALS['egw_info']['flags']) &&
1625
-	isset($GLOBALS['egw_info']['flags']['currentapp']) && !preg_match('/^[A-Za-z0-9_-]+$/',$GLOBALS['egw_info']['flags']['currentapp']))
1625
+	isset($GLOBALS['egw_info']['flags']['currentapp']) && !preg_match('/^[A-Za-z0-9_-]+$/', $GLOBALS['egw_info']['flags']['currentapp']))
1626 1626
 {
1627 1627
 	error_log(__FILE__.': '.__LINE__.' Invalid $GLOBALS[egw_info][flags][currentapp]='.array2string($GLOBALS['egw_info']['flags']['currentapp']).', $_SERVER[REQUEST_URI]='.array2string($_SERVER[REQUEST_URI]));
1628 1628
 	die('Invalid $GLOBALS[egw_info][flags][currentapp]!');
@@ -1640,12 +1640,12 @@  discard block
 block discarded – undo
1640 1640
 			die('GLOBALS overwrite detected!!!');
1641 1641
 		}
1642 1642
 		// unregister all globals
1643
-		$noUnset = array('GLOBALS','_GET','_POST','_COOKIE','_SERVER','_ENV','_FILES','xajax');
1644
-		foreach(array_unique(array_merge(
1645
-			array_keys($_GET),array_keys($_POST),array_keys($_COOKIE),array_keys($_SERVER),array_keys($_ENV),array_keys($_FILES),
1643
+		$noUnset = array('GLOBALS', '_GET', '_POST', '_COOKIE', '_SERVER', '_ENV', '_FILES', 'xajax');
1644
+		foreach (array_unique(array_merge(
1645
+			array_keys($_GET), array_keys($_POST), array_keys($_COOKIE), array_keys($_SERVER), array_keys($_ENV), array_keys($_FILES),
1646 1646
 			isset($_SESSION) && is_array($_SESSION) ? array_keys($_SESSION) : array())) as $k)
1647 1647
 		{
1648
-			if (!in_array($k,$noUnset) && isset($GLOBALS[$k]))
1648
+			if (!in_array($k, $noUnset) && isset($GLOBALS[$k]))
1649 1649
 			{
1650 1650
 				unset($GLOBALS[$k]);
1651 1651
 			}
@@ -1663,14 +1663,14 @@  discard block
 block discarded – undo
1663 1663
 	 * @param string $vars =null multiple values to replace the placeholders
1664 1664
 	 * @return string translated message with placeholders replaced
1665 1665
 	 */
1666
-	function lang($key,$vars=null)
1666
+	function lang($key, $vars = null)
1667 1667
 	{
1668
-		if(!is_array($vars))
1668
+		if (!is_array($vars))
1669 1669
 		{
1670 1670
 			$vars = func_get_args();
1671
-			array_shift($vars);	// remove $key
1671
+			array_shift($vars); // remove $key
1672 1672
 		}
1673
-		return translation::translate($key,$vars);
1673
+		return translation::translate($key, $vars);
1674 1674
 	}
1675 1675
 }
1676 1676
 
@@ -1684,16 +1684,16 @@  discard block
 block discarded – undo
1684 1684
  * @param string $vars =null multiple values to replace the placeholders
1685 1685
  * @return string translated message with placeholders replaced
1686 1686
  */
1687
-function try_lang($key,$vars=null)
1687
+function try_lang($key, $vars = null)
1688 1688
 {
1689
-	static $varnames = array('%1','%2','%3','%4');
1689
+	static $varnames = array('%1', '%2', '%3', '%4');
1690 1690
 
1691
-	if(!is_array($vars))
1691
+	if (!is_array($vars))
1692 1692
 	{
1693 1693
 		$vars = func_get_args();
1694
-		array_shift($vars);	// remove $key
1694
+		array_shift($vars); // remove $key
1695 1695
 	}
1696
-	return class_exists(translations,false) ? translation::translate($key,$vars) : str_replace($varnames,$vars,$key);
1696
+	return class_exists(translations, false) ? translation::translate($key, $vars) : str_replace($varnames, $vars, $key);
1697 1697
 }
1698 1698
 
1699 1699
 /**
@@ -1710,7 +1710,7 @@  discard block
 block discarded – undo
1710 1710
 		preg_match('/(^|;|{)[OC]:\d+:"/', $str))
1711 1711
 	{
1712 1712
 		error_log(__METHOD__."('$str') contains objects --> return false");
1713
-		return null;	// null, not false, to not trigger behavior of returning string itself to app code
1713
+		return null; // null, not false, to not trigger behavior of returning string itself to app code
1714 1714
 	}
1715 1715
 	return unserialize($str);
1716 1716
 }
@@ -1760,7 +1760,7 @@  discard block
 block discarded – undo
1760 1760
  * @param boolean $allow_not_serialized =false true: return $str as is, if it is no serialized array
1761 1761
  * @return array|str|false
1762 1762
  */
1763
-function json_php_unserialize($str, $allow_not_serialized=false)
1763
+function json_php_unserialize($str, $allow_not_serialized = false)
1764 1764
 {
1765 1765
 	if ((in_array($str[0], array('a', 'i', 's', 'b', 'O', 'C')) && $str[1] == ':' || $str === 'N;') &&
1766 1766
 		($arr = php_safe_unserialize($str)) !== false || $str === 'b:0;')
@@ -1780,7 +1780,7 @@  discard block
 block discarded – undo
1780 1780
  * @param Exception|Error $e
1781 1781
  * @param string &$headline
1782 1782
  */
1783
-function _egw_log_exception($e,&$headline=null)
1783
+function _egw_log_exception($e, &$headline = null)
1784 1784
 {
1785 1785
 	$trace = explode("\n", $e->getTraceAsString());
1786 1786
 	if ($e instanceof egw_exception_no_permission)
@@ -1793,7 +1793,7 @@  discard block
 block discarded – undo
1793 1793
 	}
1794 1794
 	elseif ($e instanceof egw_exception_wrong_userinput)
1795 1795
 	{
1796
-		$headline = '';	// message contains the whole message, it's usually no real error but some input validation
1796
+		$headline = ''; // message contains the whole message, it's usually no real error but some input validation
1797 1797
 	}
1798 1798
 	elseif ($e instanceof egw_exception_warning)
1799 1799
 	{
@@ -1806,15 +1806,15 @@  discard block
 block discarded – undo
1806 1806
 	}
1807 1807
 	// log exception to error log, if not running as cli,
1808 1808
 	// which outputs the error_log to stderr and therefore output it twice to the user
1809
-	if(isset($_SERVER['HTTP_HOST']) || $GLOBALS['egw_info']['flags']['no_exception_handler'] !== 'cli')
1809
+	if (isset($_SERVER['HTTP_HOST']) || $GLOBALS['egw_info']['flags']['no_exception_handler'] !== 'cli')
1810 1810
 	{
1811 1811
 		error_log($headline.($e instanceof egw_exception_warning ? ': ' : ' ('.get_class($e).'): ').$e->getMessage());
1812
-		foreach($trace as $line)
1812
+		foreach ($trace as $line)
1813 1813
 		{
1814 1814
 			error_log($line);
1815 1815
 		}
1816 1816
 		error_log('# Instance='.$GLOBALS['egw_info']['user']['domain'].', User='.$GLOBALS['egw_info']['user']['account_lid'].
1817
-			', Request='.$_SERVER['REQUEST_METHOD'].' '.($_SERVER['HTTPS']?'https://':'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].
1817
+			', Request='.$_SERVER['REQUEST_METHOD'].' '.($_SERVER['HTTPS'] ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].
1818 1818
 			', User-agent='.$_SERVER['HTTP_USER_AGENT']);
1819 1819
 	}
1820 1820
 }
@@ -1835,17 +1835,17 @@  discard block
 block discarded – undo
1835 1835
 	}
1836 1836
 	// logging all exceptions to the error_log (if not cli) and get headline
1837 1837
 	$headline = null;
1838
-	_egw_log_exception($e,$headline);
1838
+	_egw_log_exception($e, $headline);
1839 1839
 
1840 1840
 	// exception handler for cli (command line interface) clients, no html, no logging
1841
-	if(!isset($_SERVER['HTTP_HOST']) || $GLOBALS['egw_info']['flags']['no_exception_handler'] == 'cli')
1841
+	if (!isset($_SERVER['HTTP_HOST']) || $GLOBALS['egw_info']['flags']['no_exception_handler'] == 'cli')
1842 1842
 	{
1843 1843
 		echo ($headline ? $headline.': ' : '').$e->getMessage()."\n";
1844 1844
 		if ($GLOBALS['egw_info']['server']['exception_show_trace'])
1845 1845
 		{
1846 1846
 			echo $e->getTraceAsString()."\n";
1847 1847
 		}
1848
-		exit($e->getCode() ? $e->getCode() : 9999);		// allways give a non-zero exit code
1848
+		exit($e->getCode() ? $e->getCode() : 9999); // allways give a non-zero exit code
1849 1849
 	}
1850 1850
 	// regular GUI exception
1851 1851
 	if (!isset($GLOBALS['egw_info']['flags']['no_exception_handler']))
@@ -1862,16 +1862,16 @@  discard block
 block discarded – undo
1862 1862
 		$message .= "</pre>\n";
1863 1863
 		if (is_a($e, 'egw_exception_db_setup'))
1864 1864
 		{
1865
-			$setup_dir = str_replace(array('home/index.php','index.php'),'setup/',$_SERVER['PHP_SELF']);
1865
+			$setup_dir = str_replace(array('home/index.php', 'index.php'), 'setup/', $_SERVER['PHP_SELF']);
1866 1866
 			$message .= '<a href="'.$setup_dir.'">Run setup to install or configure EGroupware.</a>';
1867 1867
 		}
1868
-		elseif (is_object($GLOBALS['egw']) && isset($GLOBALS['egw']->session) && method_exists($GLOBALS['egw'],'link'))
1868
+		elseif (is_object($GLOBALS['egw']) && isset($GLOBALS['egw']->session) && method_exists($GLOBALS['egw'], 'link'))
1869 1869
 		{
1870 1870
 			$message .= '<p><a href="'.$GLOBALS['egw']->link('/index.php').'">'.try_lang('Click here to resume your eGroupWare Session.').'</a></p>';
1871 1871
 		}
1872 1872
 		if (is_object($GLOBALS['egw']) && isset($GLOBALS['egw']->framework))
1873 1873
 		{
1874
-			$GLOBALS['egw']->framework->render($message,$headline);
1874
+			$GLOBALS['egw']->framework->render($message, $headline);
1875 1875
 		}
1876 1876
 		else
1877 1877
 		{
@@ -1879,7 +1879,7 @@  discard block
 block discarded – undo
1879 1879
 		}
1880 1880
 	}
1881 1881
 	// exception handler sending message back to the client as basic auth message
1882
-	elseif($GLOBALS['egw_info']['flags']['no_exception_handler'] == 'basic_auth')
1882
+	elseif ($GLOBALS['egw_info']['flags']['no_exception_handler'] == 'basic_auth')
1883 1883
 	{
1884 1884
 		$error = str_replace(array("\r", "\n"), array('', ' | '), $e->getMessage());
1885 1885
 		header('WWW-Authenticate: Basic realm="'.$headline.' '.$error.'"');
@@ -1908,7 +1908,7 @@  discard block
 block discarded – undo
1908 1908
  * @link http://www.php.net/manual/en/function.set-error-handler.php
1909 1909
  * @throws ErrorException
1910 1910
  */
1911
-function egw_error_handler ($errno, $errstr, $errfile, $errline)
1911
+function egw_error_handler($errno, $errstr, $errfile, $errline)
1912 1912
 {
1913 1913
 	switch ($errno)
1914 1914
 	{
@@ -1940,13 +1940,13 @@  discard block
 block discarded – undo
1940 1940
 // some not longer necessary defines
1941 1941
 if (isset($GLOBALS['egw_info']['flags']['phpgw_compatibility']) && $GLOBALS['egw_info']['flags']['phpgw_compatibility'])
1942 1942
 {
1943
-	define('PHPGW_API_INC',EGW_API_INC);
1944
-	define('PHPGW_SERVER_ROOT',EGW_SERVER_ROOT);
1945
-	define('PHPGW_INCLUDE_ROOT',EGW_INCLUDE_ROOT);
1943
+	define('PHPGW_API_INC', EGW_API_INC);
1944
+	define('PHPGW_SERVER_ROOT', EGW_SERVER_ROOT);
1945
+	define('PHPGW_INCLUDE_ROOT', EGW_INCLUDE_ROOT);
1946 1946
 
1947 1947
 	/* debugging settings */
1948
-	define('DEBUG_DATATYPES',  True);
1949
-	define('DEBUG_LEVEL',  3);
1948
+	define('DEBUG_DATATYPES', True);
1949
+	define('DEBUG_LEVEL', 3);
1950 1950
 	define('DEBUG_OUTPUT', 2); /* 1 = screen,  2 = DB. For both use 3. */
1951 1951
 	define('DEBUG_TIMER', False);
1952 1952
 }
Please login to merge, or discard this patch.
Braces   +105 added lines, -32 removed lines patch added patch discarded remove patch
@@ -37,7 +37,11 @@  discard block
 block discarded – undo
37 37
 spl_autoload_register(function($class)
38 38
 {
39 39
 	$parts = explode('\\', $class);
40
-	if (array_shift($parts) != 'EGroupware') return;	// not our prefix
40
+	if (array_shift($parts) != 'EGroupware')
41
+	{
42
+		return;
43
+	}
44
+	// not our prefix
41 45
 
42 46
 	$app = lcfirst(array_shift($parts));
43 47
 	$base = EGW_INCLUDE_ROOT.'/'.$app.'/src/';
@@ -63,7 +67,10 @@  discard block
 block discarded – undo
63 67
 spl_autoload_register(function($class)
64 68
 {
65 69
 	// fixing warnings generated by php 5.3.8 is_a($obj) trying to autoload huge strings
66
-	if (strlen($class) > 64 || strpos($class, '.') !== false) return;
70
+	if (strlen($class) > 64 || strpos($class, '.') !== false)
71
+	{
72
+		return;
73
+	}
67 74
 
68 75
 	$components = explode('_',$class);
69 76
 	$app = array_shift($components);
@@ -133,7 +140,10 @@  discard block
 block discarded – undo
133 140
 {
134 141
 	static $func_overload = null;
135 142
 
136
-	if (is_null($func_overload)) $func_overload = extension_loaded('mbstring') ? ini_get('mbstring.func_overload') : 0;
143
+	if (is_null($func_overload))
144
+	{
145
+		$func_overload = extension_loaded('mbstring') ? ini_get('mbstring.func_overload') : 0;
146
+	}
137 147
 
138 148
 	return $func_overload & 2 ? mb_strlen($str,'ascii') : strlen($str);
139 149
 }
@@ -150,7 +160,10 @@  discard block
 block discarded – undo
150 160
 {
151 161
 	static $func_overload = null;
152 162
 
153
-	if (is_null($func_overload)) $func_overload = extension_loaded('mbstring') ? ini_get('mbstring.func_overload') : 0;
163
+	if (is_null($func_overload))
164
+	{
165
+		$func_overload = extension_loaded('mbstring') ? ini_get('mbstring.func_overload') : 0;
166
+	}
154 167
 
155 168
 	if (is_null($len))
156 169
 	{
@@ -216,7 +229,10 @@  discard block
 block discarded – undo
216 229
 			{
217 230
 				$personal = str_replace('\\', '', substr($personal, 1, -1));
218 231
 			}
219
-			if (empty($host)) $host = $default_host;
232
+			if (empty($host))
233
+			{
234
+				$host = $default_host;
235
+			}
220 236
 
221 237
 			$addresses[] = (object)array_diff(array(
222 238
 				'mailbox'  => $mailbox,
@@ -239,13 +255,19 @@  discard block
 block discarded – undo
239 255
 	 */
240 256
 	function imap_rfc822_write_address($mailbox, $host, $personal)
241 257
 	{
242
-		if (is_array($personal))  $personal = implode(' ', $personal);
258
+		if (is_array($personal))
259
+		{
260
+			$personal = implode(' ', $personal);
261
+		}
243 262
 
244 263
 		//if (!preg_match('/^[!#$%&\'*+/0-9=?A-Z^_`a-z{|}~-]+$/u', $personal))	// that's how I read the rfc(2)822
245
-		if ($personal && !preg_match('/^[0-9A-Z -]*$/iu', $personal))	// but quoting is never wrong, so quote more then necessary
264
+		if ($personal && !preg_match('/^[0-9A-Z -]*$/iu', $personal))
265
+		{
266
+			// but quoting is never wrong, so quote more then necessary
246 267
 		{
247 268
 			$personal = '"'.str_replace(array('\\', '"'),array('\\\\', '\\"'), $personal).'"';
248 269
 		}
270
+		}
249 271
 		return ($personal ? $personal.' <' : '').$mailbox.($host ? '@'.$host : '').($personal ? '>' : '');
250 272
 	}
251 273
 }
@@ -536,7 +558,7 @@  discard block
 block discarded – undo
536 558
 		if(!is_array($recieved[0]))
537 559
 		{
538 560
 		for ($i = 0; $i < $num; $i++)
539
-			{
561
+		{
540 562
 				if(isset($recieved[$i]) && $recieved[$i] !== '##DEFAULT##')
541 563
 				{
542 564
 					if(sanitize($recieved[$i],$expected[$i]['type']))
@@ -1265,51 +1287,71 @@  discard block
 block discarded – undo
1265 1287
 
1266 1288
 	for ($i=0;$i<count($testa);$i++)
1267 1289
 	{
1268
-		if ($DEBUG) { echo'<br>Checking if '. (int)$testa[$i] . ' is less than ' . (int)$testb[$i] . ' ...'; }
1290
+		if ($DEBUG)
1291
+		{
1292
+echo'<br>Checking if '. (int)$testa[$i] . ' is less than ' . (int)$testb[$i] . ' ...'; }
1269 1293
 		if ((int)$testa[$i] < (int)$testb[$i])
1270 1294
 		{
1271
-			if ($DEBUG) { echo ' yes.'; }
1295
+			if ($DEBUG)
1296
+			{
1297
+echo ' yes.'; }
1272 1298
 			$less++;
1273 1299
 			if ($i<3)
1274 1300
 			{
1275 1301
 				/* Ensure that this is definitely smaller */
1276
-				if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely less than B."; }
1302
+				if ($DEBUG)
1303
+				{
1304
+echo"  This is the $num[$i] octet, so A is definitely less than B."; }
1277 1305
 				$less = 5;
1278 1306
 				break;
1279 1307
 			}
1280 1308
 		}
1281 1309
 		elseif((int)$testa[$i] > (int)$testb[$i])
1282 1310
 		{
1283
-			if ($DEBUG) { echo ' no.'; }
1311
+			if ($DEBUG)
1312
+			{
1313
+echo ' no.'; }
1284 1314
 			$less--;
1285 1315
 			if ($i<2)
1286 1316
 			{
1287 1317
 				/* Ensure that this is definitely greater */
1288
-				if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely greater than B."; }
1318
+				if ($DEBUG)
1319
+				{
1320
+echo"  This is the $num[$i] octet, so A is definitely greater than B."; }
1289 1321
 				$less = -5;
1290 1322
 				break;
1291 1323
 			}
1292 1324
 		}
1293 1325
 		else
1294 1326
 		{
1295
-			if ($DEBUG) { echo ' no, they are equal.'; }
1327
+			if ($DEBUG)
1328
+			{
1329
+echo ' no, they are equal.'; }
1296 1330
 			$less = 0;
1297 1331
 		}
1298 1332
 	}
1299
-	if ($DEBUG) { echo '<br>Check value is: "'.$less.'"'; }
1333
+	if ($DEBUG)
1334
+	{
1335
+echo '<br>Check value is: "'.$less.'"'; }
1300 1336
 	if ($less>0)
1301 1337
 	{
1302
-		if ($DEBUG) { echo '<br>A is less than B'; }
1338
+		if ($DEBUG)
1339
+		{
1340
+echo '<br>A is less than B'; }
1303 1341
 		return True;
1304 1342
 	}
1305 1343
 	elseif($less<0)
1306 1344
 	{
1307
-		if ($DEBUG) { echo '<br>A is greater than B'; }
1345
+		if ($DEBUG)
1346
+		{
1347
+echo '<br>A is greater than B'; }
1308 1348
 		return False;
1309 1349
 	}
1310 1350
 	else
1311 1351
 	{
1312
-		if ($DEBUG) { echo '<br>A is equal to B'; }
1352
+		if ($DEBUG)
1353
+		{
1354
+echo '<br>A is equal to B'; }
1313 1355
 		return False;
1314 1356
 	}
1315 1357
 }
@@ -1345,51 +1387,71 @@  discard block
 block discarded – undo
1345 1387
 
1346 1388
 	for ($i=0;$i<count($testa);$i++)
1347 1389
 	{
1348
-		if ($DEBUG) { echo'<br>Checking if '. (int)$testa[$i] . ' is more than ' . (int)$testb[$i] . ' ...'; }
1390
+		if ($DEBUG)
1391
+		{
1392
+echo'<br>Checking if '. (int)$testa[$i] . ' is more than ' . (int)$testb[$i] . ' ...'; }
1349 1393
 		if ((int)$testa[$i] > (int)$testb[$i])
1350 1394
 		{
1351
-			if ($DEBUG) { echo ' yes.'; }
1395
+			if ($DEBUG)
1396
+			{
1397
+echo ' yes.'; }
1352 1398
 			$less++;
1353 1399
 			if ($i<3)
1354 1400
 			{
1355 1401
 				/* Ensure that this is definitely greater */
1356
-				if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely greater than B."; }
1402
+				if ($DEBUG)
1403
+				{
1404
+echo"  This is the $num[$i] octet, so A is definitely greater than B."; }
1357 1405
 				$less = 5;
1358 1406
 				break;
1359 1407
 			}
1360 1408
 		}
1361 1409
 		elseif((int)$testa[$i] < (int)$testb[$i])
1362 1410
 		{
1363
-			if ($DEBUG) { echo ' no.'; }
1411
+			if ($DEBUG)
1412
+			{
1413
+echo ' no.'; }
1364 1414
 			$less--;
1365 1415
 			if ($i<2)
1366 1416
 			{
1367 1417
 				/* Ensure that this is definitely smaller */
1368
-				if ($DEBUG) { echo"  This is the $num[$i] octet, so A is definitely less than B."; }
1418
+				if ($DEBUG)
1419
+				{
1420
+echo"  This is the $num[$i] octet, so A is definitely less than B."; }
1369 1421
 				$less = -5;
1370 1422
 				break;
1371 1423
 			}
1372 1424
 		}
1373 1425
 		else
1374 1426
 		{
1375
-			if ($DEBUG) { echo ' no, they are equal.'; }
1427
+			if ($DEBUG)
1428
+			{
1429
+echo ' no, they are equal.'; }
1376 1430
 			$less = 0;
1377 1431
 		}
1378 1432
 	}
1379
-	if ($DEBUG) { echo '<br>Check value is: "'.$less.'"'; }
1433
+	if ($DEBUG)
1434
+	{
1435
+echo '<br>Check value is: "'.$less.'"'; }
1380 1436
 	if ($less>0)
1381 1437
 	{
1382
-		if ($DEBUG) { echo '<br>A is greater than B'; }
1438
+		if ($DEBUG)
1439
+		{
1440
+echo '<br>A is greater than B'; }
1383 1441
 		return True;
1384 1442
 	}
1385 1443
 	elseif($less<0)
1386 1444
 	{
1387
-		if ($DEBUG) { echo '<br>A is less than B'; }
1445
+		if ($DEBUG)
1446
+		{
1447
+echo '<br>A is less than B'; }
1388 1448
 		return False;
1389 1449
 	}
1390 1450
 	else
1391 1451
 	{
1392
-		if ($DEBUG) { echo '<br>A is equal to B'; }
1452
+		if ($DEBUG)
1453
+		{
1454
+echo '<br>A is equal to B'; }
1393 1455
 		return False;
1394 1456
 	}
1395 1457
 }
@@ -1453,7 +1515,9 @@  discard block
 block discarded – undo
1453 1515
 {
1454 1516
 	static $preg=null;
1455 1517
 	//old: '/<\/?[^>]*\b(iframe|script|javascript|on(before)?(abort|blur|change|click|dblclick|error|focus|keydown|keypress|keyup|load|mousedown|mousemove|mouseout|mouseover|mouseup|reset|select|submit|unload))\b[^>]*>/i';
1456
-	if (!isset($preg)) $preg =
1518
+	if (!isset($preg))
1519
+	{
1520
+		$preg =
1457 1521
 		// forbidden tags like iframe or script
1458 1522
 		'/(<(\s*\/)?\s*(iframe|script|object|embed|math|meta)[^a-z0-9]|'.
1459 1523
 		// on* attributes
@@ -1462,6 +1526,7 @@  discard block
 block discarded – undo
1462 1526
 		'<[^>]+(href|src|dynsrc|lowsrc|background|style|poster|action)\s*=\s*("|\')?[^"\']*javascript|'.
1463 1527
 		// benavior:url and expression in style attribute
1464 1528
 		'<[^>]+style\s*=\s*("|\')[^>]*(behavior\s*:\s*url|expression)\s*\()/i';
1529
+	}
1465 1530
 	if (is_array($var))
1466 1531
 	{
1467 1532
 		foreach($var as $key => $val)
@@ -1470,7 +1535,9 @@  discard block
 block discarded – undo
1470 1535
 			{
1471 1536
 				_check_script_tag($var[$key],$name.'['.$key.']');
1472 1537
 			}
1473
-			elseif(strpos($val, '<') !== false)	// speedup: ignore everything without <
1538
+			elseif(strpos($val, '<') !== false)
1539
+			{
1540
+				// speedup: ignore everything without <
1474 1541
 			{
1475 1542
 				if (preg_match($preg,$val))
1476 1543
 				{
@@ -1478,6 +1545,7 @@  discard block
 block discarded – undo
1478 1545
 					if ($name == '_POST' && $key == 'json_data' && ($json_data = json_decode($val, true)))
1479 1546
 					{
1480 1547
 						_check_script_tag($json_data, $name.'[json_data]');
1548
+			}
1481 1549
 						$_REQUEST[$key] = $var[$key] = json_encode($json_data);
1482 1550
 						continue;
1483 1551
 					}
@@ -1654,7 +1722,9 @@  discard block
 block discarded – undo
1654 1722
 	unregister_globals();
1655 1723
 }
1656 1724
 
1657
-if (!function_exists('lang') || defined('NO_LANG'))	// setup declares an own version
1725
+if (!function_exists('lang') || defined('NO_LANG'))
1726
+{
1727
+	// setup declares an own version
1658 1728
 {
1659 1729
 	/**
1660 1730
 	 * function to handle multilanguage support
@@ -1668,6 +1738,7 @@  discard block
 block discarded – undo
1668 1738
 		if(!is_array($vars))
1669 1739
 		{
1670 1740
 			$vars = func_get_args();
1741
+}
1671 1742
 			array_shift($vars);	// remove $key
1672 1743
 		}
1673 1744
 		return translation::translate($key,$vars);
@@ -1931,7 +2002,9 @@  discard block
 block discarded – undo
1931 2002
 /**
1932 2003
  * Used internally to trace warnings
1933 2004
  */
1934
-class egw_exception_warning extends Exception {}
2005
+class egw_exception_warning extends Exception
2006
+{
2007
+}
1935 2008
 
1936 2009
 // install our error-handler only for catchable fatal errors and warnings
1937 2010
 // following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING
Please login to merge, or discard this patch.
Upper-Lower-Casing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -510,11 +510,11 @@  discard block
 block discarded – undo
510 510
 function safe_args($expected, $recieved, $line='??', $file='??')
511 511
 {
512 512
 	/* This array will contain all the required fields */
513
-	$required = Array();
513
+	$required = array();
514 514
 
515 515
 	/* This array will contain all types for sanatization checking */
516 516
 	/* only used when an array is passed as the first arg          */
517
-	$types = Array();
517
+	$types = array();
518 518
 
519 519
 	/* start by looping thru the expected list and set params with */
520 520
 	/* the default values                                          */
@@ -675,8 +675,8 @@  discard block
 block discarded – undo
675 675
 			break;
676 676
 		case 'password':
677 677
 			$password_length = strlen($string);
678
-			$password_numbers = Array('0','1','2','3','4','5','6','7','8','9');
679
-			$password_special_chars = Array(' ','~','`','!','@','#','$','%','^','&','*','(',')','_','+','-','=','{','}','|','[',']',"\\",':','"',';',"'",'<','>','?',',','.','/');
678
+			$password_numbers = array('0','1','2','3','4','5','6','7','8','9');
679
+			$password_special_chars = array(' ','~','`','!','@','#','$','%','^','&','*','(',')','_','+','-','=','{','}','|','[',']',"\\",':','"',';',"'",'<','>','?',',','.','/');
680 680
 
681 681
 			if(@isset($GLOBALS['egw_info']['server']['pass_min_length']) && is_int($GLOBALS['egw_info']['server']['pass_min_length']) && $GLOBALS['egw_info']['server']['pass_min_length'] > 1)
682 682
 			{
@@ -776,11 +776,11 @@  discard block
 block discarded – undo
776 776
 {
777 777
 	if($method == 'any' || $method == array('any'))
778 778
 	{
779
-		$method = Array('POST','GET','COOKIE','SERVER','FILES','GLOBAL','DEFAULT');
779
+		$method = array('POST','GET','COOKIE','SERVER','FILES','GLOBAL','DEFAULT');
780 780
 	}
781 781
 	elseif(!is_array($method))
782 782
 	{
783
-		$method = Array($method);
783
+		$method = array($method);
784 784
 	}
785 785
 	$cnt = count($method);
786 786
 	for($i=0;$i<$cnt;$i++)
Please login to merge, or discard this patch.
phpgwapi/inc/horde/Horde.php 6 patches
Doc Comments   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -398,7 +398,7 @@  discard block
 block discarded – undo
398 398
     /**
399 399
      * Returns the driver parameters for the specified backend.
400 400
      *
401
-     * @param mixed $backend  The backend system (e.g. 'prefs', 'categories',
401
+     * @param string $backend  The backend system (e.g. 'prefs', 'categories',
402 402
      *                        'contacts') being used.
403 403
      *                        The used configuration array will be
404 404
      *                        $conf[$backend]. If an array gets passed, it will
@@ -835,6 +835,7 @@  discard block
 block discarded – undo
835 835
      *                               Can be a pre-built string or an array of key/value
836 836
      *                               pairs that will be assembled and html-encoded.
837 837
      * @param optional string $dir   The root graphics directory.
838
+     * @param string $dir
838 839
      *
839 840
      * @return string  The full image tag.
840 841
      */
@@ -1028,7 +1029,7 @@  discard block
 block discarded – undo
1028 1029
      *
1029 1030
      * @access public
1030 1031
      *
1031
-     * @param string|array $app  The Horde application(s).
1032
+     * @param string|array $apps  The Horde application(s).
1032 1033
      * @param mixed $theme       The theme to use; specify an empty value to
1033 1034
      *                           retrieve the theme from user preferences, and
1034 1035
      *                           false for no theme.
Please login to merge, or discard this patch.
Indentation   +1428 added lines, -1428 removed lines patch added patch discarded remove patch
@@ -22,1453 +22,1453 @@
 block discarded – undo
22 22
  */
23 23
 class Horde {
24 24
 
25
-    /**
26
-     * Logs a message to the global Horde log backend.
27
-     *
28
-     * @access public
29
-     *
30
-     * @param mixed $message     Either a string or a PEAR_Error object.
31
-     * @param string $file       What file was the log function called from
32
-     *                           (e.g. __FILE__)?
33
-     * @param integer $line      What line was the log function called from
34
-     *                           (e.g. __LINE__)?
35
-     * @param integer $priority  The priority of the message. One of:
36
-     * <pre>
37
-     * PEAR_LOG_EMERG
38
-     * PEAR_LOG_ALERT
39
-     * PEAR_LOG_CRIT
40
-     * PEAR_LOG_ERR
41
-     * PEAR_LOG_WARNING
42
-     * PEAR_LOG_NOTICE
43
-     * PEAR_LOG_INFO
44
-     * PEAR_LOG_DEBUG
45
-     * </pre>
46
-     */
47
-    function logMessage($message, $file, $line, $priority = PEAR_LOG_INFO)
48
-    {
49
-        global $conf;
50
-
51
-        if (!$conf['log']['enabled']) {
52
-            return;
53
-        }
54
-
55
-        if ($priority > $conf['log']['priority']) {
56
-            return;
57
-        }
58
-
59
-        $logger = &Horde::getLogger();
60
-        if (!is_a($logger, 'Log')) {
61
-            Horde::fatal(PEAR::raiseError('An error has occurred. Furthermore, Horde encountered an error attempting to log this error. Please check your Horde logging configuration in horde/config/conf.php.'), __FILE__, __LINE__, false);
62
-        }
63
-
64
-        if (is_a($message, 'PEAR_Error')) {
65
-            $userinfo = $message->getUserInfo();
66
-            $message = $message->getMessage();
67
-            if (!empty($userinfo)) {
68
-                if (is_array($userinfo)) {
69
-                    $userinfo = implode(', ', $userinfo);
70
-                }
71
-                $message .= ': ' . $userinfo;
72
-            }
73
-        } elseif (is_callable(array($message, 'getMessage'))) {
74
-            $message = $message->getMessage();
75
-        }
76
-
77
-        $app = isset($GLOBALS['registry']) ? $GLOBALS['registry']->getApp() : 'horde';
78
-        $message = '[' . $app . '] ' . $message . ' [on line ' . $line . ' of "' . $file . '"]';
79
-
80
-        /* Make sure to log in the system's locale. */
81
-        $locale = setlocale(LC_TIME, 0);
82
-        setlocale(LC_TIME, 'C');
83
-
84
-        $logger->log($message, $priority);
85
-
86
-        /* Restore original locale. */
87
-        setlocale(LC_TIME, $locale);
88
-
89
-        return true;
90
-    }
91
-
92
-    function &getLogger()
93
-    {
94
-        global $conf;
95
-
96
-        if (empty($conf['log']['enabled'])) {
97
-            return false;
98
-        }
99
-
100
-        static $logcheck;
101
-        if (!isset($logcheck)) {
102
-            // Try to make sure that we can log messages somehow.
103
-            if (empty($conf['log']) ||
104
-                empty($conf['log']['type']) ||
105
-                empty($conf['log']['name']) ||
106
-                empty($conf['log']['ident']) ||
107
-                !isset($conf['log']['params'])) {
108
-                Horde::fatal(PEAR::raiseError('Horde is not correctly configured to log error messages. You must configure at least a text file log in horde/config/conf.php.'), __FILE__, __LINE__, false);
109
-            }
110
-            $logcheck = true;
111
-        }
112
-
113
-        return $logger = &Log::singleton($conf['log']['type'], $conf['log']['name'],
114
-                                         $conf['log']['ident'], $conf['log']['params']);
115
-    }
116
-
117
-    /**
118
-     * Destroys any existing session on login and make sure to use a new
119
-     * session ID, to avoid session fixation issues. Should be called before
120
-     * checking a login.
121
-     *
122
-     * @access public
123
-     */
124
-    function getCleanSession()
125
-    {
126
-        // Make sure to force a completely new session ID and clear
127
-        // all session data.
128
-        if (version_compare(phpversion(), '4.3.3') !== -1) {
129
-            session_regenerate_id();
130
-            session_unset();
131
-        } else {
132
-            @session_destroy();
133
-            if (Util::extensionExists('posix')) {
134
-                $new_session_id = md5(microtime() . posix_getpid());
135
-            } else {
136
-                $new_session_id = md5(uniqid(mt_rand(), true));
137
-            }
138
-            session_id($new_session_id);
139
-
140
-            // Restart the session, including setting up the session
141
-            // handler.
142
-            Horde::setupSessionHandler();
143
-            @session_start();
144
-        }
145
-    }
146
-
147
-    /**
148
-     * Aborts with a fatal error, displaying debug information to the user.
149
-     *
150
-     * @access public
151
-     *
152
-     * @param mixed $error   A PEAR_Error object with debug information or an
153
-     *                       error message.
154
-     * @param integer $file  The file in which the error occured.
155
-     * @param integer $line  The line on which the error occured.
156
-     * @param boolean $log   Log this message via Horde::logMesage()?
157
-     */
158
-    function fatal($error, $file, $line, $log = true)
159
-    {
160
-        @include_once 'Horde/Auth.php';
161
-        @include_once 'Horde/CLI.php';
162
-
163
-        $admin = class_exists('Auth') && Auth::isAdmin();
164
-        $cli = class_exists('Horde_CLI') && Horde_CLI::runningFromCLI();
165
-
166
-        $errortext = '<h1>' . _("A fatal error has occurred") . '</h1>';
167
-        if (is_a($error, 'PEAR_Error')) {
168
-            $info = array_merge(array('file' => 'conf.php', 'variable' => '$conf'),
169
-                                array($error->getUserInfo()));
170
-
171
-            switch ($error->getCode()) {
172
-            case HORDE_ERROR_DRIVER_CONFIG_MISSING:
173
-                $message = sprintf(_("No configuration information specified for %s."), $info['name']) . '<br />' .
174
-                    sprintf(_("The file %s should contain some %s settings."),
175
-                            $GLOBALS['registry']->get('fileroot') . '/config/' . $info['file'],
176
-                            sprintf("%s['%s']['params']", $info['variable'], $info['driver']));
177
-                break;
178
-
179
-            case HORDE_ERROR_DRIVER_CONFIG:
180
-                $message = sprintf(_("Required '%s' not specified in %s configuration."), $info['field'], $info['name']) . '<br />' .
181
-                    sprintf(_("The file %s should contain a %s setting."),
182
-                            $GLOBALS['registry']->get('fileroot') . '/config/' . $info['file'],
183
-                            sprintf("%s['%s']['params']['%s']", $info['variable'], $info['driver'], $info['field']));
184
-                break;
185
-
186
-            default:
187
-                $message = $error->getMessage();
188
-                break;
189
-            }
190
-
191
-            $errortext .= '<h3>' . htmlspecialchars($message) . '</h3>';
192
-        } elseif (is_object($error) && method_exists($error, 'getMessage')) {
193
-            $errortext .= '<h3>' . htmlspecialchars($error->getMessage()) . '</h3>';
194
-        } elseif (is_string($error)) {
195
-            $errortext .= '<h3>' . $error . '</h3>';
196
-        }
197
-
198
-        if ($admin) {
199
-            $errortext .= '<p><code>' . sprintf(_("[line %s of %s]"), $line, $file) . '</code></p>';
200
-            if (is_object($error)) {
201
-                $errortext .= '<h3>' . _("Details (also in Horde's logfile):") . '</h3>';
202
-                $errortext .= '<p><pre>' . htmlspecialchars(Util::bufferOutput('var_dump', $error)) . '</pre></p>';
203
-            }
204
-        } elseif ($log) {
205
-            $errortext .= '<h3>' . _("Details have been logged for the administrator.") . '</h3>';
206
-        }
207
-
208
-        // Log the error via Horde::logMessage() if requested.
209
-        if ($log) {
210
-            Horde::logMessage($error, $file, $line, PEAR_LOG_EMERG);
211
-        }
212
-
213
-        if ($cli) {
214
-            echo strip_tags(str_replace(array('<br />', '<p>', '</p>', '<h1>', '</h1>', '<h3>', '</h3>'), "\n", $errortext));
215
-        } else {
216
-            echo <<< HTML
25
+	/**
26
+	 * Logs a message to the global Horde log backend.
27
+	 *
28
+	 * @access public
29
+	 *
30
+	 * @param mixed $message     Either a string or a PEAR_Error object.
31
+	 * @param string $file       What file was the log function called from
32
+	 *                           (e.g. __FILE__)?
33
+	 * @param integer $line      What line was the log function called from
34
+	 *                           (e.g. __LINE__)?
35
+	 * @param integer $priority  The priority of the message. One of:
36
+	 * <pre>
37
+	 * PEAR_LOG_EMERG
38
+	 * PEAR_LOG_ALERT
39
+	 * PEAR_LOG_CRIT
40
+	 * PEAR_LOG_ERR
41
+	 * PEAR_LOG_WARNING
42
+	 * PEAR_LOG_NOTICE
43
+	 * PEAR_LOG_INFO
44
+	 * PEAR_LOG_DEBUG
45
+	 * </pre>
46
+	 */
47
+	function logMessage($message, $file, $line, $priority = PEAR_LOG_INFO)
48
+	{
49
+		global $conf;
50
+
51
+		if (!$conf['log']['enabled']) {
52
+			return;
53
+		}
54
+
55
+		if ($priority > $conf['log']['priority']) {
56
+			return;
57
+		}
58
+
59
+		$logger = &Horde::getLogger();
60
+		if (!is_a($logger, 'Log')) {
61
+			Horde::fatal(PEAR::raiseError('An error has occurred. Furthermore, Horde encountered an error attempting to log this error. Please check your Horde logging configuration in horde/config/conf.php.'), __FILE__, __LINE__, false);
62
+		}
63
+
64
+		if (is_a($message, 'PEAR_Error')) {
65
+			$userinfo = $message->getUserInfo();
66
+			$message = $message->getMessage();
67
+			if (!empty($userinfo)) {
68
+				if (is_array($userinfo)) {
69
+					$userinfo = implode(', ', $userinfo);
70
+				}
71
+				$message .= ': ' . $userinfo;
72
+			}
73
+		} elseif (is_callable(array($message, 'getMessage'))) {
74
+			$message = $message->getMessage();
75
+		}
76
+
77
+		$app = isset($GLOBALS['registry']) ? $GLOBALS['registry']->getApp() : 'horde';
78
+		$message = '[' . $app . '] ' . $message . ' [on line ' . $line . ' of "' . $file . '"]';
79
+
80
+		/* Make sure to log in the system's locale. */
81
+		$locale = setlocale(LC_TIME, 0);
82
+		setlocale(LC_TIME, 'C');
83
+
84
+		$logger->log($message, $priority);
85
+
86
+		/* Restore original locale. */
87
+		setlocale(LC_TIME, $locale);
88
+
89
+		return true;
90
+	}
91
+
92
+	function &getLogger()
93
+	{
94
+		global $conf;
95
+
96
+		if (empty($conf['log']['enabled'])) {
97
+			return false;
98
+		}
99
+
100
+		static $logcheck;
101
+		if (!isset($logcheck)) {
102
+			// Try to make sure that we can log messages somehow.
103
+			if (empty($conf['log']) ||
104
+				empty($conf['log']['type']) ||
105
+				empty($conf['log']['name']) ||
106
+				empty($conf['log']['ident']) ||
107
+				!isset($conf['log']['params'])) {
108
+				Horde::fatal(PEAR::raiseError('Horde is not correctly configured to log error messages. You must configure at least a text file log in horde/config/conf.php.'), __FILE__, __LINE__, false);
109
+			}
110
+			$logcheck = true;
111
+		}
112
+
113
+		return $logger = &Log::singleton($conf['log']['type'], $conf['log']['name'],
114
+										 $conf['log']['ident'], $conf['log']['params']);
115
+	}
116
+
117
+	/**
118
+	 * Destroys any existing session on login and make sure to use a new
119
+	 * session ID, to avoid session fixation issues. Should be called before
120
+	 * checking a login.
121
+	 *
122
+	 * @access public
123
+	 */
124
+	function getCleanSession()
125
+	{
126
+		// Make sure to force a completely new session ID and clear
127
+		// all session data.
128
+		if (version_compare(phpversion(), '4.3.3') !== -1) {
129
+			session_regenerate_id();
130
+			session_unset();
131
+		} else {
132
+			@session_destroy();
133
+			if (Util::extensionExists('posix')) {
134
+				$new_session_id = md5(microtime() . posix_getpid());
135
+			} else {
136
+				$new_session_id = md5(uniqid(mt_rand(), true));
137
+			}
138
+			session_id($new_session_id);
139
+
140
+			// Restart the session, including setting up the session
141
+			// handler.
142
+			Horde::setupSessionHandler();
143
+			@session_start();
144
+		}
145
+	}
146
+
147
+	/**
148
+	 * Aborts with a fatal error, displaying debug information to the user.
149
+	 *
150
+	 * @access public
151
+	 *
152
+	 * @param mixed $error   A PEAR_Error object with debug information or an
153
+	 *                       error message.
154
+	 * @param integer $file  The file in which the error occured.
155
+	 * @param integer $line  The line on which the error occured.
156
+	 * @param boolean $log   Log this message via Horde::logMesage()?
157
+	 */
158
+	function fatal($error, $file, $line, $log = true)
159
+	{
160
+		@include_once 'Horde/Auth.php';
161
+		@include_once 'Horde/CLI.php';
162
+
163
+		$admin = class_exists('Auth') && Auth::isAdmin();
164
+		$cli = class_exists('Horde_CLI') && Horde_CLI::runningFromCLI();
165
+
166
+		$errortext = '<h1>' . _("A fatal error has occurred") . '</h1>';
167
+		if (is_a($error, 'PEAR_Error')) {
168
+			$info = array_merge(array('file' => 'conf.php', 'variable' => '$conf'),
169
+								array($error->getUserInfo()));
170
+
171
+			switch ($error->getCode()) {
172
+			case HORDE_ERROR_DRIVER_CONFIG_MISSING:
173
+				$message = sprintf(_("No configuration information specified for %s."), $info['name']) . '<br />' .
174
+					sprintf(_("The file %s should contain some %s settings."),
175
+							$GLOBALS['registry']->get('fileroot') . '/config/' . $info['file'],
176
+							sprintf("%s['%s']['params']", $info['variable'], $info['driver']));
177
+				break;
178
+
179
+			case HORDE_ERROR_DRIVER_CONFIG:
180
+				$message = sprintf(_("Required '%s' not specified in %s configuration."), $info['field'], $info['name']) . '<br />' .
181
+					sprintf(_("The file %s should contain a %s setting."),
182
+							$GLOBALS['registry']->get('fileroot') . '/config/' . $info['file'],
183
+							sprintf("%s['%s']['params']['%s']", $info['variable'], $info['driver'], $info['field']));
184
+				break;
185
+
186
+			default:
187
+				$message = $error->getMessage();
188
+				break;
189
+			}
190
+
191
+			$errortext .= '<h3>' . htmlspecialchars($message) . '</h3>';
192
+		} elseif (is_object($error) && method_exists($error, 'getMessage')) {
193
+			$errortext .= '<h3>' . htmlspecialchars($error->getMessage()) . '</h3>';
194
+		} elseif (is_string($error)) {
195
+			$errortext .= '<h3>' . $error . '</h3>';
196
+		}
197
+
198
+		if ($admin) {
199
+			$errortext .= '<p><code>' . sprintf(_("[line %s of %s]"), $line, $file) . '</code></p>';
200
+			if (is_object($error)) {
201
+				$errortext .= '<h3>' . _("Details (also in Horde's logfile):") . '</h3>';
202
+				$errortext .= '<p><pre>' . htmlspecialchars(Util::bufferOutput('var_dump', $error)) . '</pre></p>';
203
+			}
204
+		} elseif ($log) {
205
+			$errortext .= '<h3>' . _("Details have been logged for the administrator.") . '</h3>';
206
+		}
207
+
208
+		// Log the error via Horde::logMessage() if requested.
209
+		if ($log) {
210
+			Horde::logMessage($error, $file, $line, PEAR_LOG_EMERG);
211
+		}
212
+
213
+		if ($cli) {
214
+			echo strip_tags(str_replace(array('<br />', '<p>', '</p>', '<h1>', '</h1>', '<h3>', '</h3>'), "\n", $errortext));
215
+		} else {
216
+			echo <<< HTML
217 217
 <html>
218 218
 <head><title>Horde :: Fatal Error</title></head>
219 219
 <body style="background-color: white; color: black;">$errortext</body>
220 220
 </html>
221 221
 HTML;
222
-        }
223
-        exit;
224
-    }
225
-
226
-    /**
227
-     * Adds the javascript code to the output (if output has already started)
228
-     * or to the list of script files to include via includeScriptFiles().
229
-     *
230
-     * @access public
231
-     *
232
-     * @param string $file     The full javascript file name.
233
-     * @param string $app      The application name. Defaults to the current
234
-     *                         application.
235
-     * @param boolean $direct  Include the file directly without passing it
236
-     *                         through javascript.php?
237
-     */
238
-    function addScriptFile($file, $app = null, $direct = false)
239
-    {
240
-        global $registry;
241
-        static $included = array();
242
-
243
-        if (empty($app)) {
244
-            $app = $registry->getApp();
245
-        }
246
-
247
-        // Don't include scripts multiple times.
248
-        if (!empty($included[$app][$file])) {
249
-            return;
250
-        }
251
-        $included[$app][$file] = true;
252
-
253
-        if (ob_get_length() || headers_sent()) {
254
-            if ($direct) {
255
-                $url = Horde::url($file{0} == '/' ? $registry->get('webroot', $app) . $file : $registry->get('jsuri', $app) . '/' . $file);
256
-            } else {
257
-                $url = Horde::url($registry->get('webroot', 'horde') . '/services/javascript.php');
258
-                $url = Util::addParameter($url, array('file' => $file,
259
-                                                      'app'  => $app));
260
-            }
261
-            echo '<script language="JavaScript" type="text/javascript" src="' . $url . '"></script>';
262
-        } else {
263
-            global $_horde_script_files;
264
-            $_horde_script_files[$app][] = array($file, $direct);
265
-        }
266
-    }
267
-
268
-    /**
269
-     * Includes javascript files that were needed before any headers were sent.
270
-     *
271
-     * @access public
272
-     */
273
-    function includeScriptFiles()
274
-    {
275
-        global $_horde_script_files, $registry;
276
-
277
-        if (!empty($_horde_script_files)) {
278
-            $base_url = Horde::url($registry->get('webroot', 'horde') . '/services/javascript.php');
279
-            foreach ($_horde_script_files as $app => $files) {
280
-                foreach ($files as $file) {
281
-                    if (!empty($file[1])) {
282
-                        $url = $file[0]{0} == '/' ? $registry->get('webroot', $app) . $file[0] : $registry->get('jsuri', $app) . '/' . $file[0];
283
-                        echo '<script language="JavaScript" type="text/javascript" src="' . Horde::url($url) . "\"></script>\n";
284
-                    } else {
285
-                        $url = Util::addParameter($base_url, array('file' => $file[0],
286
-                                                                   'app'  => $app));
287
-                        echo '<script language="JavaScript" type="text/javascript" src="' . $url . "\"></script>\n";
288
-                    }
289
-                }
290
-            }
291
-        }
292
-    }
293
-
294
-    /**
295
-     * Includes javascript files that were needed before any headers were sent.
296
-     *
297
-     * @access public
298
-     */
299
-    function inlineScriptFiles()
300
-    {
301
-        global $_horde_script_files, $registry;
302
-
303
-        if (!empty($_horde_script_files)) {
304
-            $jsWrapper = $registry->get('fileroot', 'horde') . '/services/javascript.php';
305
-            foreach ($_horde_script_files as $app => $files) {
306
-                foreach ($files as $file) {
307
-                    if (!empty($file[1])) {
308
-                        @readfile($file[0]{0} == '/' ? $registry->get('fileroot', $app) . $file[0] : $registry->get('jsfs', $app) . '/' . $file[0]);
309
-                    } else {
310
-                        $file = $file[0];
311
-                        require $jsWrapper;
312
-                    }
313
-                }
314
-            }
315
-        }
316
-    }
317
-
318
-    /**
319
-     * Checks if link should be shown and return the nescessary code.
320
-     *
321
-     * @access public
322
-     *
323
-     * @param string  $type      Type of link to display
324
-     * @param string  $app       The name of the current Horde application.
325
-     * @param boolean $override  Override Horde settings?
326
-     * @param boolean $referrer  Include the current page as the referrer (url=)?
327
-     *
328
-     * @return string  The HTML to create the link.
329
-     */
330
-    function getServiceLink($type, $app, $override = false, $referrer = true)
331
-    {
332
-        if (!Horde::showService($type) && !$override) {
333
-            return false;
334
-        }
335
-
336
-        switch ($type) {
337
-        case 'help':
338
-            if ($GLOBALS['browser']->hasFeature('javascript')) {
339
-                Horde::addScriptFile('open_help_win.js', 'horde');
340
-                return "javascript:open_help_win('$app');";
341
-            } else {
342
-                $url = Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/help/', true);
343
-                return Util::addParameter($url, array('module' => $app,
344
-                                                      'show' => 'topics'));
345
-            }
346
-            break;
347
-
348
-        case 'problem':
349
-            return Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/problem.php?return_url=' . urlencode(Horde::selfUrl(true)));
350
-
351
-        case 'logout':
352
-            return Auth::addLogoutParameters(Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/login.php'), AUTH_REASON_LOGOUT);
353
-
354
-        case 'login':
355
-            return Auth::getLoginScreen('', $referrer ? Horde::selfUrl(true) : null);
356
-
357
-        case 'options':
358
-            global $conf;
359
-            if (($conf['prefs']['driver'] != '') && ($conf['prefs']['driver'] != 'none')) {
360
-                return Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/prefs.php?app=' . $app);
361
-            }
362
-            break;
363
-        }
364
-
365
-        return false;
366
-    }
367
-
368
-    /**
369
-     * @access public
370
-     *
371
-     * @param string $type  The type of link.
372
-     *
373
-     * @return boolean  True if the link is to be shown.
374
-     */
375
-    function showService($type)
376
-    {
377
-        global $conf;
378
-
379
-        if (empty($conf['menu']['links'][$type])) {
380
-            return false;
381
-        }
382
-
383
-        switch ($conf['menu']['links'][$type]) {
384
-        case 'all':
385
-            return true;
386
-
387
-        case 'never':
388
-            return false;
389
-
390
-        case 'authenticated':
391
-            return (bool)Auth::getAuth();
392
-
393
-        default:
394
-            return false;
395
-        }
396
-    }
397
-
398
-    /**
399
-     * Returns the driver parameters for the specified backend.
400
-     *
401
-     * @param mixed $backend  The backend system (e.g. 'prefs', 'categories',
402
-     *                        'contacts') being used.
403
-     *                        The used configuration array will be
404
-     *                        $conf[$backend]. If an array gets passed, it will
405
-     *                        be $conf[$key1][$key2].
406
-     * @param string $type    The type of driver.
407
-     *
408
-     * @return array  The connection parameters.
409
-     */
410
-    function getDriverConfig($backend, $type = 'sql')
411
-    {
412
-        global $conf;
413
-
414
-        $c = null;
415
-        if (is_array($backend)) {
416
-            require_once 'Horde/Array.php';
417
-            $c = Horde_Array::getElement($conf, $backend);
418
-        } elseif (isset($conf[$backend])) {
419
-            $c = $conf[$backend];
420
-        }
421
-        if (!is_null($c) && isset($c['params'])) {
422
-            if (isset($conf[$type])) {
423
-                return array_merge($conf[$type], $c['params']);
424
-            } else {
425
-                return $c['params'];
426
-            }
427
-        }
428
-
429
-        return isset($conf[$type]) ? $conf[$type] : array();
430
-    }
431
-
432
-
433
-    /**
434
-     * Returns the VFS driver parameters for the specified backend.
435
-     *
436
-     * @param string $name  The VFS system name (e.g. 'images', 'documents')
437
-     *                      being used.
438
-     *
439
-     * @return array  A hash with the VFS parameters; the VFS driver in 'type'
440
-     *                and the connection parameters in 'params'.
441
-     */
442
-    function getVFSConfig($name)
443
-    {
444
-        global $conf;
445
-
446
-        if (!isset($conf[$name]['type'])) {
447
-            return PEAR::raiseError(_("You must configure a VFS backend."));
448
-        }
449
-
450
-        if ($conf[$name]['type'] == 'horde') {
451
-            $vfs = $conf['vfs'];
452
-        } else {
453
-            $vfs = $conf[$name];
454
-        }
455
-
456
-        if ($vfs['type'] == 'sql') {
457
-            $vfs['params'] = Horde::getDriverConfig($name, 'sql');
458
-        }
459
-
460
-        return $vfs;
461
-    }
462
-
463
-    /**
464
-     * Checks if all necessary parameters for a driver configuration
465
-     * are set and throws a fatal error with a detailed explaination
466
-     * how to fix this, if something is missing.
467
-     *
468
-     * @param array $params     The configuration array with all parameters.
469
-     * @param string $driver    The key name (in the configuration array) of
470
-     *                          the driver.
471
-     * @param array $fields     An array with mandatory parameter names for
472
-     *                          this driver.
473
-     * @param string $name      The clear text name of the driver. If not
474
-     *                          specified, the application name will be used.
475
-     * @param string $file      The configuration file that should contain
476
-     *                          these settings.
477
-     * @param string $variable  The name of the configuration variable.
478
-     */
479
-    function assertDriverConfig($params, $driver, $fields, $name = null,
480
-                                $file = 'conf.php', $variable = '$conf')
481
-    {
482
-        global $registry;
483
-
484
-        // Don't generate a fatal error if we fail during or before
485
-        // Registry instantiation.
486
-        if (is_null($name)) {
487
-            $name = isset($registry) ? $registry->getApp() : '[unknown]';
488
-        }
489
-        $fileroot = isset($registry) ? $registry->get('fileroot') : '';
490
-
491
-        if (!is_array($params) || !count($params)) {
492
-            Horde::fatal(PEAR::raiseError(
493
-                sprintf(_("No configuration information specified for %s."), $name) . "\n\n" .
494
-                sprintf(_("The file %s should contain some %s settings."),
495
-                    $fileroot . '/config/' . $file,
496
-                    sprintf("%s['%s']['params']", $variable, $driver))),
497
-                __FILE__, __LINE__);
498
-        }
499
-
500
-        foreach ($fields as $field) {
501
-            if (!isset($params[$field])) {
502
-                Horde::fatal(PEAR::raiseError(
503
-                    sprintf(_("Required '%s' not specified in %s configuration."), $field, $name) . "\n\n" .
504
-                    sprintf(_("The file %s should contain a %s setting."),
505
-                        $fileroot . '/config/' . $file,
506
-                        sprintf("%s['%s']['params']['%s']", $variable, $driver, $field))),
507
-                    __FILE__, __LINE__);
508
-            }
509
-        }
510
-    }
511
-
512
-    /**
513
-     * Returns a session-id-ified version of $uri.
514
-     * If a full URL is requested, all parameter separators get converted to
515
-     * "&", otherwise to "&amp;".
516
-     *
517
-     * @access public
518
-     *
519
-     * @param string $uri          The URI to be modified.
520
-     * @param bool $full           Generate a full (http://server/path/) URL.
521
-     * @param int $append_session  0 = only if needed, 1 = always, -1 = never.
522
-     *
523
-     * @return string  The URL with the session id appended (if needed).
524
-     */
525
-    function url($uri, $full = false, $append_session = 0, $force_ssl = false)
526
-    {
527
-        if ($force_ssl) {
528
-            $full = true;
529
-        }
530
-
531
-        if ($full) {
532
-            global $conf, $registry, $browser;
533
-
534
-            /* Store connection parameters in local variables. */
535
-            $server_name = $conf['server']['name'];
536
-            $server_port = $conf['server']['port'];
537
-
538
-            $protocol = 'http';
539
-            if ($conf['use_ssl'] == 1) {
540
-                $protocol = 'https';
541
-            } elseif ($conf['use_ssl'] == 2 &&
542
-                      $browser->usingSSLConnection()) {
543
-                $protocol = 'https';
544
-            } elseif ($conf['use_ssl'] == 3) {
545
-                $server_port = '';
546
-                if ($force_ssl) {
547
-                    $protocol = 'https';
548
-                }
549
-            }
550
-
551
-            /* If using non-standard ports, add the port to the URL. */
552
-            if (!empty($server_port) &&
553
-                ((($protocol == 'http') && ($server_port != 80)) ||
554
-                 (($protocol == 'https') && ($server_port != 443)))) {
555
-                $server_name .= ':' . $server_port;
556
-            }
557
-
558
-            /* Store the webroot in a local variable. */
559
-            $webroot = $registry->get('webroot');
560
-
561
-            $url = $protocol . '://' . $server_name;
562
-            if (substr($uri, 0, 1) != '/') {
563
-                if (substr($webroot, -1) == '/') {
564
-                    $url .= $webroot . $uri;
565
-                } else {
566
-                    $url .= $webroot . '/' . $uri;
567
-                }
568
-            } else {
569
-                $url .= $uri;
570
-            }
571
-        } else {
572
-            $url = $uri;
573
-        }
574
-
575
-        if (($append_session == 1) ||
576
-            (($append_session == 0) &&
577
-             !isset($_COOKIE[session_name()]))) {
578
-            $url = Util::addParameter($url, session_name(), session_id());
579
-        }
580
-
581
-        if ($full) {
582
-            /* We need to run the replace twice, because we only catch every
222
+		}
223
+		exit;
224
+	}
225
+
226
+	/**
227
+	 * Adds the javascript code to the output (if output has already started)
228
+	 * or to the list of script files to include via includeScriptFiles().
229
+	 *
230
+	 * @access public
231
+	 *
232
+	 * @param string $file     The full javascript file name.
233
+	 * @param string $app      The application name. Defaults to the current
234
+	 *                         application.
235
+	 * @param boolean $direct  Include the file directly without passing it
236
+	 *                         through javascript.php?
237
+	 */
238
+	function addScriptFile($file, $app = null, $direct = false)
239
+	{
240
+		global $registry;
241
+		static $included = array();
242
+
243
+		if (empty($app)) {
244
+			$app = $registry->getApp();
245
+		}
246
+
247
+		// Don't include scripts multiple times.
248
+		if (!empty($included[$app][$file])) {
249
+			return;
250
+		}
251
+		$included[$app][$file] = true;
252
+
253
+		if (ob_get_length() || headers_sent()) {
254
+			if ($direct) {
255
+				$url = Horde::url($file{0} == '/' ? $registry->get('webroot', $app) . $file : $registry->get('jsuri', $app) . '/' . $file);
256
+			} else {
257
+				$url = Horde::url($registry->get('webroot', 'horde') . '/services/javascript.php');
258
+				$url = Util::addParameter($url, array('file' => $file,
259
+													  'app'  => $app));
260
+			}
261
+			echo '<script language="JavaScript" type="text/javascript" src="' . $url . '"></script>';
262
+		} else {
263
+			global $_horde_script_files;
264
+			$_horde_script_files[$app][] = array($file, $direct);
265
+		}
266
+	}
267
+
268
+	/**
269
+	 * Includes javascript files that were needed before any headers were sent.
270
+	 *
271
+	 * @access public
272
+	 */
273
+	function includeScriptFiles()
274
+	{
275
+		global $_horde_script_files, $registry;
276
+
277
+		if (!empty($_horde_script_files)) {
278
+			$base_url = Horde::url($registry->get('webroot', 'horde') . '/services/javascript.php');
279
+			foreach ($_horde_script_files as $app => $files) {
280
+				foreach ($files as $file) {
281
+					if (!empty($file[1])) {
282
+						$url = $file[0]{0} == '/' ? $registry->get('webroot', $app) . $file[0] : $registry->get('jsuri', $app) . '/' . $file[0];
283
+						echo '<script language="JavaScript" type="text/javascript" src="' . Horde::url($url) . "\"></script>\n";
284
+					} else {
285
+						$url = Util::addParameter($base_url, array('file' => $file[0],
286
+																   'app'  => $app));
287
+						echo '<script language="JavaScript" type="text/javascript" src="' . $url . "\"></script>\n";
288
+					}
289
+				}
290
+			}
291
+		}
292
+	}
293
+
294
+	/**
295
+	 * Includes javascript files that were needed before any headers were sent.
296
+	 *
297
+	 * @access public
298
+	 */
299
+	function inlineScriptFiles()
300
+	{
301
+		global $_horde_script_files, $registry;
302
+
303
+		if (!empty($_horde_script_files)) {
304
+			$jsWrapper = $registry->get('fileroot', 'horde') . '/services/javascript.php';
305
+			foreach ($_horde_script_files as $app => $files) {
306
+				foreach ($files as $file) {
307
+					if (!empty($file[1])) {
308
+						@readfile($file[0]{0} == '/' ? $registry->get('fileroot', $app) . $file[0] : $registry->get('jsfs', $app) . '/' . $file[0]);
309
+					} else {
310
+						$file = $file[0];
311
+						require $jsWrapper;
312
+					}
313
+				}
314
+			}
315
+		}
316
+	}
317
+
318
+	/**
319
+	 * Checks if link should be shown and return the nescessary code.
320
+	 *
321
+	 * @access public
322
+	 *
323
+	 * @param string  $type      Type of link to display
324
+	 * @param string  $app       The name of the current Horde application.
325
+	 * @param boolean $override  Override Horde settings?
326
+	 * @param boolean $referrer  Include the current page as the referrer (url=)?
327
+	 *
328
+	 * @return string  The HTML to create the link.
329
+	 */
330
+	function getServiceLink($type, $app, $override = false, $referrer = true)
331
+	{
332
+		if (!Horde::showService($type) && !$override) {
333
+			return false;
334
+		}
335
+
336
+		switch ($type) {
337
+		case 'help':
338
+			if ($GLOBALS['browser']->hasFeature('javascript')) {
339
+				Horde::addScriptFile('open_help_win.js', 'horde');
340
+				return "javascript:open_help_win('$app');";
341
+			} else {
342
+				$url = Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/help/', true);
343
+				return Util::addParameter($url, array('module' => $app,
344
+													  'show' => 'topics'));
345
+			}
346
+			break;
347
+
348
+		case 'problem':
349
+			return Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/problem.php?return_url=' . urlencode(Horde::selfUrl(true)));
350
+
351
+		case 'logout':
352
+			return Auth::addLogoutParameters(Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/login.php'), AUTH_REASON_LOGOUT);
353
+
354
+		case 'login':
355
+			return Auth::getLoginScreen('', $referrer ? Horde::selfUrl(true) : null);
356
+
357
+		case 'options':
358
+			global $conf;
359
+			if (($conf['prefs']['driver'] != '') && ($conf['prefs']['driver'] != 'none')) {
360
+				return Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/prefs.php?app=' . $app);
361
+			}
362
+			break;
363
+		}
364
+
365
+		return false;
366
+	}
367
+
368
+	/**
369
+	 * @access public
370
+	 *
371
+	 * @param string $type  The type of link.
372
+	 *
373
+	 * @return boolean  True if the link is to be shown.
374
+	 */
375
+	function showService($type)
376
+	{
377
+		global $conf;
378
+
379
+		if (empty($conf['menu']['links'][$type])) {
380
+			return false;
381
+		}
382
+
383
+		switch ($conf['menu']['links'][$type]) {
384
+		case 'all':
385
+			return true;
386
+
387
+		case 'never':
388
+			return false;
389
+
390
+		case 'authenticated':
391
+			return (bool)Auth::getAuth();
392
+
393
+		default:
394
+			return false;
395
+		}
396
+	}
397
+
398
+	/**
399
+	 * Returns the driver parameters for the specified backend.
400
+	 *
401
+	 * @param mixed $backend  The backend system (e.g. 'prefs', 'categories',
402
+	 *                        'contacts') being used.
403
+	 *                        The used configuration array will be
404
+	 *                        $conf[$backend]. If an array gets passed, it will
405
+	 *                        be $conf[$key1][$key2].
406
+	 * @param string $type    The type of driver.
407
+	 *
408
+	 * @return array  The connection parameters.
409
+	 */
410
+	function getDriverConfig($backend, $type = 'sql')
411
+	{
412
+		global $conf;
413
+
414
+		$c = null;
415
+		if (is_array($backend)) {
416
+			require_once 'Horde/Array.php';
417
+			$c = Horde_Array::getElement($conf, $backend);
418
+		} elseif (isset($conf[$backend])) {
419
+			$c = $conf[$backend];
420
+		}
421
+		if (!is_null($c) && isset($c['params'])) {
422
+			if (isset($conf[$type])) {
423
+				return array_merge($conf[$type], $c['params']);
424
+			} else {
425
+				return $c['params'];
426
+			}
427
+		}
428
+
429
+		return isset($conf[$type]) ? $conf[$type] : array();
430
+	}
431
+
432
+
433
+	/**
434
+	 * Returns the VFS driver parameters for the specified backend.
435
+	 *
436
+	 * @param string $name  The VFS system name (e.g. 'images', 'documents')
437
+	 *                      being used.
438
+	 *
439
+	 * @return array  A hash with the VFS parameters; the VFS driver in 'type'
440
+	 *                and the connection parameters in 'params'.
441
+	 */
442
+	function getVFSConfig($name)
443
+	{
444
+		global $conf;
445
+
446
+		if (!isset($conf[$name]['type'])) {
447
+			return PEAR::raiseError(_("You must configure a VFS backend."));
448
+		}
449
+
450
+		if ($conf[$name]['type'] == 'horde') {
451
+			$vfs = $conf['vfs'];
452
+		} else {
453
+			$vfs = $conf[$name];
454
+		}
455
+
456
+		if ($vfs['type'] == 'sql') {
457
+			$vfs['params'] = Horde::getDriverConfig($name, 'sql');
458
+		}
459
+
460
+		return $vfs;
461
+	}
462
+
463
+	/**
464
+	 * Checks if all necessary parameters for a driver configuration
465
+	 * are set and throws a fatal error with a detailed explaination
466
+	 * how to fix this, if something is missing.
467
+	 *
468
+	 * @param array $params     The configuration array with all parameters.
469
+	 * @param string $driver    The key name (in the configuration array) of
470
+	 *                          the driver.
471
+	 * @param array $fields     An array with mandatory parameter names for
472
+	 *                          this driver.
473
+	 * @param string $name      The clear text name of the driver. If not
474
+	 *                          specified, the application name will be used.
475
+	 * @param string $file      The configuration file that should contain
476
+	 *                          these settings.
477
+	 * @param string $variable  The name of the configuration variable.
478
+	 */
479
+	function assertDriverConfig($params, $driver, $fields, $name = null,
480
+								$file = 'conf.php', $variable = '$conf')
481
+	{
482
+		global $registry;
483
+
484
+		// Don't generate a fatal error if we fail during or before
485
+		// Registry instantiation.
486
+		if (is_null($name)) {
487
+			$name = isset($registry) ? $registry->getApp() : '[unknown]';
488
+		}
489
+		$fileroot = isset($registry) ? $registry->get('fileroot') : '';
490
+
491
+		if (!is_array($params) || !count($params)) {
492
+			Horde::fatal(PEAR::raiseError(
493
+				sprintf(_("No configuration information specified for %s."), $name) . "\n\n" .
494
+				sprintf(_("The file %s should contain some %s settings."),
495
+					$fileroot . '/config/' . $file,
496
+					sprintf("%s['%s']['params']", $variable, $driver))),
497
+				__FILE__, __LINE__);
498
+		}
499
+
500
+		foreach ($fields as $field) {
501
+			if (!isset($params[$field])) {
502
+				Horde::fatal(PEAR::raiseError(
503
+					sprintf(_("Required '%s' not specified in %s configuration."), $field, $name) . "\n\n" .
504
+					sprintf(_("The file %s should contain a %s setting."),
505
+						$fileroot . '/config/' . $file,
506
+						sprintf("%s['%s']['params']['%s']", $variable, $driver, $field))),
507
+					__FILE__, __LINE__);
508
+			}
509
+		}
510
+	}
511
+
512
+	/**
513
+	 * Returns a session-id-ified version of $uri.
514
+	 * If a full URL is requested, all parameter separators get converted to
515
+	 * "&", otherwise to "&amp;".
516
+	 *
517
+	 * @access public
518
+	 *
519
+	 * @param string $uri          The URI to be modified.
520
+	 * @param bool $full           Generate a full (http://server/path/) URL.
521
+	 * @param int $append_session  0 = only if needed, 1 = always, -1 = never.
522
+	 *
523
+	 * @return string  The URL with the session id appended (if needed).
524
+	 */
525
+	function url($uri, $full = false, $append_session = 0, $force_ssl = false)
526
+	{
527
+		if ($force_ssl) {
528
+			$full = true;
529
+		}
530
+
531
+		if ($full) {
532
+			global $conf, $registry, $browser;
533
+
534
+			/* Store connection parameters in local variables. */
535
+			$server_name = $conf['server']['name'];
536
+			$server_port = $conf['server']['port'];
537
+
538
+			$protocol = 'http';
539
+			if ($conf['use_ssl'] == 1) {
540
+				$protocol = 'https';
541
+			} elseif ($conf['use_ssl'] == 2 &&
542
+					  $browser->usingSSLConnection()) {
543
+				$protocol = 'https';
544
+			} elseif ($conf['use_ssl'] == 3) {
545
+				$server_port = '';
546
+				if ($force_ssl) {
547
+					$protocol = 'https';
548
+				}
549
+			}
550
+
551
+			/* If using non-standard ports, add the port to the URL. */
552
+			if (!empty($server_port) &&
553
+				((($protocol == 'http') && ($server_port != 80)) ||
554
+				 (($protocol == 'https') && ($server_port != 443)))) {
555
+				$server_name .= ':' . $server_port;
556
+			}
557
+
558
+			/* Store the webroot in a local variable. */
559
+			$webroot = $registry->get('webroot');
560
+
561
+			$url = $protocol . '://' . $server_name;
562
+			if (substr($uri, 0, 1) != '/') {
563
+				if (substr($webroot, -1) == '/') {
564
+					$url .= $webroot . $uri;
565
+				} else {
566
+					$url .= $webroot . '/' . $uri;
567
+				}
568
+			} else {
569
+				$url .= $uri;
570
+			}
571
+		} else {
572
+			$url = $uri;
573
+		}
574
+
575
+		if (($append_session == 1) ||
576
+			(($append_session == 0) &&
577
+			 !isset($_COOKIE[session_name()]))) {
578
+			$url = Util::addParameter($url, session_name(), session_id());
579
+		}
580
+
581
+		if ($full) {
582
+			/* We need to run the replace twice, because we only catch every
583 583
              * second match. */
584
-            return preg_replace(array('/(=?.*?)&amp;(.*?=)/',
585
-                                      '/(=?.*?)&amp;(.*?=)/'),
586
-                                '$1&$2', $url);
587
-        } elseif (preg_match('/=.*&amp;.*=/', $url)) {
588
-            return $url;
589
-        } else {
590
-            return htmlentities($url);
591
-        }
592
-    }
593
-
594
-    /**
595
-     * Returns a session-id-ified version of $uri, using the current
596
-     * application's webroot setting.
597
-     *
598
-     * @access public
599
-     *
600
-     * @param string $uri          The URI to be modified.
601
-     * @param bool $full           Generate a full (http://server/path/) URL.
602
-     * @param int $append_session  0 = only if needed, 1 = always, -1 = never.
603
-     *
604
-     * @return string  The url with the session id appended.
605
-     */
606
-    function applicationUrl($uri, $full = false, $append_session = 0)
607
-    {
608
-        global $registry;
609
-
610
-        /* Store the webroot in a local variable. */
611
-        $webroot = $registry->get('webroot');
612
-
613
-        if ($full) {
614
-            return Horde::url($uri, $full, $append_session);
615
-        } elseif (substr($webroot, -1) == '/') {
616
-            return Horde::url($webroot . $uri, $full, $append_session);
617
-        } else {
618
-            return Horde::url($webroot . '/' . $uri, $full, $append_session);
619
-        }
620
-    }
621
-
622
-    /**
623
-     * Returns an external link passed through the dereferer to strip session
624
-     * IDs from the referer.
625
-     *
626
-     * @param string $url   The external URL to link to.
627
-     * @param boolean $tag  If true, a complete <a> tag is returned, only the
628
-     *                      url otherwise.
629
-     *
630
-     * @return string  The correct link to the dereferer script.
631
-     */
632
-    function externalUrl($url, $tag = false)
633
-    {
634
-        $ext = Horde::url($GLOBALS['registry']->get('webroot', 'horde') .
635
-                          '/services/go.php', true, -1);
636
-
637
-        /* We must make sure there are no &amp's in the URL. */
638
-        $url = preg_replace(array('/(=?.*?)&amp;(.*?=)/', '/(=?.*?)&amp;(.*?=)/'), '$1&$2', $url);
639
-        $ext = Util::addParameter($ext, 'url', $url);
640
-        if ($tag) {
641
-            $ext = Horde::link($ext, $url, '', '_blank');
642
-        }
643
-        return $ext;
644
-    }
645
-
646
-    /**
647
-     * Returns a URL to be used for downloading, that takes into account any
648
-     * special browser quirks (i.e. IE's broken filename handling).
649
-     *
650
-     * @access public
651
-     *
652
-     * @param string $filename  The filename of the download data.
653
-     * @param array $params     Any additional parameters needed.
654
-     * @param string $url       The URL to alter. If none passed in, will use
655
-     *                          the file 'view.php' located in the current
656
-     *                          module's base directory.
657
-     *
658
-     * @return string  The download URL.
659
-     */
660
-    function downloadUrl($filename, $params = array(), $url = null)
661
-    {
662
-        global $browser;
663
-
664
-        $horde_url = false;
665
-
666
-        if (is_null($url)) {
667
-            global $registry;
668
-            $url = Util::addParameter(Horde::url($registry->get('webroot', 'horde') . '/services/download/'), 'module', $registry->getApp());
669
-            $horde_url = true;
670
-        }
671
-
672
-        /* Add parameters. */
673
-        if (!is_null($params)) {
674
-            foreach ($params as $key => $val) {
675
-                $url = Util::addParameter($url, $key, $val);
676
-            }
677
-        }
678
-
679
-        /* If we are using the default Horde download link, add the
584
+			return preg_replace(array('/(=?.*?)&amp;(.*?=)/',
585
+									  '/(=?.*?)&amp;(.*?=)/'),
586
+								'$1&$2', $url);
587
+		} elseif (preg_match('/=.*&amp;.*=/', $url)) {
588
+			return $url;
589
+		} else {
590
+			return htmlentities($url);
591
+		}
592
+	}
593
+
594
+	/**
595
+	 * Returns a session-id-ified version of $uri, using the current
596
+	 * application's webroot setting.
597
+	 *
598
+	 * @access public
599
+	 *
600
+	 * @param string $uri          The URI to be modified.
601
+	 * @param bool $full           Generate a full (http://server/path/) URL.
602
+	 * @param int $append_session  0 = only if needed, 1 = always, -1 = never.
603
+	 *
604
+	 * @return string  The url with the session id appended.
605
+	 */
606
+	function applicationUrl($uri, $full = false, $append_session = 0)
607
+	{
608
+		global $registry;
609
+
610
+		/* Store the webroot in a local variable. */
611
+		$webroot = $registry->get('webroot');
612
+
613
+		if ($full) {
614
+			return Horde::url($uri, $full, $append_session);
615
+		} elseif (substr($webroot, -1) == '/') {
616
+			return Horde::url($webroot . $uri, $full, $append_session);
617
+		} else {
618
+			return Horde::url($webroot . '/' . $uri, $full, $append_session);
619
+		}
620
+	}
621
+
622
+	/**
623
+	 * Returns an external link passed through the dereferer to strip session
624
+	 * IDs from the referer.
625
+	 *
626
+	 * @param string $url   The external URL to link to.
627
+	 * @param boolean $tag  If true, a complete <a> tag is returned, only the
628
+	 *                      url otherwise.
629
+	 *
630
+	 * @return string  The correct link to the dereferer script.
631
+	 */
632
+	function externalUrl($url, $tag = false)
633
+	{
634
+		$ext = Horde::url($GLOBALS['registry']->get('webroot', 'horde') .
635
+						  '/services/go.php', true, -1);
636
+
637
+		/* We must make sure there are no &amp's in the URL. */
638
+		$url = preg_replace(array('/(=?.*?)&amp;(.*?=)/', '/(=?.*?)&amp;(.*?=)/'), '$1&$2', $url);
639
+		$ext = Util::addParameter($ext, 'url', $url);
640
+		if ($tag) {
641
+			$ext = Horde::link($ext, $url, '', '_blank');
642
+		}
643
+		return $ext;
644
+	}
645
+
646
+	/**
647
+	 * Returns a URL to be used for downloading, that takes into account any
648
+	 * special browser quirks (i.e. IE's broken filename handling).
649
+	 *
650
+	 * @access public
651
+	 *
652
+	 * @param string $filename  The filename of the download data.
653
+	 * @param array $params     Any additional parameters needed.
654
+	 * @param string $url       The URL to alter. If none passed in, will use
655
+	 *                          the file 'view.php' located in the current
656
+	 *                          module's base directory.
657
+	 *
658
+	 * @return string  The download URL.
659
+	 */
660
+	function downloadUrl($filename, $params = array(), $url = null)
661
+	{
662
+		global $browser;
663
+
664
+		$horde_url = false;
665
+
666
+		if (is_null($url)) {
667
+			global $registry;
668
+			$url = Util::addParameter(Horde::url($registry->get('webroot', 'horde') . '/services/download/'), 'module', $registry->getApp());
669
+			$horde_url = true;
670
+		}
671
+
672
+		/* Add parameters. */
673
+		if (!is_null($params)) {
674
+			foreach ($params as $key => $val) {
675
+				$url = Util::addParameter($url, $key, $val);
676
+			}
677
+		}
678
+
679
+		/* If we are using the default Horde download link, add the
680 680
          * filename to the end of the URL. Although not necessary for
681 681
          * many browsers, this should allow every browser to download
682 682
          * correctly. */
683
-        if ($horde_url) {
684
-            $url = Util::addParameter($url, 'fn=/' . rawurlencode($filename));
685
-        } elseif ($browser->hasQuirk('break_disposition_filename')) {
686
-            /* Some browsers will only obtain the filename correctly
683
+		if ($horde_url) {
684
+			$url = Util::addParameter($url, 'fn=/' . rawurlencode($filename));
685
+		} elseif ($browser->hasQuirk('break_disposition_filename')) {
686
+			/* Some browsers will only obtain the filename correctly
687 687
              * if the extension is the last argument in the query
688 688
              * string and rest of the filename appears in the
689 689
              * PATH_INFO element. */
690
-            $filename = rawurlencode($filename);
690
+			$filename = rawurlencode($filename);
691 691
 
692
-            /* Get the webserver ID. */
693
-            $server = Horde::webServerID();
692
+			/* Get the webserver ID. */
693
+			$server = Horde::webServerID();
694 694
 
695
-            /* Get the name and extension of the file.  Apache 2 does
695
+			/* Get the name and extension of the file.  Apache 2 does
696 696
              * NOT support PATH_INFO information being passed to the
697 697
              * PHP module by default, so disable that
698 698
              * functionality. */
699
-            if (($server != 'apache2')) {
700
-                if (($pos = strrpos($filename, '.'))) {
701
-                    $name = '/' . preg_replace('/\./', '%2E', substr($filename, 0, $pos));
702
-                    $ext = substr($filename, $pos);
703
-                } else {
704
-                    $name = '/' . $filename;
705
-                    $ext = '';
706
-                }
707
-
708
-                /* Enter the PATH_INFO information. */
709
-                if (($pos = strpos($url, '?'))) {
710
-                    $url = substr($url, 0, $pos) . $name . substr($url, $pos);
711
-                } else {
712
-                    $url .= $name;
713
-                }
714
-            }
715
-
716
-            /* Append the extension, if it exists. */
717
-            if (($server == 'apache2') || !empty($ext)) {
718
-                $url = Util::addParameter($url, 'fn_ext=/' . $filename);
719
-            }
720
-        }
721
-
722
-        return $url;
723
-    }
724
-
725
-    /**
726
-     * Returns an anchor tag with the relevant parameters
727
-     *
728
-     * @access public
729
-     *
730
-     * @param string $url        The full URL to be linked to
731
-     * @param string $status     The JavaScript mouse-over string
732
-     * @param string $class      The CSS class of the link
733
-     * @param string $target     The window target to point to.
734
-     * @param string $onclick    JavaScript action for the 'onclick' event.
735
-     * @param string $title      The link title (tooltip).
736
-     * @param string $accesskey  The access key to use.
737
-     * @param array $attributes  Any other name/value pairs to add to the <a>
738
-     *                           tag.
739
-     *
740
-     * @return string  The full <a href> tag.
741
-     */
742
-    function link($url, $status = '', $class = '', $target = '', $onclick = '',
743
-                  $title = '', $accesskey = '', $attributes = array())
744
-    {
745
-        $ret = "<a href=\"$url\"";
746
-        if (!empty($onclick)) {
747
-            $ret .= " onclick=\"$onclick\"";
748
-        }
749
-        if (!empty($status)) {
750
-            $ret .= ' onmouseout="window.status=\'\';" onmouseover="window.status=\'' . @htmlspecialchars(strtr(addslashes($status), array("\r" => '', "\n" => '')), ENT_QUOTES, NLS::getCharset()) . '\'; return true;"';
751
-        }
752
-        if (!empty($class)) {
753
-            $ret .= " class=\"$class\"";
754
-        }
755
-        if (!empty($target)) {
756
-            $ret .= " target=\"$target\"";
757
-        }
758
-        if (!empty($title)) {
759
-            $ret .= ' title="' . @htmlspecialchars($title, ENT_QUOTES, NLS::getCharset()) . '"';
760
-        }
761
-        if (!empty($accesskey)) {
762
-            $ret .= ' accesskey="' . htmlspecialchars($accesskey) . '"';
763
-        }
764
-
765
-        foreach ($attributes as $name => $value) {
766
-            $ret .= ' ' . htmlspecialchars($name) . '="' . htmlspecialchars($value) . '"';
767
-        }
768
-
769
-        return "$ret>";
770
-    }
771
-
772
-    /**
773
-     * Returns an anchor sequence with the relevant parameters for a widget
774
-     * with accesskey and text.
775
-     *
776
-     * @access public
777
-     *
778
-     * @param string $url       The full URL to be linked to
779
-     * @param string $status    The JavaScript mouse-over string
780
-     * @param string $class     The CSS class of the link
781
-     * @param string $target    The window target to point to.
782
-     * @param string $onclick   JavaScript action for the 'onclick' event.
783
-     * @param string $title     The link title (tooltip).
784
-     * @param boolean $nocheck  Don't check if the access key already has been
785
-     *                          used?
786
-     *
787
-     * @return string  The full <a href>Title</a> sequence.
788
-     */
789
-    function widget($url, $status = '', $class = 'widget', $target = '',
790
-                    $onclick = '', $title = '', $nocheck = false)
791
-    {
792
-        $ak = Horde::getAccessKey($title, $nocheck);
793
-        $plaintitle = Horde::stripAccessKey($title);
794
-
795
-        return Horde::link($url, $status, $class, $target, $onclick, $plaintitle, $ak) . Horde::highlightAccessKey($title, $ak) . '</a>';
796
-    }
797
-
798
-    /**
799
-     * Returns a session-id-ified version of $PHP_SELF.
800
-     *
801
-     * @access public
802
-     *
803
-     * @param boolean $query_string  Include any QUERY_STRING?
804
-     * @param boolean $nocache       Include a nocache parameter in the URL?
805
-     * @param boolean $full          Return a full URL?
806
-     *
807
-     * @return string  The requested URI.
808
-     */
809
-    function selfUrl($query_string = false, $nocache = true, $full = false,
810
-                     $force_ssl = false)
811
-    {
812
-        $url = $_SERVER['PHP_SELF'];
813
-
814
-        if ($query_string && !empty($_SERVER['QUERY_STRING'])) {
815
-            $url .= '?' . $_SERVER['QUERY_STRING'];
816
-        }
817
-
818
-        $url = Horde::url($url, $full, 0, $force_ssl);
819
-
820
-        if ($nocache) {
821
-            return Util::nocacheUrl($url);
822
-        } else {
823
-            return $url;
824
-        }
825
-    }
826
-
827
-    /**
828
-     * Constructs a correctly-pathed link to an image.
829
-     *
830
-     * @access public
831
-     *
832
-     * @param          string $src   The image file.
833
-     * @param optional string $alt   Text describing the image.
834
-     * @param optional mixed  $attr  Any additional attributes for the image tag.
835
-     *                               Can be a pre-built string or an array of key/value
836
-     *                               pairs that will be assembled and html-encoded.
837
-     * @param optional string $dir   The root graphics directory.
838
-     *
839
-     * @return string  The full image tag.
840
-     */
841
-    function img($src, $alt = '', $attr = '', $dir = null)
842
-    {
843
-        /* If browser does not support images, simply return the ALT text. */
844
-        if (!$GLOBALS['browser']->hasFeature('images')) {
845
-            return @htmlspecialchars($alt, ENT_COMPAT, NLS::getCharset());
846
-        }
847
-
848
-        /* If no directory has been specified, get it from the registry. */
849
-        if ($dir === null) {
850
-            global $registry;
851
-            $dir = $registry->getImageDir();
852
-        }
853
-
854
-        /* If a directory has been provided, prepend it to the image source. */
855
-        if (!empty($dir)) {
856
-            $src = $dir . '/' . $src;
857
-        }
858
-
859
-        /* Build all of the tag attributes. */
860
-        $attributes = array('src' => $src,
861
-                            'alt' => $alt,
862
-                            'title' => $alt);
863
-        if (is_array($attr)) {
864
-            $attributes = array_merge($attributes, $attr);
865
-        }
866
-
867
-        $img = '<img';
868
-        foreach ($attributes as $attribute => $value) {
869
-            $img .= ' ' . $attribute . '="' . ($attribute == 'src' ? $value : @htmlspecialchars($value, ENT_COMPAT, NLS::getCharset())) . '"';
870
-        }
871
-
872
-        /* If the user supplied a pre-built string of attributes, add that. */
873
-        if (is_string($attr) && !empty($attr)) {
874
-            $img .= ' ' . $attr;
875
-        }
876
-
877
-        /* Return the closed image tag. */
878
-        return $img . ' />';
879
-    }
880
-
881
-    /**
882
-     * Determines the location of the system temporary directory. If a specific
883
-     * setting cannot be found, it defaults to /tmp.
884
-     *
885
-     * @access public
886
-     *
887
-     * @return string  A directory name which can be used for temp files.
888
-     *                 Returns false if one could not be found.
889
-     */
890
-    function getTempDir()
891
-    {
892
-        global $conf;
893
-
894
-        /* If one has been specifically set, then use that */
895
-        if (!empty($conf['tmpdir'])) {
896
-            $tmp = $conf['tmpdir'];
897
-        }
898
-
899
-        /* Next, try Util::getTempDir(). */
900
-        if (empty($tmp)) {
901
-            $tmp = Util::getTempDir();
902
-        }
903
-
904
-        /* If it is still empty, we have failed, so return false;
699
+			if (($server != 'apache2')) {
700
+				if (($pos = strrpos($filename, '.'))) {
701
+					$name = '/' . preg_replace('/\./', '%2E', substr($filename, 0, $pos));
702
+					$ext = substr($filename, $pos);
703
+				} else {
704
+					$name = '/' . $filename;
705
+					$ext = '';
706
+				}
707
+
708
+				/* Enter the PATH_INFO information. */
709
+				if (($pos = strpos($url, '?'))) {
710
+					$url = substr($url, 0, $pos) . $name . substr($url, $pos);
711
+				} else {
712
+					$url .= $name;
713
+				}
714
+			}
715
+
716
+			/* Append the extension, if it exists. */
717
+			if (($server == 'apache2') || !empty($ext)) {
718
+				$url = Util::addParameter($url, 'fn_ext=/' . $filename);
719
+			}
720
+		}
721
+
722
+		return $url;
723
+	}
724
+
725
+	/**
726
+	 * Returns an anchor tag with the relevant parameters
727
+	 *
728
+	 * @access public
729
+	 *
730
+	 * @param string $url        The full URL to be linked to
731
+	 * @param string $status     The JavaScript mouse-over string
732
+	 * @param string $class      The CSS class of the link
733
+	 * @param string $target     The window target to point to.
734
+	 * @param string $onclick    JavaScript action for the 'onclick' event.
735
+	 * @param string $title      The link title (tooltip).
736
+	 * @param string $accesskey  The access key to use.
737
+	 * @param array $attributes  Any other name/value pairs to add to the <a>
738
+	 *                           tag.
739
+	 *
740
+	 * @return string  The full <a href> tag.
741
+	 */
742
+	function link($url, $status = '', $class = '', $target = '', $onclick = '',
743
+				  $title = '', $accesskey = '', $attributes = array())
744
+	{
745
+		$ret = "<a href=\"$url\"";
746
+		if (!empty($onclick)) {
747
+			$ret .= " onclick=\"$onclick\"";
748
+		}
749
+		if (!empty($status)) {
750
+			$ret .= ' onmouseout="window.status=\'\';" onmouseover="window.status=\'' . @htmlspecialchars(strtr(addslashes($status), array("\r" => '', "\n" => '')), ENT_QUOTES, NLS::getCharset()) . '\'; return true;"';
751
+		}
752
+		if (!empty($class)) {
753
+			$ret .= " class=\"$class\"";
754
+		}
755
+		if (!empty($target)) {
756
+			$ret .= " target=\"$target\"";
757
+		}
758
+		if (!empty($title)) {
759
+			$ret .= ' title="' . @htmlspecialchars($title, ENT_QUOTES, NLS::getCharset()) . '"';
760
+		}
761
+		if (!empty($accesskey)) {
762
+			$ret .= ' accesskey="' . htmlspecialchars($accesskey) . '"';
763
+		}
764
+
765
+		foreach ($attributes as $name => $value) {
766
+			$ret .= ' ' . htmlspecialchars($name) . '="' . htmlspecialchars($value) . '"';
767
+		}
768
+
769
+		return "$ret>";
770
+	}
771
+
772
+	/**
773
+	 * Returns an anchor sequence with the relevant parameters for a widget
774
+	 * with accesskey and text.
775
+	 *
776
+	 * @access public
777
+	 *
778
+	 * @param string $url       The full URL to be linked to
779
+	 * @param string $status    The JavaScript mouse-over string
780
+	 * @param string $class     The CSS class of the link
781
+	 * @param string $target    The window target to point to.
782
+	 * @param string $onclick   JavaScript action for the 'onclick' event.
783
+	 * @param string $title     The link title (tooltip).
784
+	 * @param boolean $nocheck  Don't check if the access key already has been
785
+	 *                          used?
786
+	 *
787
+	 * @return string  The full <a href>Title</a> sequence.
788
+	 */
789
+	function widget($url, $status = '', $class = 'widget', $target = '',
790
+					$onclick = '', $title = '', $nocheck = false)
791
+	{
792
+		$ak = Horde::getAccessKey($title, $nocheck);
793
+		$plaintitle = Horde::stripAccessKey($title);
794
+
795
+		return Horde::link($url, $status, $class, $target, $onclick, $plaintitle, $ak) . Horde::highlightAccessKey($title, $ak) . '</a>';
796
+	}
797
+
798
+	/**
799
+	 * Returns a session-id-ified version of $PHP_SELF.
800
+	 *
801
+	 * @access public
802
+	 *
803
+	 * @param boolean $query_string  Include any QUERY_STRING?
804
+	 * @param boolean $nocache       Include a nocache parameter in the URL?
805
+	 * @param boolean $full          Return a full URL?
806
+	 *
807
+	 * @return string  The requested URI.
808
+	 */
809
+	function selfUrl($query_string = false, $nocache = true, $full = false,
810
+					 $force_ssl = false)
811
+	{
812
+		$url = $_SERVER['PHP_SELF'];
813
+
814
+		if ($query_string && !empty($_SERVER['QUERY_STRING'])) {
815
+			$url .= '?' . $_SERVER['QUERY_STRING'];
816
+		}
817
+
818
+		$url = Horde::url($url, $full, 0, $force_ssl);
819
+
820
+		if ($nocache) {
821
+			return Util::nocacheUrl($url);
822
+		} else {
823
+			return $url;
824
+		}
825
+	}
826
+
827
+	/**
828
+	 * Constructs a correctly-pathed link to an image.
829
+	 *
830
+	 * @access public
831
+	 *
832
+	 * @param          string $src   The image file.
833
+	 * @param optional string $alt   Text describing the image.
834
+	 * @param optional mixed  $attr  Any additional attributes for the image tag.
835
+	 *                               Can be a pre-built string or an array of key/value
836
+	 *                               pairs that will be assembled and html-encoded.
837
+	 * @param optional string $dir   The root graphics directory.
838
+	 *
839
+	 * @return string  The full image tag.
840
+	 */
841
+	function img($src, $alt = '', $attr = '', $dir = null)
842
+	{
843
+		/* If browser does not support images, simply return the ALT text. */
844
+		if (!$GLOBALS['browser']->hasFeature('images')) {
845
+			return @htmlspecialchars($alt, ENT_COMPAT, NLS::getCharset());
846
+		}
847
+
848
+		/* If no directory has been specified, get it from the registry. */
849
+		if ($dir === null) {
850
+			global $registry;
851
+			$dir = $registry->getImageDir();
852
+		}
853
+
854
+		/* If a directory has been provided, prepend it to the image source. */
855
+		if (!empty($dir)) {
856
+			$src = $dir . '/' . $src;
857
+		}
858
+
859
+		/* Build all of the tag attributes. */
860
+		$attributes = array('src' => $src,
861
+							'alt' => $alt,
862
+							'title' => $alt);
863
+		if (is_array($attr)) {
864
+			$attributes = array_merge($attributes, $attr);
865
+		}
866
+
867
+		$img = '<img';
868
+		foreach ($attributes as $attribute => $value) {
869
+			$img .= ' ' . $attribute . '="' . ($attribute == 'src' ? $value : @htmlspecialchars($value, ENT_COMPAT, NLS::getCharset())) . '"';
870
+		}
871
+
872
+		/* If the user supplied a pre-built string of attributes, add that. */
873
+		if (is_string($attr) && !empty($attr)) {
874
+			$img .= ' ' . $attr;
875
+		}
876
+
877
+		/* Return the closed image tag. */
878
+		return $img . ' />';
879
+	}
880
+
881
+	/**
882
+	 * Determines the location of the system temporary directory. If a specific
883
+	 * setting cannot be found, it defaults to /tmp.
884
+	 *
885
+	 * @access public
886
+	 *
887
+	 * @return string  A directory name which can be used for temp files.
888
+	 *                 Returns false if one could not be found.
889
+	 */
890
+	function getTempDir()
891
+	{
892
+		global $conf;
893
+
894
+		/* If one has been specifically set, then use that */
895
+		if (!empty($conf['tmpdir'])) {
896
+			$tmp = $conf['tmpdir'];
897
+		}
898
+
899
+		/* Next, try Util::getTempDir(). */
900
+		if (empty($tmp)) {
901
+			$tmp = Util::getTempDir();
902
+		}
903
+
904
+		/* If it is still empty, we have failed, so return false;
905 905
          * otherwise return the directory determined. */
906
-        return empty($tmp) ? false : $tmp;
907
-    }
908
-
909
-    /**
910
-     * Creates a temporary filename for the lifetime of the script, and
911
-     * (optionally) registers it to be deleted at request shutdown.
912
-     *
913
-     * @access public
914
-     *
915
-     * @param string $prefix   Prefix to make the temporary name more
916
-     *                         recognizable.
917
-     * @param boolean $delete  Delete the file at the end of the request?
918
-     * @param string $dir      Directory to create the temporary file in.
919
-     * @param boolean $secure  If deleting file, should we securely delete the
920
-     *                         file?
921
-     *
922
-     * @return string   Returns the full path-name to the temporary file or
923
-     *                  false if a temporary file could not be created.
924
-     */
925
-    function getTempFile($prefix = 'Horde', $delete = true, $dir = '',
926
-                         $secure = false)
927
-    {
928
-        if (empty($dir) || !is_dir($dir)) {
929
-            $dir = Horde::getTempDir();
930
-        }
931
-
932
-        return Util::getTempFile($prefix, $delete, $dir, $secure);
933
-    }
934
-
935
-    /**
936
-     * Starts output compression, if requested.
937
-     *
938
-     * @access public
939
-     *
940
-     * @since Horde 2.2
941
-     */
942
-    function compressOutput()
943
-    {
944
-        static $started;
945
-
946
-        if (isset($started)) {
947
-            return;
948
-        }
949
-
950
-        /* Compress output if requested and possible. */
951
-        if ($GLOBALS['conf']['compress_pages'] &&
952
-            !$GLOBALS['browser']->hasQuirk('buggy_compression') &&
953
-            ini_get('zlib.output_compression') == '' &&
954
-            ini_get('output_handler') != 'ob_gzhandler') {
955
-            if (ob_get_level()) {
956
-                ob_end_clean();
957
-            }
958
-            ob_start('ob_gzhandler');
959
-        }
960
-
961
-        $started = true;
962
-    }
963
-
964
-    /**
965
-     * Determines if output compression can be used.
966
-     *
967
-     * @access public
968
-     *
969
-     * @return boolean  True if output compression can be used, false if not.
970
-     */
971
-    function allowOutputCompression()
972
-    {
973
-        require_once 'Horde/Browser.php';
974
-        $browser = &Browser::singleton();
975
-
976
-        /* Turn off compression for buggy browsers. */
977
-        if ($browser->hasQuirk('buggy_compression')) {
978
-            return false;
979
-        }
980
-
981
-        return (ini_get('zlib.output_compression') == '' &&
982
-                ini_get('output_handler') != 'ob_gzhandler');
983
-    }
984
-
985
-    /**
986
-     * Returns the Web server being used.
987
-     * PHP string list built from the PHP 'configure' script.
988
-     *
989
-     * @access public
990
-     *
991
-     * @return string  A web server identification string.
992
-     * <pre>
993
-     * 'aolserver' = AOL Server
994
-     * 'apache1'   = Apache 1.x
995
-     * 'apache2'   = Apache 2.x
996
-     * 'caudium'   = Caudium
997
-     * 'cgi'       = Unknown server - PHP built as CGI program
998
-     * 'cli'       = Command Line Interface build
999
-     * 'embed'     = Embedded PHP
1000
-     * 'isapi'     = Zeus ISAPI
1001
-     * 'milter'    = Milter
1002
-     * 'nsapi'     = NSAPI
1003
-     * 'phttpd'    = PHTTPD
1004
-     * 'pi3web'    = Pi3Web
1005
-     * 'roxen'     = Roxen/Pike
1006
-     * 'servlet'   = Servlet
1007
-     * 'thttpd'    = thttpd
1008
-     * 'tux'       = Tux
1009
-     * 'webjames'  = Webjames
1010
-     * </pre>
1011
-     */
1012
-    function webServerID()
1013
-    {
1014
-        $server = php_sapi_name();
1015
-
1016
-        if ($server == 'apache') {
1017
-            return 'apache1';
1018
-        } elseif (($server == 'apache2filter') ||
1019
-                  ($server == 'apache2handler')) {
1020
-            return 'apache2';
1021
-        } else {
1022
-            return $server;
1023
-        }
1024
-    }
1025
-
1026
-    /**
1027
-     * Returns the <link> tags for the CSS stylesheets.
1028
-     *
1029
-     * @access public
1030
-     *
1031
-     * @param string|array $app  The Horde application(s).
1032
-     * @param mixed $theme       The theme to use; specify an empty value to
1033
-     *                           retrieve the theme from user preferences, and
1034
-     *                           false for no theme.
1035
-     * @param boolean $inherit   Inherit Horde-wide CSS?
1036
-     *
1037
-     * @return string  <link> tags for CSS stylesheets.
1038
-     */
1039
-    function stylesheetLink($apps = null, $theme = '', $inherit = true)
1040
-    {
1041
-        if ($theme !== false && empty($theme)) {
1042
-            $theme = $GLOBALS['prefs']->getValue('theme');
1043
-        }
1044
-
1045
-        $css = array();
1046
-        $themes_fs = $GLOBALS['registry']->get('themesfs', 'horde');
1047
-        if ($inherit) {
1048
-            $themes_uri = Horde::url($GLOBALS['registry']->get('themesuri', 'horde'), false, -1);
1049
-            $css[] = $themes_uri . '/screen.css';
1050
-            if (!empty($theme) &&
1051
-                file_exists($themes_fs . '/' . $theme . '/screen.css')) {
1052
-                $css[] = $themes_uri . '/' . $theme . '/screen.css';
1053
-            }
1054
-        }
1055
-
1056
-        if (!empty($apps)) {
1057
-            if (!is_array($apps)) {
1058
-                $apps = array($apps);
1059
-            }
1060
-            foreach ($apps as $app) {
1061
-                if ($inherit && $app == 'horde') {
1062
-                    continue;
1063
-                }
1064
-
1065
-                $themes_fs = $GLOBALS['registry']->get('themesfs', $app);
1066
-                if (file_exists($themes_fs . '/screen.css')) {
1067
-                    $themes_uri = Horde::url($GLOBALS['registry']->get('themesuri', $app), false, -1);
1068
-                    $css[] = $themes_uri . '/screen.css';
1069
-                }
1070
-                if (!empty($theme) &&
1071
-                    file_exists($themes_fs . '/' . $theme . '/screen.css')) {
1072
-                    $css[] = $themes_uri . '/' . $theme . '/screen.css';
1073
-                }
1074
-            }
1075
-        }
1076
-
1077
-        $html = '';
1078
-        foreach ($css as $css_link) {
1079
-            $html .= '<link href="' . $css_link . '" rel="stylesheet" type="text/css" />' . "\n";
1080
-        }
1081
-
1082
-        /* Load IE PNG transparency code if needed. */
1083
-        if ($GLOBALS['browser']->hasQuirk('png_transparency') &&
1084
-            $GLOBALS['prefs']->getValue('alpha_filter')) {
1085
-            $url = Horde::url($GLOBALS['registry']->get('jsuri', 'horde') . '/alphaImageLoader.php', true, -1);
1086
-            $html .= '<style type="text/css"> img { behavior: url("' . $url . '"); } </style>';
1087
-        }
1088
-
1089
-        /* Load browser specific stylesheets if needed. */
1090
-        if ($GLOBALS['browser']->isBrowser('msie')) {
1091
-            $html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/ie.css" rel="stylesheet" type="text/css" />' . "\n";
1092
-            if ($GLOBALS['browser']->getPlatform() == 'mac') {
1093
-                $html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/ie5mac.css" rel="stylesheet" type="text/css" />' . "\n";
1094
-            }
1095
-        }
1096
-        if ($GLOBALS['browser']->isBrowser('opera')) {
1097
-            $html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/opera.css" rel="stylesheet" type="text/css" />' . "\n";
1098
-        }
1099
-        if (strpos(strtolower($GLOBALS['browser']->getAgentString()), 'safari') !== false) {
1100
-            $html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/safari.css" rel="stylesheet" type="text/css" />' . "\n";
1101
-        }
1102
-
1103
-        return $html;
1104
-    }
1105
-
1106
-    /**
1107
-     * Sets a custom session handler up, if there is one.
1108
-     *
1109
-     * @access public
1110
-     */
1111
-    function setupSessionHandler()
1112
-    {
1113
-        global $conf;
1114
-
1115
-        ini_set('url_rewriter.tags', 0);
1116
-        session_set_cookie_params($conf['session']['timeout'],
1117
-                                  $conf['cookie']['path'], $conf['cookie']['domain'], $conf['use_ssl'] == 1 ? 1 : 0);
1118
-        session_cache_limiter($conf['session']['cache_limiter']);
1119
-        session_name(urlencode($conf['session']['name']));
1120
-
1121
-        $type = !empty($conf['sessionhandler']['type']) ? $conf['sessionhandler']['type'] : 'none';
1122
-
1123
-        if ($type == 'external') {
1124
-            $calls = $conf['sessionhandler']['params'];
1125
-            session_set_save_handler($calls['open'],
1126
-                                     $calls['close'],
1127
-                                     $calls['read'],
1128
-                                     $calls['write'],
1129
-                                     $calls['destroy'],
1130
-                                     $calls['gc']);
1131
-        } elseif ($type != 'none') {
1132
-            global $_session_handler;
1133
-            require_once 'Horde/SessionHandler.php';
1134
-            $_session_handler = &SessionHandler::singleton($conf['sessionhandler']['type']);
1135
-            if (!empty($_session_handler) &&
1136
-                !is_a($_session_handler, 'PEAR_Error')) {
1137
-                ini_set('session.save_handler', 'user');
1138
-                session_set_save_handler(array(&$_session_handler, 'open'),
1139
-                                         array(&$_session_handler, 'close'),
1140
-                                         array(&$_session_handler, 'read'),
1141
-                                         array(&$_session_handler, 'write'),
1142
-                                         array(&$_session_handler, 'destroy'),
1143
-                                         array(&$_session_handler, 'gc'));
1144
-            } else {
1145
-                Horde::fatal(PEAR::raiseError('Horde is unable to correctly start the custom session handler.'), __FILE__, __LINE__, false);
1146
-            }
1147
-        }
1148
-    }
1149
-
1150
-    /**
1151
-     * Returns an un-used access key from the label given.
1152
-     *
1153
-     * @access public
1154
-     *
1155
-     * @param string $label     The label to choose an access key from.
1156
-     * @param boolean $nocheck  Don't check if the access key already has been
1157
-     *                          used?
1158
-     *
1159
-     * @return string  A single lower case character access key or empty
1160
-     *                 string if none can be found
1161
-     */
1162
-    function getAccessKey($label, $nocheck = false, $shutdown = false)
1163
-    {
1164
-        /* The access keys already used in this page */
1165
-        static $_used = array();
1166
-
1167
-        /* The labels already used in this page */
1168
-        static $_labels = array();
1169
-
1170
-        /* Shutdown call for translators? */
1171
-        if ($shutdown) {
1172
-            if (!count($_labels)) {
1173
-                return;
1174
-            }
1175
-            $script = basename($_SERVER['PHP_SELF']);
1176
-            $labels = array_keys($_labels);
1177
-            sort($labels);
1178
-            $used = array_keys($_used);
1179
-            sort($used);
1180
-            $remaining = str_replace($used, array(), 'abcdefghijklmnopqrstuvwxyz');
1181
-            Horde::logMessage('Access key information for ' . $script, __FILE__, __LINE__);
1182
-            Horde::logMessage('Used labels: ' . implode(',', $labels), __FILE__, __LINE__);
1183
-            Horde::logMessage('Used keys: ' . implode('', $used), __FILE__, __LINE__);
1184
-            Horde::logMessage('Free keys: ' . $remaining, __FILE__, __LINE__);
1185
-            return;
1186
-        }
1187
-
1188
-        /* Use access keys at all? */
1189
-        static $notsupported;
1190
-        if (!isset($notsupported)) {
1191
-            $notsupported = !$GLOBALS['browser']->hasFeature('accesskey') ||
1192
-                !$GLOBALS['prefs']->getValue('widget_accesskey');
1193
-        }
1194
-
1195
-        if ($notsupported || !preg_match('/_([A-Za-z])/', $label, $match)) {
1196
-            return '';
1197
-        }
1198
-        $key = $match[1];
1199
-
1200
-        /* Has this key already been used? */
1201
-        if (isset($_used[strtolower($key)]) &&
1202
-            !($nocheck && isset($_labels[$label]))) {
1203
-            return '';
1204
-        }
1205
-
1206
-        /* Save key and label. */
1207
-        $_used[strtolower($key)] = true;
1208
-        $_labels[$label] = true;
1209
-
1210
-        return $key;
1211
-    }
1212
-
1213
-    /**
1214
-     * Strips an access key from a label.
1215
-     * For multibyte charset strings the access key gets removed completely,
1216
-     * otherwise only the underscore gets removed.
1217
-     *
1218
-     * @access public
1219
-     *
1220
-     * @param string $label  The label containing an access key.
1221
-     *
1222
-     * @return string  The label with the access key being stripped.
1223
-     */
1224
-    function stripAccessKey($label)
1225
-    {
1226
-        include_once HORDE_BASE . '/config/nls.php';
1227
-        $multibyte = isset($GLOBALS['nls']['multibyte'][NLS::getCharset(true)]);
1228
-
1229
-        return preg_replace('/_([A-Za-z])/',
1230
-                            $multibyte && preg_match('/[\x80-\xff]/', $label) ? '' : '\1',
1231
-                            $label);
1232
-    }
1233
-
1234
-    /**
1235
-     * Highlights an access key in a label.
1236
-     *
1237
-     * @access public
1238
-     *
1239
-     * @param string $label      The label to to highlight the access key in.
1240
-     * @param string $accessKey  The access key to highlight.
1241
-     *
1242
-     * @return string  The HTML version of the label with the access key
1243
-     *                 highlighted.
1244
-     */
1245
-    function highlightAccessKey($label, $accessKey)
1246
-    {
1247
-        $stripped_label = Horde::stripAccesskey($label);
1248
-
1249
-        if (empty($accessKey)) {
1250
-            return $stripped_label;
1251
-        }
1252
-
1253
-        if (isset($GLOBALS['nls']['multibyte'][NLS::getCharset(true)])) {
1254
-            return $stripped_label . '(' . '<span class="accessKey">' .
1255
-                strtoupper($accessKey) . '</span>' . ')';
1256
-        } else {
1257
-            return str_replace('_' . $accessKey, '<span class="accessKey">' . $accessKey . '</span>', $label);
1258
-        }
1259
-    }
1260
-
1261
-    /**
1262
-     * Returns the appropriate "accesskey" and "title" attributes for an HTML
1263
-     * tag and the given label.
1264
-     *
1265
-     * @param string $label     The title of an HTML element
1266
-     * @param boolean $nocheck  Don't check if the access key already has been
1267
-     *                          used?
1268
-     *
1269
-     * @return string  The title, and if appropriate, the accesskey attributes
1270
-     *                 for the element.
1271
-     */
1272
-    function getAccessKeyAndTitle($label, $nocheck = false)
1273
-    {
1274
-        $ak = Horde::getAccessKey($label, $nocheck);
1275
-        $attributes = 'title="' . Horde::stripAccessKey($label);
1276
-        if (!empty($ak)) {
1277
-            $attributes .= sprintf(_(" (Accesskey %s)"), $ak);
1278
-            $attributes .= '" accesskey="' . $ak;
1279
-        }
1280
-        $attributes .= '"';
1281
-        return $attributes;
1282
-    }
1283
-
1284
-    /**
1285
-     * Returns a label element including an access key for usage in conjuction
1286
-     * with a form field. User preferences regarding access keys are respected.
1287
-     *
1288
-     * @param string $for    The form field's id attribute.
1289
-     * @param string $label  The label text.
1290
-     * @param string $ak     The access key to use. If null a new access key
1291
-     *                       will be generated.
1292
-     *
1293
-     * @return string  The html code for the label element.
1294
-     */
1295
-    function label($for, $label, $ak = null)
1296
-    {
1297
-        global $prefs;
1298
-
1299
-        if (is_null($ak)) {
1300
-            $ak = Horde::getAccesskey($label, 1);
1301
-        }
1302
-        $label = Horde::highlightAccessKey($label, $ak);
1303
-
1304
-        return sprintf('<label for="%s"%s>%s</label>',
1305
-                       $for,
1306
-                       !empty($ak) ? ' accesskey="' . $ak . '"' : '',
1307
-                       $label);
1308
-    }
1309
-
1310
-    /**
1311
-     * Redirects to the main Horde login page on authentication failure.
1312
-     *
1313
-     * @access public
1314
-     */
1315
-    function authenticationFailureRedirect()
1316
-    {
1317
-        require_once 'Horde/CLI.php';
1318
-        if (Horde_CLI::runningFromCLI()) {
1319
-            $cli = &Horde_CLI::singleton();
1320
-            $cli->fatal(_("You are not authenticated."));
1321
-        }
1322
-
1323
-        $url = $GLOBALS['registry']->get('webroot', 'horde') . '/login.php';
1324
-        $url = Util::addParameter($url, 'url', Horde::selfUrl(true));
1325
-        $url = Auth::addLogoutParameters($url);
1326
-        header('Location: ' . Horde::url($url, true));
1327
-        exit;
1328
-    }
1329
-
1330
-    /**
1331
-     * Uses DOM Tooltips (via javascript) to display the 'title'
1332
-     * attribute for Horde::link() calls.
1333
-     *
1334
-     * If using this function, the following function must be called:
1335
-     *   Horde::addScriptFile('tooltip.js', 'horde', true);
1336
-     *
1337
-     * @access public
1338
-     *
1339
-     * @param string $url        The full URL to be linked to
1340
-     * @param string $status     The JavaScript mouse-over string
1341
-     * @param string $class      The CSS class of the link
1342
-     * @param string $target     The window target to point to.
1343
-     * @param string $onclick    JavaScript action for the 'onclick' event.
1344
-     * @param string $title      The link title (tooltip).
1345
-     * @param string $accesskey  The access key to use.
1346
-     * @param array $attributes  Any other name/value pairs to add to the <a>
1347
-     *                           tag.
1348
-     *
1349
-     * @return string  The full <a href> tag.
1350
-     */
1351
-    function linkTooltip($url, $status = '', $class = '', $target = '',
1352
-                         $onclick = '', $title = '', $accesskey = '',
1353
-                         $attributes = array())
1354
-    {
1355
-        $url = substr(Horde::link($url, null, $class, $target, $onclick, null, $accesskey, $attributes), 0, -1);
1356
-
1357
-        if (strlen($status)) {
1358
-            $status = @htmlspecialchars(addslashes($status), ENT_QUOTES, NLS::getCharset());
1359
-        }
1360
-
1361
-        $title = trim($title);
1362
-        if (strlen($title)) {
1363
-            require_once 'Horde/Text/Filter.php';
1364
-            $title = Text_Filter::filter($title, 'text2html', array('parselevel' => TEXT_HTML_NOHTML, 'charset' => '', 'class' => ''));
1365
-            $title = '<pre style="margin:0px;">' . strtr(addslashes($title), array("\r" => '', "\n" => '')) . '</pre>';
1366
-            $url .= ' onmouseover="tooltipLink(\'' . @htmlspecialchars($title, ENT_QUOTES, NLS::getCharset()) . '\', \'' . $status . '\'); return true;" onmouseout="tooltipClose();"';
1367
-        }
1368
-        $url .= '>';
1369
-
1370
-        return $url;
1371
-    }
1372
-
1373
-    /**
1374
-     * Provides a standardised function to call a Horde hook, checking whether
1375
-     * a hook config file exists and whether the function itself exists. If
1376
-     * these two conditions are not satisfied it will return the specified
1377
-     * value (by default a PEAR error).
1378
-     *
1379
-     * @access public
1380
-     *
1381
-     * @param string $hook  The function to call.
1382
-     * @param array  $args  An array of any arguments to pass to the hook
1383
-     *                      function.
1384
-     * @param string $app   If specified look for hooks in the config directory
1385
-     *                      of this app.
1386
-     * @param mixed $error  What to return if $app/config/hooks.php or $hook
1387
-     *                      does not exist. If this is the string 'PEAR_Error'
1388
-     *                      a PEAR error object is returned instead, detailing
1389
-     *                      the failure.
1390
-     *
1391
-     * @return mixed  Either the results of the hook or PEAR error on failure.
1392
-     */
1393
-    function callHook($hook, $args = array(), $app = 'horde', $error = 'PEAR_Error')
1394
-    {
1395
-        global $registry;
1396
-        static $hooks_loaded;
1397
-
1398
-        if (!isset($hooks_loaded)) {
1399
-            if (file_exists($registry->get('fileroot', $app) . '/config/hooks.php')) {
1400
-                require_once $registry->get('fileroot', $app) . '/config/hooks.php';
1401
-                $hooks_loaded = true;
1402
-            } else {
1403
-                $hooks_loaded = false;
1404
-            }
1405
-        }
1406
-        if ($hooks_loaded && function_exists($hook)) {
1407
-            return call_user_func_array($hook, $args);
1408
-        }
1409
-
1410
-        if (is_string($error) && strcmp($error, 'PEAR_Error') == 0) {
1411
-            $error = PEAR::raiseError(sprintf('Hook %s in application %s not called.', $hook, $app));
1412
-            Horde::logMessage($error, __FILE__, __LINE__, PEAR_LOG_DEBUG);
1413
-        }
1414
-
1415
-        return $error;
1416
-    }
1417
-
1418
-    /**
1419
-     * Return the initial page to load when accessing Horde.
1420
-     *
1421
-     * @return string  The URL of the initial page.
1422
-     */
1423
-    function initialPage()
1424
-    {
1425
-        global $prefs, $registry, $perms;
1426
-
1427
-        $initial_app = $prefs->getValue('initial_application');
1428
-        if (!empty($initial_app) && $registry->hasPermission($initial_app)) {
1429
-            return Horde::url($registry->getInitialPage($initial_app), true);
1430
-        } elseif (isset($registry->applications['horde']['initial_page'])) {
1431
-            return Horde::applicationUrl($registry->applications['horde']['initial_page'], true);
1432
-        } elseif (Auth::getAuth()) {
1433
-            return Horde::applicationUrl('services/portal/', true);
1434
-        } else {
1435
-            return Horde::applicationUrl('login.php', true);
1436
-        }
1437
-    }
1438
-
1439
-    /**
1440
-     * Returns an array of available menu items when in a Horde script.
1441
-     *
1442
-     * @return array  Available menu items.
1443
-     */
1444
-    function getHordeMenu()
1445
-    {
1446
-        global $registry, $prefs;
1447
-
1448
-        $menu = array();
1449
-
1450
-        /* The home page button. If an initial application has been set in the
906
+		return empty($tmp) ? false : $tmp;
907
+	}
908
+
909
+	/**
910
+	 * Creates a temporary filename for the lifetime of the script, and
911
+	 * (optionally) registers it to be deleted at request shutdown.
912
+	 *
913
+	 * @access public
914
+	 *
915
+	 * @param string $prefix   Prefix to make the temporary name more
916
+	 *                         recognizable.
917
+	 * @param boolean $delete  Delete the file at the end of the request?
918
+	 * @param string $dir      Directory to create the temporary file in.
919
+	 * @param boolean $secure  If deleting file, should we securely delete the
920
+	 *                         file?
921
+	 *
922
+	 * @return string   Returns the full path-name to the temporary file or
923
+	 *                  false if a temporary file could not be created.
924
+	 */
925
+	function getTempFile($prefix = 'Horde', $delete = true, $dir = '',
926
+						 $secure = false)
927
+	{
928
+		if (empty($dir) || !is_dir($dir)) {
929
+			$dir = Horde::getTempDir();
930
+		}
931
+
932
+		return Util::getTempFile($prefix, $delete, $dir, $secure);
933
+	}
934
+
935
+	/**
936
+	 * Starts output compression, if requested.
937
+	 *
938
+	 * @access public
939
+	 *
940
+	 * @since Horde 2.2
941
+	 */
942
+	function compressOutput()
943
+	{
944
+		static $started;
945
+
946
+		if (isset($started)) {
947
+			return;
948
+		}
949
+
950
+		/* Compress output if requested and possible. */
951
+		if ($GLOBALS['conf']['compress_pages'] &&
952
+			!$GLOBALS['browser']->hasQuirk('buggy_compression') &&
953
+			ini_get('zlib.output_compression') == '' &&
954
+			ini_get('output_handler') != 'ob_gzhandler') {
955
+			if (ob_get_level()) {
956
+				ob_end_clean();
957
+			}
958
+			ob_start('ob_gzhandler');
959
+		}
960
+
961
+		$started = true;
962
+	}
963
+
964
+	/**
965
+	 * Determines if output compression can be used.
966
+	 *
967
+	 * @access public
968
+	 *
969
+	 * @return boolean  True if output compression can be used, false if not.
970
+	 */
971
+	function allowOutputCompression()
972
+	{
973
+		require_once 'Horde/Browser.php';
974
+		$browser = &Browser::singleton();
975
+
976
+		/* Turn off compression for buggy browsers. */
977
+		if ($browser->hasQuirk('buggy_compression')) {
978
+			return false;
979
+		}
980
+
981
+		return (ini_get('zlib.output_compression') == '' &&
982
+				ini_get('output_handler') != 'ob_gzhandler');
983
+	}
984
+
985
+	/**
986
+	 * Returns the Web server being used.
987
+	 * PHP string list built from the PHP 'configure' script.
988
+	 *
989
+	 * @access public
990
+	 *
991
+	 * @return string  A web server identification string.
992
+	 * <pre>
993
+	 * 'aolserver' = AOL Server
994
+	 * 'apache1'   = Apache 1.x
995
+	 * 'apache2'   = Apache 2.x
996
+	 * 'caudium'   = Caudium
997
+	 * 'cgi'       = Unknown server - PHP built as CGI program
998
+	 * 'cli'       = Command Line Interface build
999
+	 * 'embed'     = Embedded PHP
1000
+	 * 'isapi'     = Zeus ISAPI
1001
+	 * 'milter'    = Milter
1002
+	 * 'nsapi'     = NSAPI
1003
+	 * 'phttpd'    = PHTTPD
1004
+	 * 'pi3web'    = Pi3Web
1005
+	 * 'roxen'     = Roxen/Pike
1006
+	 * 'servlet'   = Servlet
1007
+	 * 'thttpd'    = thttpd
1008
+	 * 'tux'       = Tux
1009
+	 * 'webjames'  = Webjames
1010
+	 * </pre>
1011
+	 */
1012
+	function webServerID()
1013
+	{
1014
+		$server = php_sapi_name();
1015
+
1016
+		if ($server == 'apache') {
1017
+			return 'apache1';
1018
+		} elseif (($server == 'apache2filter') ||
1019
+				  ($server == 'apache2handler')) {
1020
+			return 'apache2';
1021
+		} else {
1022
+			return $server;
1023
+		}
1024
+	}
1025
+
1026
+	/**
1027
+	 * Returns the <link> tags for the CSS stylesheets.
1028
+	 *
1029
+	 * @access public
1030
+	 *
1031
+	 * @param string|array $app  The Horde application(s).
1032
+	 * @param mixed $theme       The theme to use; specify an empty value to
1033
+	 *                           retrieve the theme from user preferences, and
1034
+	 *                           false for no theme.
1035
+	 * @param boolean $inherit   Inherit Horde-wide CSS?
1036
+	 *
1037
+	 * @return string  <link> tags for CSS stylesheets.
1038
+	 */
1039
+	function stylesheetLink($apps = null, $theme = '', $inherit = true)
1040
+	{
1041
+		if ($theme !== false && empty($theme)) {
1042
+			$theme = $GLOBALS['prefs']->getValue('theme');
1043
+		}
1044
+
1045
+		$css = array();
1046
+		$themes_fs = $GLOBALS['registry']->get('themesfs', 'horde');
1047
+		if ($inherit) {
1048
+			$themes_uri = Horde::url($GLOBALS['registry']->get('themesuri', 'horde'), false, -1);
1049
+			$css[] = $themes_uri . '/screen.css';
1050
+			if (!empty($theme) &&
1051
+				file_exists($themes_fs . '/' . $theme . '/screen.css')) {
1052
+				$css[] = $themes_uri . '/' . $theme . '/screen.css';
1053
+			}
1054
+		}
1055
+
1056
+		if (!empty($apps)) {
1057
+			if (!is_array($apps)) {
1058
+				$apps = array($apps);
1059
+			}
1060
+			foreach ($apps as $app) {
1061
+				if ($inherit && $app == 'horde') {
1062
+					continue;
1063
+				}
1064
+
1065
+				$themes_fs = $GLOBALS['registry']->get('themesfs', $app);
1066
+				if (file_exists($themes_fs . '/screen.css')) {
1067
+					$themes_uri = Horde::url($GLOBALS['registry']->get('themesuri', $app), false, -1);
1068
+					$css[] = $themes_uri . '/screen.css';
1069
+				}
1070
+				if (!empty($theme) &&
1071
+					file_exists($themes_fs . '/' . $theme . '/screen.css')) {
1072
+					$css[] = $themes_uri . '/' . $theme . '/screen.css';
1073
+				}
1074
+			}
1075
+		}
1076
+
1077
+		$html = '';
1078
+		foreach ($css as $css_link) {
1079
+			$html .= '<link href="' . $css_link . '" rel="stylesheet" type="text/css" />' . "\n";
1080
+		}
1081
+
1082
+		/* Load IE PNG transparency code if needed. */
1083
+		if ($GLOBALS['browser']->hasQuirk('png_transparency') &&
1084
+			$GLOBALS['prefs']->getValue('alpha_filter')) {
1085
+			$url = Horde::url($GLOBALS['registry']->get('jsuri', 'horde') . '/alphaImageLoader.php', true, -1);
1086
+			$html .= '<style type="text/css"> img { behavior: url("' . $url . '"); } </style>';
1087
+		}
1088
+
1089
+		/* Load browser specific stylesheets if needed. */
1090
+		if ($GLOBALS['browser']->isBrowser('msie')) {
1091
+			$html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/ie.css" rel="stylesheet" type="text/css" />' . "\n";
1092
+			if ($GLOBALS['browser']->getPlatform() == 'mac') {
1093
+				$html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/ie5mac.css" rel="stylesheet" type="text/css" />' . "\n";
1094
+			}
1095
+		}
1096
+		if ($GLOBALS['browser']->isBrowser('opera')) {
1097
+			$html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/opera.css" rel="stylesheet" type="text/css" />' . "\n";
1098
+		}
1099
+		if (strpos(strtolower($GLOBALS['browser']->getAgentString()), 'safari') !== false) {
1100
+			$html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/safari.css" rel="stylesheet" type="text/css" />' . "\n";
1101
+		}
1102
+
1103
+		return $html;
1104
+	}
1105
+
1106
+	/**
1107
+	 * Sets a custom session handler up, if there is one.
1108
+	 *
1109
+	 * @access public
1110
+	 */
1111
+	function setupSessionHandler()
1112
+	{
1113
+		global $conf;
1114
+
1115
+		ini_set('url_rewriter.tags', 0);
1116
+		session_set_cookie_params($conf['session']['timeout'],
1117
+								  $conf['cookie']['path'], $conf['cookie']['domain'], $conf['use_ssl'] == 1 ? 1 : 0);
1118
+		session_cache_limiter($conf['session']['cache_limiter']);
1119
+		session_name(urlencode($conf['session']['name']));
1120
+
1121
+		$type = !empty($conf['sessionhandler']['type']) ? $conf['sessionhandler']['type'] : 'none';
1122
+
1123
+		if ($type == 'external') {
1124
+			$calls = $conf['sessionhandler']['params'];
1125
+			session_set_save_handler($calls['open'],
1126
+									 $calls['close'],
1127
+									 $calls['read'],
1128
+									 $calls['write'],
1129
+									 $calls['destroy'],
1130
+									 $calls['gc']);
1131
+		} elseif ($type != 'none') {
1132
+			global $_session_handler;
1133
+			require_once 'Horde/SessionHandler.php';
1134
+			$_session_handler = &SessionHandler::singleton($conf['sessionhandler']['type']);
1135
+			if (!empty($_session_handler) &&
1136
+				!is_a($_session_handler, 'PEAR_Error')) {
1137
+				ini_set('session.save_handler', 'user');
1138
+				session_set_save_handler(array(&$_session_handler, 'open'),
1139
+										 array(&$_session_handler, 'close'),
1140
+										 array(&$_session_handler, 'read'),
1141
+										 array(&$_session_handler, 'write'),
1142
+										 array(&$_session_handler, 'destroy'),
1143
+										 array(&$_session_handler, 'gc'));
1144
+			} else {
1145
+				Horde::fatal(PEAR::raiseError('Horde is unable to correctly start the custom session handler.'), __FILE__, __LINE__, false);
1146
+			}
1147
+		}
1148
+	}
1149
+
1150
+	/**
1151
+	 * Returns an un-used access key from the label given.
1152
+	 *
1153
+	 * @access public
1154
+	 *
1155
+	 * @param string $label     The label to choose an access key from.
1156
+	 * @param boolean $nocheck  Don't check if the access key already has been
1157
+	 *                          used?
1158
+	 *
1159
+	 * @return string  A single lower case character access key or empty
1160
+	 *                 string if none can be found
1161
+	 */
1162
+	function getAccessKey($label, $nocheck = false, $shutdown = false)
1163
+	{
1164
+		/* The access keys already used in this page */
1165
+		static $_used = array();
1166
+
1167
+		/* The labels already used in this page */
1168
+		static $_labels = array();
1169
+
1170
+		/* Shutdown call for translators? */
1171
+		if ($shutdown) {
1172
+			if (!count($_labels)) {
1173
+				return;
1174
+			}
1175
+			$script = basename($_SERVER['PHP_SELF']);
1176
+			$labels = array_keys($_labels);
1177
+			sort($labels);
1178
+			$used = array_keys($_used);
1179
+			sort($used);
1180
+			$remaining = str_replace($used, array(), 'abcdefghijklmnopqrstuvwxyz');
1181
+			Horde::logMessage('Access key information for ' . $script, __FILE__, __LINE__);
1182
+			Horde::logMessage('Used labels: ' . implode(',', $labels), __FILE__, __LINE__);
1183
+			Horde::logMessage('Used keys: ' . implode('', $used), __FILE__, __LINE__);
1184
+			Horde::logMessage('Free keys: ' . $remaining, __FILE__, __LINE__);
1185
+			return;
1186
+		}
1187
+
1188
+		/* Use access keys at all? */
1189
+		static $notsupported;
1190
+		if (!isset($notsupported)) {
1191
+			$notsupported = !$GLOBALS['browser']->hasFeature('accesskey') ||
1192
+				!$GLOBALS['prefs']->getValue('widget_accesskey');
1193
+		}
1194
+
1195
+		if ($notsupported || !preg_match('/_([A-Za-z])/', $label, $match)) {
1196
+			return '';
1197
+		}
1198
+		$key = $match[1];
1199
+
1200
+		/* Has this key already been used? */
1201
+		if (isset($_used[strtolower($key)]) &&
1202
+			!($nocheck && isset($_labels[$label]))) {
1203
+			return '';
1204
+		}
1205
+
1206
+		/* Save key and label. */
1207
+		$_used[strtolower($key)] = true;
1208
+		$_labels[$label] = true;
1209
+
1210
+		return $key;
1211
+	}
1212
+
1213
+	/**
1214
+	 * Strips an access key from a label.
1215
+	 * For multibyte charset strings the access key gets removed completely,
1216
+	 * otherwise only the underscore gets removed.
1217
+	 *
1218
+	 * @access public
1219
+	 *
1220
+	 * @param string $label  The label containing an access key.
1221
+	 *
1222
+	 * @return string  The label with the access key being stripped.
1223
+	 */
1224
+	function stripAccessKey($label)
1225
+	{
1226
+		include_once HORDE_BASE . '/config/nls.php';
1227
+		$multibyte = isset($GLOBALS['nls']['multibyte'][NLS::getCharset(true)]);
1228
+
1229
+		return preg_replace('/_([A-Za-z])/',
1230
+							$multibyte && preg_match('/[\x80-\xff]/', $label) ? '' : '\1',
1231
+							$label);
1232
+	}
1233
+
1234
+	/**
1235
+	 * Highlights an access key in a label.
1236
+	 *
1237
+	 * @access public
1238
+	 *
1239
+	 * @param string $label      The label to to highlight the access key in.
1240
+	 * @param string $accessKey  The access key to highlight.
1241
+	 *
1242
+	 * @return string  The HTML version of the label with the access key
1243
+	 *                 highlighted.
1244
+	 */
1245
+	function highlightAccessKey($label, $accessKey)
1246
+	{
1247
+		$stripped_label = Horde::stripAccesskey($label);
1248
+
1249
+		if (empty($accessKey)) {
1250
+			return $stripped_label;
1251
+		}
1252
+
1253
+		if (isset($GLOBALS['nls']['multibyte'][NLS::getCharset(true)])) {
1254
+			return $stripped_label . '(' . '<span class="accessKey">' .
1255
+				strtoupper($accessKey) . '</span>' . ')';
1256
+		} else {
1257
+			return str_replace('_' . $accessKey, '<span class="accessKey">' . $accessKey . '</span>', $label);
1258
+		}
1259
+	}
1260
+
1261
+	/**
1262
+	 * Returns the appropriate "accesskey" and "title" attributes for an HTML
1263
+	 * tag and the given label.
1264
+	 *
1265
+	 * @param string $label     The title of an HTML element
1266
+	 * @param boolean $nocheck  Don't check if the access key already has been
1267
+	 *                          used?
1268
+	 *
1269
+	 * @return string  The title, and if appropriate, the accesskey attributes
1270
+	 *                 for the element.
1271
+	 */
1272
+	function getAccessKeyAndTitle($label, $nocheck = false)
1273
+	{
1274
+		$ak = Horde::getAccessKey($label, $nocheck);
1275
+		$attributes = 'title="' . Horde::stripAccessKey($label);
1276
+		if (!empty($ak)) {
1277
+			$attributes .= sprintf(_(" (Accesskey %s)"), $ak);
1278
+			$attributes .= '" accesskey="' . $ak;
1279
+		}
1280
+		$attributes .= '"';
1281
+		return $attributes;
1282
+	}
1283
+
1284
+	/**
1285
+	 * Returns a label element including an access key for usage in conjuction
1286
+	 * with a form field. User preferences regarding access keys are respected.
1287
+	 *
1288
+	 * @param string $for    The form field's id attribute.
1289
+	 * @param string $label  The label text.
1290
+	 * @param string $ak     The access key to use. If null a new access key
1291
+	 *                       will be generated.
1292
+	 *
1293
+	 * @return string  The html code for the label element.
1294
+	 */
1295
+	function label($for, $label, $ak = null)
1296
+	{
1297
+		global $prefs;
1298
+
1299
+		if (is_null($ak)) {
1300
+			$ak = Horde::getAccesskey($label, 1);
1301
+		}
1302
+		$label = Horde::highlightAccessKey($label, $ak);
1303
+
1304
+		return sprintf('<label for="%s"%s>%s</label>',
1305
+					   $for,
1306
+					   !empty($ak) ? ' accesskey="' . $ak . '"' : '',
1307
+					   $label);
1308
+	}
1309
+
1310
+	/**
1311
+	 * Redirects to the main Horde login page on authentication failure.
1312
+	 *
1313
+	 * @access public
1314
+	 */
1315
+	function authenticationFailureRedirect()
1316
+	{
1317
+		require_once 'Horde/CLI.php';
1318
+		if (Horde_CLI::runningFromCLI()) {
1319
+			$cli = &Horde_CLI::singleton();
1320
+			$cli->fatal(_("You are not authenticated."));
1321
+		}
1322
+
1323
+		$url = $GLOBALS['registry']->get('webroot', 'horde') . '/login.php';
1324
+		$url = Util::addParameter($url, 'url', Horde::selfUrl(true));
1325
+		$url = Auth::addLogoutParameters($url);
1326
+		header('Location: ' . Horde::url($url, true));
1327
+		exit;
1328
+	}
1329
+
1330
+	/**
1331
+	 * Uses DOM Tooltips (via javascript) to display the 'title'
1332
+	 * attribute for Horde::link() calls.
1333
+	 *
1334
+	 * If using this function, the following function must be called:
1335
+	 *   Horde::addScriptFile('tooltip.js', 'horde', true);
1336
+	 *
1337
+	 * @access public
1338
+	 *
1339
+	 * @param string $url        The full URL to be linked to
1340
+	 * @param string $status     The JavaScript mouse-over string
1341
+	 * @param string $class      The CSS class of the link
1342
+	 * @param string $target     The window target to point to.
1343
+	 * @param string $onclick    JavaScript action for the 'onclick' event.
1344
+	 * @param string $title      The link title (tooltip).
1345
+	 * @param string $accesskey  The access key to use.
1346
+	 * @param array $attributes  Any other name/value pairs to add to the <a>
1347
+	 *                           tag.
1348
+	 *
1349
+	 * @return string  The full <a href> tag.
1350
+	 */
1351
+	function linkTooltip($url, $status = '', $class = '', $target = '',
1352
+						 $onclick = '', $title = '', $accesskey = '',
1353
+						 $attributes = array())
1354
+	{
1355
+		$url = substr(Horde::link($url, null, $class, $target, $onclick, null, $accesskey, $attributes), 0, -1);
1356
+
1357
+		if (strlen($status)) {
1358
+			$status = @htmlspecialchars(addslashes($status), ENT_QUOTES, NLS::getCharset());
1359
+		}
1360
+
1361
+		$title = trim($title);
1362
+		if (strlen($title)) {
1363
+			require_once 'Horde/Text/Filter.php';
1364
+			$title = Text_Filter::filter($title, 'text2html', array('parselevel' => TEXT_HTML_NOHTML, 'charset' => '', 'class' => ''));
1365
+			$title = '<pre style="margin:0px;">' . strtr(addslashes($title), array("\r" => '', "\n" => '')) . '</pre>';
1366
+			$url .= ' onmouseover="tooltipLink(\'' . @htmlspecialchars($title, ENT_QUOTES, NLS::getCharset()) . '\', \'' . $status . '\'); return true;" onmouseout="tooltipClose();"';
1367
+		}
1368
+		$url .= '>';
1369
+
1370
+		return $url;
1371
+	}
1372
+
1373
+	/**
1374
+	 * Provides a standardised function to call a Horde hook, checking whether
1375
+	 * a hook config file exists and whether the function itself exists. If
1376
+	 * these two conditions are not satisfied it will return the specified
1377
+	 * value (by default a PEAR error).
1378
+	 *
1379
+	 * @access public
1380
+	 *
1381
+	 * @param string $hook  The function to call.
1382
+	 * @param array  $args  An array of any arguments to pass to the hook
1383
+	 *                      function.
1384
+	 * @param string $app   If specified look for hooks in the config directory
1385
+	 *                      of this app.
1386
+	 * @param mixed $error  What to return if $app/config/hooks.php or $hook
1387
+	 *                      does not exist. If this is the string 'PEAR_Error'
1388
+	 *                      a PEAR error object is returned instead, detailing
1389
+	 *                      the failure.
1390
+	 *
1391
+	 * @return mixed  Either the results of the hook or PEAR error on failure.
1392
+	 */
1393
+	function callHook($hook, $args = array(), $app = 'horde', $error = 'PEAR_Error')
1394
+	{
1395
+		global $registry;
1396
+		static $hooks_loaded;
1397
+
1398
+		if (!isset($hooks_loaded)) {
1399
+			if (file_exists($registry->get('fileroot', $app) . '/config/hooks.php')) {
1400
+				require_once $registry->get('fileroot', $app) . '/config/hooks.php';
1401
+				$hooks_loaded = true;
1402
+			} else {
1403
+				$hooks_loaded = false;
1404
+			}
1405
+		}
1406
+		if ($hooks_loaded && function_exists($hook)) {
1407
+			return call_user_func_array($hook, $args);
1408
+		}
1409
+
1410
+		if (is_string($error) && strcmp($error, 'PEAR_Error') == 0) {
1411
+			$error = PEAR::raiseError(sprintf('Hook %s in application %s not called.', $hook, $app));
1412
+			Horde::logMessage($error, __FILE__, __LINE__, PEAR_LOG_DEBUG);
1413
+		}
1414
+
1415
+		return $error;
1416
+	}
1417
+
1418
+	/**
1419
+	 * Return the initial page to load when accessing Horde.
1420
+	 *
1421
+	 * @return string  The URL of the initial page.
1422
+	 */
1423
+	function initialPage()
1424
+	{
1425
+		global $prefs, $registry, $perms;
1426
+
1427
+		$initial_app = $prefs->getValue('initial_application');
1428
+		if (!empty($initial_app) && $registry->hasPermission($initial_app)) {
1429
+			return Horde::url($registry->getInitialPage($initial_app), true);
1430
+		} elseif (isset($registry->applications['horde']['initial_page'])) {
1431
+			return Horde::applicationUrl($registry->applications['horde']['initial_page'], true);
1432
+		} elseif (Auth::getAuth()) {
1433
+			return Horde::applicationUrl('services/portal/', true);
1434
+		} else {
1435
+			return Horde::applicationUrl('login.php', true);
1436
+		}
1437
+	}
1438
+
1439
+	/**
1440
+	 * Returns an array of available menu items when in a Horde script.
1441
+	 *
1442
+	 * @return array  Available menu items.
1443
+	 */
1444
+	function getHordeMenu()
1445
+	{
1446
+		global $registry, $prefs;
1447
+
1448
+		$menu = array();
1449
+
1450
+		/* The home page button. If an initial application has been set in the
1451 1451
          * prefs this will default to that application. Otherwise it will go
1452 1452
          * to the portal screen. */
1453
-        $initial_app = $prefs->getValue('initial_application');
1454
-        if (!empty($initial_app)) {
1455
-            $url = Horde::url($registry->getInitialPage($initial_app));
1456
-        } else {
1457
-            $url = Horde::applicationUrl('services/portal/');
1458
-        }
1459
-        $menu[] = array('url' => $url,
1460
-                        'text' =>  _("Home"),
1461
-                        'icon' => 'horde.png',
1462
-                        'icon_path' => $registry->getImageDir());
1463
-
1464
-        if (Auth::isAdmin()) {
1465
-            $menu[] = array('url' => Horde::applicationUrl('admin/'),
1466
-                            'text' =>  _("_Administration"),
1467
-                            'icon' => 'administration.png',
1468
-                            'icon_path' => $registry->getImageDir());
1469
-        }
1470
-
1471
-        return $menu;
1472
-    }
1453
+		$initial_app = $prefs->getValue('initial_application');
1454
+		if (!empty($initial_app)) {
1455
+			$url = Horde::url($registry->getInitialPage($initial_app));
1456
+		} else {
1457
+			$url = Horde::applicationUrl('services/portal/');
1458
+		}
1459
+		$menu[] = array('url' => $url,
1460
+						'text' =>  _("Home"),
1461
+						'icon' => 'horde.png',
1462
+						'icon_path' => $registry->getImageDir());
1463
+
1464
+		if (Auth::isAdmin()) {
1465
+			$menu[] = array('url' => Horde::applicationUrl('admin/'),
1466
+							'text' =>  _("_Administration"),
1467
+							'icon' => 'administration.png',
1468
+							'icon_path' => $registry->getImageDir());
1469
+		}
1470
+
1471
+		return $menu;
1472
+	}
1473 1473
 
1474 1474
 }
Please login to merge, or discard this patch.
Switch Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -169,23 +169,23 @@  discard block
 block discarded – undo
169 169
                                 array($error->getUserInfo()));
170 170
 
171 171
             switch ($error->getCode()) {
172
-            case HORDE_ERROR_DRIVER_CONFIG_MISSING:
173
-                $message = sprintf(_("No configuration information specified for %s."), $info['name']) . '<br />' .
174
-                    sprintf(_("The file %s should contain some %s settings."),
175
-                            $GLOBALS['registry']->get('fileroot') . '/config/' . $info['file'],
176
-                            sprintf("%s['%s']['params']", $info['variable'], $info['driver']));
177
-                break;
178
-
179
-            case HORDE_ERROR_DRIVER_CONFIG:
180
-                $message = sprintf(_("Required '%s' not specified in %s configuration."), $info['field'], $info['name']) . '<br />' .
181
-                    sprintf(_("The file %s should contain a %s setting."),
182
-                            $GLOBALS['registry']->get('fileroot') . '/config/' . $info['file'],
183
-                            sprintf("%s['%s']['params']['%s']", $info['variable'], $info['driver'], $info['field']));
184
-                break;
185
-
186
-            default:
187
-                $message = $error->getMessage();
188
-                break;
172
+            	case HORDE_ERROR_DRIVER_CONFIG_MISSING:
173
+                	$message = sprintf(_("No configuration information specified for %s."), $info['name']) . '<br />' .
174
+                    	sprintf(_("The file %s should contain some %s settings."),
175
+                            	$GLOBALS['registry']->get('fileroot') . '/config/' . $info['file'],
176
+                            	sprintf("%s['%s']['params']", $info['variable'], $info['driver']));
177
+                	break;
178
+
179
+            	case HORDE_ERROR_DRIVER_CONFIG:
180
+                	$message = sprintf(_("Required '%s' not specified in %s configuration."), $info['field'], $info['name']) . '<br />' .
181
+                    	sprintf(_("The file %s should contain a %s setting."),
182
+                            	$GLOBALS['registry']->get('fileroot') . '/config/' . $info['file'],
183
+                            	sprintf("%s['%s']['params']['%s']", $info['variable'], $info['driver'], $info['field']));
184
+                	break;
185
+
186
+            	default:
187
+                	$message = $error->getMessage();
188
+                	break;
189 189
             }
190 190
 
191 191
             $errortext .= '<h3>' . htmlspecialchars($message) . '</h3>';
@@ -334,32 +334,32 @@  discard block
 block discarded – undo
334 334
         }
335 335
 
336 336
         switch ($type) {
337
-        case 'help':
338
-            if ($GLOBALS['browser']->hasFeature('javascript')) {
339
-                Horde::addScriptFile('open_help_win.js', 'horde');
340
-                return "javascript:open_help_win('$app');";
341
-            } else {
342
-                $url = Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/help/', true);
343
-                return Util::addParameter($url, array('module' => $app,
344
-                                                      'show' => 'topics'));
345
-            }
346
-            break;
347
-
348
-        case 'problem':
349
-            return Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/problem.php?return_url=' . urlencode(Horde::selfUrl(true)));
350
-
351
-        case 'logout':
352
-            return Auth::addLogoutParameters(Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/login.php'), AUTH_REASON_LOGOUT);
353
-
354
-        case 'login':
355
-            return Auth::getLoginScreen('', $referrer ? Horde::selfUrl(true) : null);
356
-
357
-        case 'options':
358
-            global $conf;
359
-            if (($conf['prefs']['driver'] != '') && ($conf['prefs']['driver'] != 'none')) {
360
-                return Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/prefs.php?app=' . $app);
361
-            }
362
-            break;
337
+        	case 'help':
338
+            	if ($GLOBALS['browser']->hasFeature('javascript')) {
339
+                	Horde::addScriptFile('open_help_win.js', 'horde');
340
+                	return "javascript:open_help_win('$app');";
341
+            	} else {
342
+                	$url = Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/help/', true);
343
+                	return Util::addParameter($url, array('module' => $app,
344
+                                                      	'show' => 'topics'));
345
+            	}
346
+            	break;
347
+
348
+        	case 'problem':
349
+            	return Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/problem.php?return_url=' . urlencode(Horde::selfUrl(true)));
350
+
351
+        	case 'logout':
352
+            	return Auth::addLogoutParameters(Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/login.php'), AUTH_REASON_LOGOUT);
353
+
354
+        	case 'login':
355
+            	return Auth::getLoginScreen('', $referrer ? Horde::selfUrl(true) : null);
356
+
357
+        	case 'options':
358
+            	global $conf;
359
+            	if (($conf['prefs']['driver'] != '') && ($conf['prefs']['driver'] != 'none')) {
360
+                	return Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/prefs.php?app=' . $app);
361
+            	}
362
+            	break;
363 363
         }
364 364
 
365 365
         return false;
@@ -381,17 +381,17 @@  discard block
 block discarded – undo
381 381
         }
382 382
 
383 383
         switch ($conf['menu']['links'][$type]) {
384
-        case 'all':
385
-            return true;
384
+        	case 'all':
385
+            	return true;
386 386
 
387
-        case 'never':
388
-            return false;
387
+        	case 'never':
388
+            	return false;
389 389
 
390
-        case 'authenticated':
391
-            return (bool)Auth::getAuth();
390
+        	case 'authenticated':
391
+            	return (bool)Auth::getAuth();
392 392
 
393
-        default:
394
-            return false;
393
+        	default:
394
+            	return false;
395 395
         }
396 396
     }
397 397
 
Please login to merge, or discard this patch.
Spacing   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -68,14 +68,14 @@  discard block
 block discarded – undo
68 68
                 if (is_array($userinfo)) {
69 69
                     $userinfo = implode(', ', $userinfo);
70 70
                 }
71
-                $message .= ': ' . $userinfo;
71
+                $message .= ': '.$userinfo;
72 72
             }
73 73
         } elseif (is_callable(array($message, 'getMessage'))) {
74 74
             $message = $message->getMessage();
75 75
         }
76 76
 
77 77
         $app = isset($GLOBALS['registry']) ? $GLOBALS['registry']->getApp() : 'horde';
78
-        $message = '[' . $app . '] ' . $message . ' [on line ' . $line . ' of "' . $file . '"]';
78
+        $message = '['.$app.'] '.$message.' [on line '.$line.' of "'.$file.'"]';
79 79
 
80 80
         /* Make sure to log in the system's locale. */
81 81
         $locale = setlocale(LC_TIME, 0);
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
         } else {
132 132
             @session_destroy();
133 133
             if (Util::extensionExists('posix')) {
134
-                $new_session_id = md5(microtime() . posix_getpid());
134
+                $new_session_id = md5(microtime().posix_getpid());
135 135
             } else {
136 136
                 $new_session_id = md5(uniqid(mt_rand(), true));
137 137
             }
@@ -163,23 +163,23 @@  discard block
 block discarded – undo
163 163
         $admin = class_exists('Auth') && Auth::isAdmin();
164 164
         $cli = class_exists('Horde_CLI') && Horde_CLI::runningFromCLI();
165 165
 
166
-        $errortext = '<h1>' . _("A fatal error has occurred") . '</h1>';
166
+        $errortext = '<h1>'._("A fatal error has occurred").'</h1>';
167 167
         if (is_a($error, 'PEAR_Error')) {
168 168
             $info = array_merge(array('file' => 'conf.php', 'variable' => '$conf'),
169 169
                                 array($error->getUserInfo()));
170 170
 
171 171
             switch ($error->getCode()) {
172 172
             case HORDE_ERROR_DRIVER_CONFIG_MISSING:
173
-                $message = sprintf(_("No configuration information specified for %s."), $info['name']) . '<br />' .
173
+                $message = sprintf(_("No configuration information specified for %s."), $info['name']).'<br />'.
174 174
                     sprintf(_("The file %s should contain some %s settings."),
175
-                            $GLOBALS['registry']->get('fileroot') . '/config/' . $info['file'],
175
+                            $GLOBALS['registry']->get('fileroot').'/config/'.$info['file'],
176 176
                             sprintf("%s['%s']['params']", $info['variable'], $info['driver']));
177 177
                 break;
178 178
 
179 179
             case HORDE_ERROR_DRIVER_CONFIG:
180
-                $message = sprintf(_("Required '%s' not specified in %s configuration."), $info['field'], $info['name']) . '<br />' .
180
+                $message = sprintf(_("Required '%s' not specified in %s configuration."), $info['field'], $info['name']).'<br />'.
181 181
                     sprintf(_("The file %s should contain a %s setting."),
182
-                            $GLOBALS['registry']->get('fileroot') . '/config/' . $info['file'],
182
+                            $GLOBALS['registry']->get('fileroot').'/config/'.$info['file'],
183 183
                             sprintf("%s['%s']['params']['%s']", $info['variable'], $info['driver'], $info['field']));
184 184
                 break;
185 185
 
@@ -188,21 +188,21 @@  discard block
 block discarded – undo
188 188
                 break;
189 189
             }
190 190
 
191
-            $errortext .= '<h3>' . htmlspecialchars($message) . '</h3>';
191
+            $errortext .= '<h3>'.htmlspecialchars($message).'</h3>';
192 192
         } elseif (is_object($error) && method_exists($error, 'getMessage')) {
193
-            $errortext .= '<h3>' . htmlspecialchars($error->getMessage()) . '</h3>';
193
+            $errortext .= '<h3>'.htmlspecialchars($error->getMessage()).'</h3>';
194 194
         } elseif (is_string($error)) {
195
-            $errortext .= '<h3>' . $error . '</h3>';
195
+            $errortext .= '<h3>'.$error.'</h3>';
196 196
         }
197 197
 
198 198
         if ($admin) {
199
-            $errortext .= '<p><code>' . sprintf(_("[line %s of %s]"), $line, $file) . '</code></p>';
199
+            $errortext .= '<p><code>'.sprintf(_("[line %s of %s]"), $line, $file).'</code></p>';
200 200
             if (is_object($error)) {
201
-                $errortext .= '<h3>' . _("Details (also in Horde's logfile):") . '</h3>';
202
-                $errortext .= '<p><pre>' . htmlspecialchars(Util::bufferOutput('var_dump', $error)) . '</pre></p>';
201
+                $errortext .= '<h3>'._("Details (also in Horde's logfile):").'</h3>';
202
+                $errortext .= '<p><pre>'.htmlspecialchars(Util::bufferOutput('var_dump', $error)).'</pre></p>';
203 203
             }
204 204
         } elseif ($log) {
205
-            $errortext .= '<h3>' . _("Details have been logged for the administrator.") . '</h3>';
205
+            $errortext .= '<h3>'._("Details have been logged for the administrator.").'</h3>';
206 206
         }
207 207
 
208 208
         // Log the error via Horde::logMessage() if requested.
@@ -252,13 +252,13 @@  discard block
 block discarded – undo
252 252
 
253 253
         if (ob_get_length() || headers_sent()) {
254 254
             if ($direct) {
255
-                $url = Horde::url($file{0} == '/' ? $registry->get('webroot', $app) . $file : $registry->get('jsuri', $app) . '/' . $file);
255
+                $url = Horde::url($file{0} == '/' ? $registry->get('webroot', $app).$file : $registry->get('jsuri', $app).'/'.$file);
256 256
             } else {
257
-                $url = Horde::url($registry->get('webroot', 'horde') . '/services/javascript.php');
257
+                $url = Horde::url($registry->get('webroot', 'horde').'/services/javascript.php');
258 258
                 $url = Util::addParameter($url, array('file' => $file,
259 259
                                                       'app'  => $app));
260 260
             }
261
-            echo '<script language="JavaScript" type="text/javascript" src="' . $url . '"></script>';
261
+            echo '<script language="JavaScript" type="text/javascript" src="'.$url.'"></script>';
262 262
         } else {
263 263
             global $_horde_script_files;
264 264
             $_horde_script_files[$app][] = array($file, $direct);
@@ -275,16 +275,16 @@  discard block
 block discarded – undo
275 275
         global $_horde_script_files, $registry;
276 276
 
277 277
         if (!empty($_horde_script_files)) {
278
-            $base_url = Horde::url($registry->get('webroot', 'horde') . '/services/javascript.php');
278
+            $base_url = Horde::url($registry->get('webroot', 'horde').'/services/javascript.php');
279 279
             foreach ($_horde_script_files as $app => $files) {
280 280
                 foreach ($files as $file) {
281 281
                     if (!empty($file[1])) {
282
-                        $url = $file[0]{0} == '/' ? $registry->get('webroot', $app) . $file[0] : $registry->get('jsuri', $app) . '/' . $file[0];
283
-                        echo '<script language="JavaScript" type="text/javascript" src="' . Horde::url($url) . "\"></script>\n";
282
+                        $url = $file[0]{0} == '/' ? $registry->get('webroot', $app).$file[0] : $registry->get('jsuri', $app).'/'.$file[0];
283
+                        echo '<script language="JavaScript" type="text/javascript" src="'.Horde::url($url)."\"></script>\n";
284 284
                     } else {
285 285
                         $url = Util::addParameter($base_url, array('file' => $file[0],
286 286
                                                                    'app'  => $app));
287
-                        echo '<script language="JavaScript" type="text/javascript" src="' . $url . "\"></script>\n";
287
+                        echo '<script language="JavaScript" type="text/javascript" src="'.$url."\"></script>\n";
288 288
                     }
289 289
                 }
290 290
             }
@@ -301,11 +301,11 @@  discard block
 block discarded – undo
301 301
         global $_horde_script_files, $registry;
302 302
 
303 303
         if (!empty($_horde_script_files)) {
304
-            $jsWrapper = $registry->get('fileroot', 'horde') . '/services/javascript.php';
304
+            $jsWrapper = $registry->get('fileroot', 'horde').'/services/javascript.php';
305 305
             foreach ($_horde_script_files as $app => $files) {
306 306
                 foreach ($files as $file) {
307 307
                     if (!empty($file[1])) {
308
-                        @readfile($file[0]{0} == '/' ? $registry->get('fileroot', $app) . $file[0] : $registry->get('jsfs', $app) . '/' . $file[0]);
308
+                        @readfile($file[0]{0} == '/' ? $registry->get('fileroot', $app).$file[0] : $registry->get('jsfs', $app).'/'.$file[0]);
309 309
                     } else {
310 310
                         $file = $file[0];
311 311
                         require $jsWrapper;
@@ -339,17 +339,17 @@  discard block
 block discarded – undo
339 339
                 Horde::addScriptFile('open_help_win.js', 'horde');
340 340
                 return "javascript:open_help_win('$app');";
341 341
             } else {
342
-                $url = Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/help/', true);
342
+                $url = Horde::url($GLOBALS['registry']->get('webroot', 'horde').'/services/help/', true);
343 343
                 return Util::addParameter($url, array('module' => $app,
344 344
                                                       'show' => 'topics'));
345 345
             }
346 346
             break;
347 347
 
348 348
         case 'problem':
349
-            return Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/problem.php?return_url=' . urlencode(Horde::selfUrl(true)));
349
+            return Horde::url($GLOBALS['registry']->get('webroot', 'horde').'/services/problem.php?return_url='.urlencode(Horde::selfUrl(true)));
350 350
 
351 351
         case 'logout':
352
-            return Auth::addLogoutParameters(Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/login.php'), AUTH_REASON_LOGOUT);
352
+            return Auth::addLogoutParameters(Horde::url($GLOBALS['registry']->get('webroot', 'horde').'/login.php'), AUTH_REASON_LOGOUT);
353 353
 
354 354
         case 'login':
355 355
             return Auth::getLoginScreen('', $referrer ? Horde::selfUrl(true) : null);
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
         case 'options':
358 358
             global $conf;
359 359
             if (($conf['prefs']['driver'] != '') && ($conf['prefs']['driver'] != 'none')) {
360
-                return Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/prefs.php?app=' . $app);
360
+                return Horde::url($GLOBALS['registry']->get('webroot', 'horde').'/services/prefs.php?app='.$app);
361 361
             }
362 362
             break;
363 363
         }
@@ -490,9 +490,9 @@  discard block
 block discarded – undo
490 490
 
491 491
         if (!is_array($params) || !count($params)) {
492 492
             Horde::fatal(PEAR::raiseError(
493
-                sprintf(_("No configuration information specified for %s."), $name) . "\n\n" .
493
+                sprintf(_("No configuration information specified for %s."), $name)."\n\n".
494 494
                 sprintf(_("The file %s should contain some %s settings."),
495
-                    $fileroot . '/config/' . $file,
495
+                    $fileroot.'/config/'.$file,
496 496
                     sprintf("%s['%s']['params']", $variable, $driver))),
497 497
                 __FILE__, __LINE__);
498 498
         }
@@ -500,9 +500,9 @@  discard block
 block discarded – undo
500 500
         foreach ($fields as $field) {
501 501
             if (!isset($params[$field])) {
502 502
                 Horde::fatal(PEAR::raiseError(
503
-                    sprintf(_("Required '%s' not specified in %s configuration."), $field, $name) . "\n\n" .
503
+                    sprintf(_("Required '%s' not specified in %s configuration."), $field, $name)."\n\n".
504 504
                     sprintf(_("The file %s should contain a %s setting."),
505
-                        $fileroot . '/config/' . $file,
505
+                        $fileroot.'/config/'.$file,
506 506
                         sprintf("%s['%s']['params']['%s']", $variable, $driver, $field))),
507 507
                     __FILE__, __LINE__);
508 508
             }
@@ -552,18 +552,18 @@  discard block
 block discarded – undo
552 552
             if (!empty($server_port) &&
553 553
                 ((($protocol == 'http') && ($server_port != 80)) ||
554 554
                  (($protocol == 'https') && ($server_port != 443)))) {
555
-                $server_name .= ':' . $server_port;
555
+                $server_name .= ':'.$server_port;
556 556
             }
557 557
 
558 558
             /* Store the webroot in a local variable. */
559 559
             $webroot = $registry->get('webroot');
560 560
 
561
-            $url = $protocol . '://' . $server_name;
561
+            $url = $protocol.'://'.$server_name;
562 562
             if (substr($uri, 0, 1) != '/') {
563 563
                 if (substr($webroot, -1) == '/') {
564
-                    $url .= $webroot . $uri;
564
+                    $url .= $webroot.$uri;
565 565
                 } else {
566
-                    $url .= $webroot . '/' . $uri;
566
+                    $url .= $webroot.'/'.$uri;
567 567
                 }
568 568
             } else {
569 569
                 $url .= $uri;
@@ -613,9 +613,9 @@  discard block
 block discarded – undo
613 613
         if ($full) {
614 614
             return Horde::url($uri, $full, $append_session);
615 615
         } elseif (substr($webroot, -1) == '/') {
616
-            return Horde::url($webroot . $uri, $full, $append_session);
616
+            return Horde::url($webroot.$uri, $full, $append_session);
617 617
         } else {
618
-            return Horde::url($webroot . '/' . $uri, $full, $append_session);
618
+            return Horde::url($webroot.'/'.$uri, $full, $append_session);
619 619
         }
620 620
     }
621 621
 
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
      */
632 632
     function externalUrl($url, $tag = false)
633 633
     {
634
-        $ext = Horde::url($GLOBALS['registry']->get('webroot', 'horde') .
634
+        $ext = Horde::url($GLOBALS['registry']->get('webroot', 'horde').
635 635
                           '/services/go.php', true, -1);
636 636
 
637 637
         /* We must make sure there are no &amp's in the URL. */
@@ -665,7 +665,7 @@  discard block
 block discarded – undo
665 665
 
666 666
         if (is_null($url)) {
667 667
             global $registry;
668
-            $url = Util::addParameter(Horde::url($registry->get('webroot', 'horde') . '/services/download/'), 'module', $registry->getApp());
668
+            $url = Util::addParameter(Horde::url($registry->get('webroot', 'horde').'/services/download/'), 'module', $registry->getApp());
669 669
             $horde_url = true;
670 670
         }
671 671
 
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
          * many browsers, this should allow every browser to download
682 682
          * correctly. */
683 683
         if ($horde_url) {
684
-            $url = Util::addParameter($url, 'fn=/' . rawurlencode($filename));
684
+            $url = Util::addParameter($url, 'fn=/'.rawurlencode($filename));
685 685
         } elseif ($browser->hasQuirk('break_disposition_filename')) {
686 686
             /* Some browsers will only obtain the filename correctly
687 687
              * if the extension is the last argument in the query
@@ -698,16 +698,16 @@  discard block
 block discarded – undo
698 698
              * functionality. */
699 699
             if (($server != 'apache2')) {
700 700
                 if (($pos = strrpos($filename, '.'))) {
701
-                    $name = '/' . preg_replace('/\./', '%2E', substr($filename, 0, $pos));
701
+                    $name = '/'.preg_replace('/\./', '%2E', substr($filename, 0, $pos));
702 702
                     $ext = substr($filename, $pos);
703 703
                 } else {
704
-                    $name = '/' . $filename;
704
+                    $name = '/'.$filename;
705 705
                     $ext = '';
706 706
                 }
707 707
 
708 708
                 /* Enter the PATH_INFO information. */
709 709
                 if (($pos = strpos($url, '?'))) {
710
-                    $url = substr($url, 0, $pos) . $name . substr($url, $pos);
710
+                    $url = substr($url, 0, $pos).$name.substr($url, $pos);
711 711
                 } else {
712 712
                     $url .= $name;
713 713
                 }
@@ -715,7 +715,7 @@  discard block
 block discarded – undo
715 715
 
716 716
             /* Append the extension, if it exists. */
717 717
             if (($server == 'apache2') || !empty($ext)) {
718
-                $url = Util::addParameter($url, 'fn_ext=/' . $filename);
718
+                $url = Util::addParameter($url, 'fn_ext=/'.$filename);
719 719
             }
720 720
         }
721 721
 
@@ -747,7 +747,7 @@  discard block
 block discarded – undo
747 747
             $ret .= " onclick=\"$onclick\"";
748 748
         }
749 749
         if (!empty($status)) {
750
-            $ret .= ' onmouseout="window.status=\'\';" onmouseover="window.status=\'' . @htmlspecialchars(strtr(addslashes($status), array("\r" => '', "\n" => '')), ENT_QUOTES, NLS::getCharset()) . '\'; return true;"';
750
+            $ret .= ' onmouseout="window.status=\'\';" onmouseover="window.status=\''.@htmlspecialchars(strtr(addslashes($status), array("\r" => '', "\n" => '')), ENT_QUOTES, NLS::getCharset()).'\'; return true;"';
751 751
         }
752 752
         if (!empty($class)) {
753 753
             $ret .= " class=\"$class\"";
@@ -756,14 +756,14 @@  discard block
 block discarded – undo
756 756
             $ret .= " target=\"$target\"";
757 757
         }
758 758
         if (!empty($title)) {
759
-            $ret .= ' title="' . @htmlspecialchars($title, ENT_QUOTES, NLS::getCharset()) . '"';
759
+            $ret .= ' title="'.@htmlspecialchars($title, ENT_QUOTES, NLS::getCharset()).'"';
760 760
         }
761 761
         if (!empty($accesskey)) {
762
-            $ret .= ' accesskey="' . htmlspecialchars($accesskey) . '"';
762
+            $ret .= ' accesskey="'.htmlspecialchars($accesskey).'"';
763 763
         }
764 764
 
765 765
         foreach ($attributes as $name => $value) {
766
-            $ret .= ' ' . htmlspecialchars($name) . '="' . htmlspecialchars($value) . '"';
766
+            $ret .= ' '.htmlspecialchars($name).'="'.htmlspecialchars($value).'"';
767 767
         }
768 768
 
769 769
         return "$ret>";
@@ -792,7 +792,7 @@  discard block
 block discarded – undo
792 792
         $ak = Horde::getAccessKey($title, $nocheck);
793 793
         $plaintitle = Horde::stripAccessKey($title);
794 794
 
795
-        return Horde::link($url, $status, $class, $target, $onclick, $plaintitle, $ak) . Horde::highlightAccessKey($title, $ak) . '</a>';
795
+        return Horde::link($url, $status, $class, $target, $onclick, $plaintitle, $ak).Horde::highlightAccessKey($title, $ak).'</a>';
796 796
     }
797 797
 
798 798
     /**
@@ -812,7 +812,7 @@  discard block
 block discarded – undo
812 812
         $url = $_SERVER['PHP_SELF'];
813 813
 
814 814
         if ($query_string && !empty($_SERVER['QUERY_STRING'])) {
815
-            $url .= '?' . $_SERVER['QUERY_STRING'];
815
+            $url .= '?'.$_SERVER['QUERY_STRING'];
816 816
         }
817 817
 
818 818
         $url = Horde::url($url, $full, 0, $force_ssl);
@@ -853,7 +853,7 @@  discard block
 block discarded – undo
853 853
 
854 854
         /* If a directory has been provided, prepend it to the image source. */
855 855
         if (!empty($dir)) {
856
-            $src = $dir . '/' . $src;
856
+            $src = $dir.'/'.$src;
857 857
         }
858 858
 
859 859
         /* Build all of the tag attributes. */
@@ -866,16 +866,16 @@  discard block
 block discarded – undo
866 866
 
867 867
         $img = '<img';
868 868
         foreach ($attributes as $attribute => $value) {
869
-            $img .= ' ' . $attribute . '="' . ($attribute == 'src' ? $value : @htmlspecialchars($value, ENT_COMPAT, NLS::getCharset())) . '"';
869
+            $img .= ' '.$attribute.'="'.($attribute == 'src' ? $value : @htmlspecialchars($value, ENT_COMPAT, NLS::getCharset())).'"';
870 870
         }
871 871
 
872 872
         /* If the user supplied a pre-built string of attributes, add that. */
873 873
         if (is_string($attr) && !empty($attr)) {
874
-            $img .= ' ' . $attr;
874
+            $img .= ' '.$attr;
875 875
         }
876 876
 
877 877
         /* Return the closed image tag. */
878
-        return $img . ' />';
878
+        return $img.' />';
879 879
     }
880 880
 
881 881
     /**
@@ -1046,10 +1046,10 @@  discard block
 block discarded – undo
1046 1046
         $themes_fs = $GLOBALS['registry']->get('themesfs', 'horde');
1047 1047
         if ($inherit) {
1048 1048
             $themes_uri = Horde::url($GLOBALS['registry']->get('themesuri', 'horde'), false, -1);
1049
-            $css[] = $themes_uri . '/screen.css';
1049
+            $css[] = $themes_uri.'/screen.css';
1050 1050
             if (!empty($theme) &&
1051
-                file_exists($themes_fs . '/' . $theme . '/screen.css')) {
1052
-                $css[] = $themes_uri . '/' . $theme . '/screen.css';
1051
+                file_exists($themes_fs.'/'.$theme.'/screen.css')) {
1052
+                $css[] = $themes_uri.'/'.$theme.'/screen.css';
1053 1053
             }
1054 1054
         }
1055 1055
 
@@ -1063,41 +1063,41 @@  discard block
 block discarded – undo
1063 1063
                 }
1064 1064
 
1065 1065
                 $themes_fs = $GLOBALS['registry']->get('themesfs', $app);
1066
-                if (file_exists($themes_fs . '/screen.css')) {
1066
+                if (file_exists($themes_fs.'/screen.css')) {
1067 1067
                     $themes_uri = Horde::url($GLOBALS['registry']->get('themesuri', $app), false, -1);
1068
-                    $css[] = $themes_uri . '/screen.css';
1068
+                    $css[] = $themes_uri.'/screen.css';
1069 1069
                 }
1070 1070
                 if (!empty($theme) &&
1071
-                    file_exists($themes_fs . '/' . $theme . '/screen.css')) {
1072
-                    $css[] = $themes_uri . '/' . $theme . '/screen.css';
1071
+                    file_exists($themes_fs.'/'.$theme.'/screen.css')) {
1072
+                    $css[] = $themes_uri.'/'.$theme.'/screen.css';
1073 1073
                 }
1074 1074
             }
1075 1075
         }
1076 1076
 
1077 1077
         $html = '';
1078 1078
         foreach ($css as $css_link) {
1079
-            $html .= '<link href="' . $css_link . '" rel="stylesheet" type="text/css" />' . "\n";
1079
+            $html .= '<link href="'.$css_link.'" rel="stylesheet" type="text/css" />'."\n";
1080 1080
         }
1081 1081
 
1082 1082
         /* Load IE PNG transparency code if needed. */
1083 1083
         if ($GLOBALS['browser']->hasQuirk('png_transparency') &&
1084 1084
             $GLOBALS['prefs']->getValue('alpha_filter')) {
1085
-            $url = Horde::url($GLOBALS['registry']->get('jsuri', 'horde') . '/alphaImageLoader.php', true, -1);
1086
-            $html .= '<style type="text/css"> img { behavior: url("' . $url . '"); } </style>';
1085
+            $url = Horde::url($GLOBALS['registry']->get('jsuri', 'horde').'/alphaImageLoader.php', true, -1);
1086
+            $html .= '<style type="text/css"> img { behavior: url("'.$url.'"); } </style>';
1087 1087
         }
1088 1088
 
1089 1089
         /* Load browser specific stylesheets if needed. */
1090 1090
         if ($GLOBALS['browser']->isBrowser('msie')) {
1091
-            $html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/ie.css" rel="stylesheet" type="text/css" />' . "\n";
1091
+            $html .= '<link href="'.$GLOBALS['registry']->get('themesuri', 'horde').'/ie.css" rel="stylesheet" type="text/css" />'."\n";
1092 1092
             if ($GLOBALS['browser']->getPlatform() == 'mac') {
1093
-                $html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/ie5mac.css" rel="stylesheet" type="text/css" />' . "\n";
1093
+                $html .= '<link href="'.$GLOBALS['registry']->get('themesuri', 'horde').'/ie5mac.css" rel="stylesheet" type="text/css" />'."\n";
1094 1094
             }
1095 1095
         }
1096 1096
         if ($GLOBALS['browser']->isBrowser('opera')) {
1097
-            $html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/opera.css" rel="stylesheet" type="text/css" />' . "\n";
1097
+            $html .= '<link href="'.$GLOBALS['registry']->get('themesuri', 'horde').'/opera.css" rel="stylesheet" type="text/css" />'."\n";
1098 1098
         }
1099 1099
         if (strpos(strtolower($GLOBALS['browser']->getAgentString()), 'safari') !== false) {
1100
-            $html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/safari.css" rel="stylesheet" type="text/css" />' . "\n";
1100
+            $html .= '<link href="'.$GLOBALS['registry']->get('themesuri', 'horde').'/safari.css" rel="stylesheet" type="text/css" />'."\n";
1101 1101
         }
1102 1102
 
1103 1103
         return $html;
@@ -1178,10 +1178,10 @@  discard block
 block discarded – undo
1178 1178
             $used = array_keys($_used);
1179 1179
             sort($used);
1180 1180
             $remaining = str_replace($used, array(), 'abcdefghijklmnopqrstuvwxyz');
1181
-            Horde::logMessage('Access key information for ' . $script, __FILE__, __LINE__);
1182
-            Horde::logMessage('Used labels: ' . implode(',', $labels), __FILE__, __LINE__);
1183
-            Horde::logMessage('Used keys: ' . implode('', $used), __FILE__, __LINE__);
1184
-            Horde::logMessage('Free keys: ' . $remaining, __FILE__, __LINE__);
1181
+            Horde::logMessage('Access key information for '.$script, __FILE__, __LINE__);
1182
+            Horde::logMessage('Used labels: '.implode(',', $labels), __FILE__, __LINE__);
1183
+            Horde::logMessage('Used keys: '.implode('', $used), __FILE__, __LINE__);
1184
+            Horde::logMessage('Free keys: '.$remaining, __FILE__, __LINE__);
1185 1185
             return;
1186 1186
         }
1187 1187
 
@@ -1223,7 +1223,7 @@  discard block
 block discarded – undo
1223 1223
      */
1224 1224
     function stripAccessKey($label)
1225 1225
     {
1226
-        include_once HORDE_BASE . '/config/nls.php';
1226
+        include_once HORDE_BASE.'/config/nls.php';
1227 1227
         $multibyte = isset($GLOBALS['nls']['multibyte'][NLS::getCharset(true)]);
1228 1228
 
1229 1229
         return preg_replace('/_([A-Za-z])/',
@@ -1251,10 +1251,10 @@  discard block
 block discarded – undo
1251 1251
         }
1252 1252
 
1253 1253
         if (isset($GLOBALS['nls']['multibyte'][NLS::getCharset(true)])) {
1254
-            return $stripped_label . '(' . '<span class="accessKey">' .
1255
-                strtoupper($accessKey) . '</span>' . ')';
1254
+            return $stripped_label.'('.'<span class="accessKey">'.
1255
+                strtoupper($accessKey).'</span>'.')';
1256 1256
         } else {
1257
-            return str_replace('_' . $accessKey, '<span class="accessKey">' . $accessKey . '</span>', $label);
1257
+            return str_replace('_'.$accessKey, '<span class="accessKey">'.$accessKey.'</span>', $label);
1258 1258
         }
1259 1259
     }
1260 1260
 
@@ -1272,10 +1272,10 @@  discard block
 block discarded – undo
1272 1272
     function getAccessKeyAndTitle($label, $nocheck = false)
1273 1273
     {
1274 1274
         $ak = Horde::getAccessKey($label, $nocheck);
1275
-        $attributes = 'title="' . Horde::stripAccessKey($label);
1275
+        $attributes = 'title="'.Horde::stripAccessKey($label);
1276 1276
         if (!empty($ak)) {
1277 1277
             $attributes .= sprintf(_(" (Accesskey %s)"), $ak);
1278
-            $attributes .= '" accesskey="' . $ak;
1278
+            $attributes .= '" accesskey="'.$ak;
1279 1279
         }
1280 1280
         $attributes .= '"';
1281 1281
         return $attributes;
@@ -1303,7 +1303,7 @@  discard block
 block discarded – undo
1303 1303
 
1304 1304
         return sprintf('<label for="%s"%s>%s</label>',
1305 1305
                        $for,
1306
-                       !empty($ak) ? ' accesskey="' . $ak . '"' : '',
1306
+                       !empty($ak) ? ' accesskey="'.$ak.'"' : '',
1307 1307
                        $label);
1308 1308
     }
1309 1309
 
@@ -1320,10 +1320,10 @@  discard block
 block discarded – undo
1320 1320
             $cli->fatal(_("You are not authenticated."));
1321 1321
         }
1322 1322
 
1323
-        $url = $GLOBALS['registry']->get('webroot', 'horde') . '/login.php';
1323
+        $url = $GLOBALS['registry']->get('webroot', 'horde').'/login.php';
1324 1324
         $url = Util::addParameter($url, 'url', Horde::selfUrl(true));
1325 1325
         $url = Auth::addLogoutParameters($url);
1326
-        header('Location: ' . Horde::url($url, true));
1326
+        header('Location: '.Horde::url($url, true));
1327 1327
         exit;
1328 1328
     }
1329 1329
 
@@ -1362,8 +1362,8 @@  discard block
 block discarded – undo
1362 1362
         if (strlen($title)) {
1363 1363
             require_once 'Horde/Text/Filter.php';
1364 1364
             $title = Text_Filter::filter($title, 'text2html', array('parselevel' => TEXT_HTML_NOHTML, 'charset' => '', 'class' => ''));
1365
-            $title = '<pre style="margin:0px;">' . strtr(addslashes($title), array("\r" => '', "\n" => '')) . '</pre>';
1366
-            $url .= ' onmouseover="tooltipLink(\'' . @htmlspecialchars($title, ENT_QUOTES, NLS::getCharset()) . '\', \'' . $status . '\'); return true;" onmouseout="tooltipClose();"';
1365
+            $title = '<pre style="margin:0px;">'.strtr(addslashes($title), array("\r" => '', "\n" => '')).'</pre>';
1366
+            $url .= ' onmouseover="tooltipLink(\''.@htmlspecialchars($title, ENT_QUOTES, NLS::getCharset()).'\', \''.$status.'\'); return true;" onmouseout="tooltipClose();"';
1367 1367
         }
1368 1368
         $url .= '>';
1369 1369
 
@@ -1396,8 +1396,8 @@  discard block
 block discarded – undo
1396 1396
         static $hooks_loaded;
1397 1397
 
1398 1398
         if (!isset($hooks_loaded)) {
1399
-            if (file_exists($registry->get('fileroot', $app) . '/config/hooks.php')) {
1400
-                require_once $registry->get('fileroot', $app) . '/config/hooks.php';
1399
+            if (file_exists($registry->get('fileroot', $app).'/config/hooks.php')) {
1400
+                require_once $registry->get('fileroot', $app).'/config/hooks.php';
1401 1401
                 $hooks_loaded = true;
1402 1402
             } else {
1403 1403
                 $hooks_loaded = false;
Please login to merge, or discard this patch.
Braces   +364 added lines, -164 removed lines patch added patch discarded remove patch
@@ -20,7 +20,8 @@  discard block
 block discarded – undo
20 20
  * @since   Horde 1.3
21 21
  * @package Horde_Framework
22 22
  */
23
-class Horde {
23
+class Horde
24
+{
24 25
 
25 26
     /**
26 27
      * Logs a message to the global Horde log backend.
@@ -48,29 +49,37 @@  discard block
 block discarded – undo
48 49
     {
49 50
         global $conf;
50 51
 
51
-        if (!$conf['log']['enabled']) {
52
+        if (!$conf['log']['enabled'])
53
+        {
52 54
             return;
53 55
         }
54 56
 
55
-        if ($priority > $conf['log']['priority']) {
57
+        if ($priority > $conf['log']['priority'])
58
+        {
56 59
             return;
57 60
         }
58 61
 
59 62
         $logger = &Horde::getLogger();
60
-        if (!is_a($logger, 'Log')) {
63
+        if (!is_a($logger, 'Log'))
64
+        {
61 65
             Horde::fatal(PEAR::raiseError('An error has occurred. Furthermore, Horde encountered an error attempting to log this error. Please check your Horde logging configuration in horde/config/conf.php.'), __FILE__, __LINE__, false);
62 66
         }
63 67
 
64
-        if (is_a($message, 'PEAR_Error')) {
68
+        if (is_a($message, 'PEAR_Error'))
69
+        {
65 70
             $userinfo = $message->getUserInfo();
66 71
             $message = $message->getMessage();
67
-            if (!empty($userinfo)) {
68
-                if (is_array($userinfo)) {
72
+            if (!empty($userinfo))
73
+            {
74
+                if (is_array($userinfo))
75
+                {
69 76
                     $userinfo = implode(', ', $userinfo);
70 77
                 }
71 78
                 $message .= ': ' . $userinfo;
72 79
             }
73
-        } elseif (is_callable(array($message, 'getMessage'))) {
80
+        }
81
+        elseif (is_callable(array($message, 'getMessage')))
82
+        {
74 83
             $message = $message->getMessage();
75 84
         }
76 85
 
@@ -93,18 +102,21 @@  discard block
 block discarded – undo
93 102
     {
94 103
         global $conf;
95 104
 
96
-        if (empty($conf['log']['enabled'])) {
105
+        if (empty($conf['log']['enabled']))
106
+        {
97 107
             return false;
98 108
         }
99 109
 
100 110
         static $logcheck;
101
-        if (!isset($logcheck)) {
111
+        if (!isset($logcheck))
112
+        {
102 113
             // Try to make sure that we can log messages somehow.
103 114
             if (empty($conf['log']) ||
104 115
                 empty($conf['log']['type']) ||
105 116
                 empty($conf['log']['name']) ||
106 117
                 empty($conf['log']['ident']) ||
107
-                !isset($conf['log']['params'])) {
118
+                !isset($conf['log']['params']))
119
+            {
108 120
                 Horde::fatal(PEAR::raiseError('Horde is not correctly configured to log error messages. You must configure at least a text file log in horde/config/conf.php.'), __FILE__, __LINE__, false);
109 121
             }
110 122
             $logcheck = true;
@@ -125,14 +137,20 @@  discard block
 block discarded – undo
125 137
     {
126 138
         // Make sure to force a completely new session ID and clear
127 139
         // all session data.
128
-        if (version_compare(phpversion(), '4.3.3') !== -1) {
140
+        if (version_compare(phpversion(), '4.3.3') !== -1)
141
+        {
129 142
             session_regenerate_id();
130 143
             session_unset();
131
-        } else {
144
+        }
145
+        else
146
+        {
132 147
             @session_destroy();
133
-            if (Util::extensionExists('posix')) {
148
+            if (Util::extensionExists('posix'))
149
+            {
134 150
                 $new_session_id = md5(microtime() . posix_getpid());
135
-            } else {
151
+            }
152
+            else
153
+            {
136 154
                 $new_session_id = md5(uniqid(mt_rand(), true));
137 155
             }
138 156
             session_id($new_session_id);
@@ -164,11 +182,13 @@  discard block
 block discarded – undo
164 182
         $cli = class_exists('Horde_CLI') && Horde_CLI::runningFromCLI();
165 183
 
166 184
         $errortext = '<h1>' . _("A fatal error has occurred") . '</h1>';
167
-        if (is_a($error, 'PEAR_Error')) {
185
+        if (is_a($error, 'PEAR_Error'))
186
+        {
168 187
             $info = array_merge(array('file' => 'conf.php', 'variable' => '$conf'),
169 188
                                 array($error->getUserInfo()));
170 189
 
171
-            switch ($error->getCode()) {
190
+            switch ($error->getCode())
191
+            {
172 192
             case HORDE_ERROR_DRIVER_CONFIG_MISSING:
173 193
                 $message = sprintf(_("No configuration information specified for %s."), $info['name']) . '<br />' .
174 194
                     sprintf(_("The file %s should contain some %s settings."),
@@ -189,30 +209,42 @@  discard block
 block discarded – undo
189 209
             }
190 210
 
191 211
             $errortext .= '<h3>' . htmlspecialchars($message) . '</h3>';
192
-        } elseif (is_object($error) && method_exists($error, 'getMessage')) {
212
+        }
213
+        elseif (is_object($error) && method_exists($error, 'getMessage'))
214
+        {
193 215
             $errortext .= '<h3>' . htmlspecialchars($error->getMessage()) . '</h3>';
194
-        } elseif (is_string($error)) {
216
+        }
217
+        elseif (is_string($error))
218
+        {
195 219
             $errortext .= '<h3>' . $error . '</h3>';
196 220
         }
197 221
 
198
-        if ($admin) {
222
+        if ($admin)
223
+        {
199 224
             $errortext .= '<p><code>' . sprintf(_("[line %s of %s]"), $line, $file) . '</code></p>';
200
-            if (is_object($error)) {
225
+            if (is_object($error))
226
+            {
201 227
                 $errortext .= '<h3>' . _("Details (also in Horde's logfile):") . '</h3>';
202 228
                 $errortext .= '<p><pre>' . htmlspecialchars(Util::bufferOutput('var_dump', $error)) . '</pre></p>';
203 229
             }
204
-        } elseif ($log) {
230
+        }
231
+        elseif ($log)
232
+        {
205 233
             $errortext .= '<h3>' . _("Details have been logged for the administrator.") . '</h3>';
206 234
         }
207 235
 
208 236
         // Log the error via Horde::logMessage() if requested.
209
-        if ($log) {
237
+        if ($log)
238
+        {
210 239
             Horde::logMessage($error, $file, $line, PEAR_LOG_EMERG);
211 240
         }
212 241
 
213
-        if ($cli) {
242
+        if ($cli)
243
+        {
214 244
             echo strip_tags(str_replace(array('<br />', '<p>', '</p>', '<h1>', '</h1>', '<h3>', '</h3>'), "\n", $errortext));
215
-        } else {
245
+        }
246
+        else
247
+        {
216 248
             echo <<< HTML
217 249
 <html>
218 250
 <head><title>Horde :: Fatal Error</title></head>
@@ -240,26 +272,34 @@  discard block
 block discarded – undo
240 272
         global $registry;
241 273
         static $included = array();
242 274
 
243
-        if (empty($app)) {
275
+        if (empty($app))
276
+        {
244 277
             $app = $registry->getApp();
245 278
         }
246 279
 
247 280
         // Don't include scripts multiple times.
248
-        if (!empty($included[$app][$file])) {
281
+        if (!empty($included[$app][$file]))
282
+        {
249 283
             return;
250 284
         }
251 285
         $included[$app][$file] = true;
252 286
 
253
-        if (ob_get_length() || headers_sent()) {
254
-            if ($direct) {
287
+        if (ob_get_length() || headers_sent())
288
+        {
289
+            if ($direct)
290
+            {
255 291
                 $url = Horde::url($file{0} == '/' ? $registry->get('webroot', $app) . $file : $registry->get('jsuri', $app) . '/' . $file);
256
-            } else {
292
+            }
293
+            else
294
+            {
257 295
                 $url = Horde::url($registry->get('webroot', 'horde') . '/services/javascript.php');
258 296
                 $url = Util::addParameter($url, array('file' => $file,
259 297
                                                       'app'  => $app));
260 298
             }
261 299
             echo '<script language="JavaScript" type="text/javascript" src="' . $url . '"></script>';
262
-        } else {
300
+        }
301
+        else
302
+        {
263 303
             global $_horde_script_files;
264 304
             $_horde_script_files[$app][] = array($file, $direct);
265 305
         }
@@ -274,14 +314,20 @@  discard block
 block discarded – undo
274 314
     {
275 315
         global $_horde_script_files, $registry;
276 316
 
277
-        if (!empty($_horde_script_files)) {
317
+        if (!empty($_horde_script_files))
318
+        {
278 319
             $base_url = Horde::url($registry->get('webroot', 'horde') . '/services/javascript.php');
279
-            foreach ($_horde_script_files as $app => $files) {
280
-                foreach ($files as $file) {
281
-                    if (!empty($file[1])) {
320
+            foreach ($_horde_script_files as $app => $files)
321
+            {
322
+                foreach ($files as $file)
323
+                {
324
+                    if (!empty($file[1]))
325
+                    {
282 326
                         $url = $file[0]{0} == '/' ? $registry->get('webroot', $app) . $file[0] : $registry->get('jsuri', $app) . '/' . $file[0];
283 327
                         echo '<script language="JavaScript" type="text/javascript" src="' . Horde::url($url) . "\"></script>\n";
284
-                    } else {
328
+                    }
329
+                    else
330
+                    {
285 331
                         $url = Util::addParameter($base_url, array('file' => $file[0],
286 332
                                                                    'app'  => $app));
287 333
                         echo '<script language="JavaScript" type="text/javascript" src="' . $url . "\"></script>\n";
@@ -300,13 +346,19 @@  discard block
 block discarded – undo
300 346
     {
301 347
         global $_horde_script_files, $registry;
302 348
 
303
-        if (!empty($_horde_script_files)) {
349
+        if (!empty($_horde_script_files))
350
+        {
304 351
             $jsWrapper = $registry->get('fileroot', 'horde') . '/services/javascript.php';
305
-            foreach ($_horde_script_files as $app => $files) {
306
-                foreach ($files as $file) {
307
-                    if (!empty($file[1])) {
352
+            foreach ($_horde_script_files as $app => $files)
353
+            {
354
+                foreach ($files as $file)
355
+                {
356
+                    if (!empty($file[1]))
357
+                    {
308 358
                         @readfile($file[0]{0} == '/' ? $registry->get('fileroot', $app) . $file[0] : $registry->get('jsfs', $app) . '/' . $file[0]);
309
-                    } else {
359
+                    }
360
+                    else
361
+                    {
310 362
                         $file = $file[0];
311 363
                         require $jsWrapper;
312 364
                     }
@@ -329,16 +381,21 @@  discard block
 block discarded – undo
329 381
      */
330 382
     function getServiceLink($type, $app, $override = false, $referrer = true)
331 383
     {
332
-        if (!Horde::showService($type) && !$override) {
384
+        if (!Horde::showService($type) && !$override)
385
+        {
333 386
             return false;
334 387
         }
335 388
 
336
-        switch ($type) {
389
+        switch ($type)
390
+        {
337 391
         case 'help':
338
-            if ($GLOBALS['browser']->hasFeature('javascript')) {
392
+            if ($GLOBALS['browser']->hasFeature('javascript'))
393
+            {
339 394
                 Horde::addScriptFile('open_help_win.js', 'horde');
340 395
                 return "javascript:open_help_win('$app');";
341
-            } else {
396
+            }
397
+            else
398
+            {
342 399
                 $url = Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/help/', true);
343 400
                 return Util::addParameter($url, array('module' => $app,
344 401
                                                       'show' => 'topics'));
@@ -356,7 +413,8 @@  discard block
 block discarded – undo
356 413
 
357 414
         case 'options':
358 415
             global $conf;
359
-            if (($conf['prefs']['driver'] != '') && ($conf['prefs']['driver'] != 'none')) {
416
+            if (($conf['prefs']['driver'] != '') && ($conf['prefs']['driver'] != 'none'))
417
+            {
360 418
                 return Horde::url($GLOBALS['registry']->get('webroot', 'horde') . '/services/prefs.php?app=' . $app);
361 419
             }
362 420
             break;
@@ -376,11 +434,13 @@  discard block
 block discarded – undo
376 434
     {
377 435
         global $conf;
378 436
 
379
-        if (empty($conf['menu']['links'][$type])) {
437
+        if (empty($conf['menu']['links'][$type]))
438
+        {
380 439
             return false;
381 440
         }
382 441
 
383
-        switch ($conf['menu']['links'][$type]) {
442
+        switch ($conf['menu']['links'][$type])
443
+        {
384 444
         case 'all':
385 445
             return true;
386 446
 
@@ -412,16 +472,23 @@  discard block
 block discarded – undo
412 472
         global $conf;
413 473
 
414 474
         $c = null;
415
-        if (is_array($backend)) {
475
+        if (is_array($backend))
476
+        {
416 477
             require_once 'Horde/Array.php';
417 478
             $c = Horde_Array::getElement($conf, $backend);
418
-        } elseif (isset($conf[$backend])) {
479
+        }
480
+        elseif (isset($conf[$backend]))
481
+        {
419 482
             $c = $conf[$backend];
420 483
         }
421
-        if (!is_null($c) && isset($c['params'])) {
422
-            if (isset($conf[$type])) {
484
+        if (!is_null($c) && isset($c['params']))
485
+        {
486
+            if (isset($conf[$type]))
487
+            {
423 488
                 return array_merge($conf[$type], $c['params']);
424
-            } else {
489
+            }
490
+            else
491
+            {
425 492
                 return $c['params'];
426 493
             }
427 494
         }
@@ -443,17 +510,22 @@  discard block
 block discarded – undo
443 510
     {
444 511
         global $conf;
445 512
 
446
-        if (!isset($conf[$name]['type'])) {
513
+        if (!isset($conf[$name]['type']))
514
+        {
447 515
             return PEAR::raiseError(_("You must configure a VFS backend."));
448 516
         }
449 517
 
450
-        if ($conf[$name]['type'] == 'horde') {
518
+        if ($conf[$name]['type'] == 'horde')
519
+        {
451 520
             $vfs = $conf['vfs'];
452
-        } else {
521
+        }
522
+        else
523
+        {
453 524
             $vfs = $conf[$name];
454 525
         }
455 526
 
456
-        if ($vfs['type'] == 'sql') {
527
+        if ($vfs['type'] == 'sql')
528
+        {
457 529
             $vfs['params'] = Horde::getDriverConfig($name, 'sql');
458 530
         }
459 531
 
@@ -483,12 +555,14 @@  discard block
 block discarded – undo
483 555
 
484 556
         // Don't generate a fatal error if we fail during or before
485 557
         // Registry instantiation.
486
-        if (is_null($name)) {
558
+        if (is_null($name))
559
+        {
487 560
             $name = isset($registry) ? $registry->getApp() : '[unknown]';
488 561
         }
489 562
         $fileroot = isset($registry) ? $registry->get('fileroot') : '';
490 563
 
491
-        if (!is_array($params) || !count($params)) {
564
+        if (!is_array($params) || !count($params))
565
+        {
492 566
             Horde::fatal(PEAR::raiseError(
493 567
                 sprintf(_("No configuration information specified for %s."), $name) . "\n\n" .
494 568
                 sprintf(_("The file %s should contain some %s settings."),
@@ -497,8 +571,10 @@  discard block
 block discarded – undo
497 571
                 __FILE__, __LINE__);
498 572
         }
499 573
 
500
-        foreach ($fields as $field) {
501
-            if (!isset($params[$field])) {
574
+        foreach ($fields as $field)
575
+        {
576
+            if (!isset($params[$field]))
577
+            {
502 578
                 Horde::fatal(PEAR::raiseError(
503 579
                     sprintf(_("Required '%s' not specified in %s configuration."), $field, $name) . "\n\n" .
504 580
                     sprintf(_("The file %s should contain a %s setting."),
@@ -524,11 +600,13 @@  discard block
 block discarded – undo
524 600
      */
525 601
     function url($uri, $full = false, $append_session = 0, $force_ssl = false)
526 602
     {
527
-        if ($force_ssl) {
603
+        if ($force_ssl)
604
+        {
528 605
             $full = true;
529 606
         }
530 607
 
531
-        if ($full) {
608
+        if ($full)
609
+        {
532 610
             global $conf, $registry, $browser;
533 611
 
534 612
             /* Store connection parameters in local variables. */
@@ -536,14 +614,20 @@  discard block
 block discarded – undo
536 614
             $server_port = $conf['server']['port'];
537 615
 
538 616
             $protocol = 'http';
539
-            if ($conf['use_ssl'] == 1) {
617
+            if ($conf['use_ssl'] == 1)
618
+            {
540 619
                 $protocol = 'https';
541
-            } elseif ($conf['use_ssl'] == 2 &&
542
-                      $browser->usingSSLConnection()) {
620
+            }
621
+            elseif ($conf['use_ssl'] == 2 &&
622
+                      $browser->usingSSLConnection())
623
+            {
543 624
                 $protocol = 'https';
544
-            } elseif ($conf['use_ssl'] == 3) {
625
+            }
626
+            elseif ($conf['use_ssl'] == 3)
627
+            {
545 628
                 $server_port = '';
546
-                if ($force_ssl) {
629
+                if ($force_ssl)
630
+                {
547 631
                     $protocol = 'https';
548 632
                 }
549 633
             }
@@ -551,7 +635,8 @@  discard block
 block discarded – undo
551 635
             /* If using non-standard ports, add the port to the URL. */
552 636
             if (!empty($server_port) &&
553 637
                 ((($protocol == 'http') && ($server_port != 80)) ||
554
-                 (($protocol == 'https') && ($server_port != 443)))) {
638
+                 (($protocol == 'https') && ($server_port != 443))))
639
+            {
555 640
                 $server_name .= ':' . $server_port;
556 641
             }
557 642
 
@@ -559,34 +644,48 @@  discard block
 block discarded – undo
559 644
             $webroot = $registry->get('webroot');
560 645
 
561 646
             $url = $protocol . '://' . $server_name;
562
-            if (substr($uri, 0, 1) != '/') {
563
-                if (substr($webroot, -1) == '/') {
647
+            if (substr($uri, 0, 1) != '/')
648
+            {
649
+                if (substr($webroot, -1) == '/')
650
+                {
564 651
                     $url .= $webroot . $uri;
565
-                } else {
652
+                }
653
+                else
654
+                {
566 655
                     $url .= $webroot . '/' . $uri;
567 656
                 }
568
-            } else {
657
+            }
658
+            else
659
+            {
569 660
                 $url .= $uri;
570 661
             }
571
-        } else {
662
+        }
663
+        else
664
+        {
572 665
             $url = $uri;
573 666
         }
574 667
 
575 668
         if (($append_session == 1) ||
576 669
             (($append_session == 0) &&
577
-             !isset($_COOKIE[session_name()]))) {
670
+             !isset($_COOKIE[session_name()])))
671
+        {
578 672
             $url = Util::addParameter($url, session_name(), session_id());
579 673
         }
580 674
 
581
-        if ($full) {
675
+        if ($full)
676
+        {
582 677
             /* We need to run the replace twice, because we only catch every
583 678
              * second match. */
584 679
             return preg_replace(array('/(=?.*?)&amp;(.*?=)/',
585 680
                                       '/(=?.*?)&amp;(.*?=)/'),
586 681
                                 '$1&$2', $url);
587
-        } elseif (preg_match('/=.*&amp;.*=/', $url)) {
682
+        }
683
+        elseif (preg_match('/=.*&amp;.*=/', $url))
684
+        {
588 685
             return $url;
589
-        } else {
686
+        }
687
+        else
688
+        {
590 689
             return htmlentities($url);
591 690
         }
592 691
     }
@@ -610,11 +709,16 @@  discard block
 block discarded – undo
610 709
         /* Store the webroot in a local variable. */
611 710
         $webroot = $registry->get('webroot');
612 711
 
613
-        if ($full) {
712
+        if ($full)
713
+        {
614 714
             return Horde::url($uri, $full, $append_session);
615
-        } elseif (substr($webroot, -1) == '/') {
715
+        }
716
+        elseif (substr($webroot, -1) == '/')
717
+        {
616 718
             return Horde::url($webroot . $uri, $full, $append_session);
617
-        } else {
719
+        }
720
+        else
721
+        {
618 722
             return Horde::url($webroot . '/' . $uri, $full, $append_session);
619 723
         }
620 724
     }
@@ -637,7 +741,8 @@  discard block
 block discarded – undo
637 741
         /* We must make sure there are no &amp's in the URL. */
638 742
         $url = preg_replace(array('/(=?.*?)&amp;(.*?=)/', '/(=?.*?)&amp;(.*?=)/'), '$1&$2', $url);
639 743
         $ext = Util::addParameter($ext, 'url', $url);
640
-        if ($tag) {
744
+        if ($tag)
745
+        {
641 746
             $ext = Horde::link($ext, $url, '', '_blank');
642 747
         }
643 748
         return $ext;
@@ -663,15 +768,18 @@  discard block
 block discarded – undo
663 768
 
664 769
         $horde_url = false;
665 770
 
666
-        if (is_null($url)) {
771
+        if (is_null($url))
772
+        {
667 773
             global $registry;
668 774
             $url = Util::addParameter(Horde::url($registry->get('webroot', 'horde') . '/services/download/'), 'module', $registry->getApp());
669 775
             $horde_url = true;
670 776
         }
671 777
 
672 778
         /* Add parameters. */
673
-        if (!is_null($params)) {
674
-            foreach ($params as $key => $val) {
779
+        if (!is_null($params))
780
+        {
781
+            foreach ($params as $key => $val)
782
+            {
675 783
                 $url = Util::addParameter($url, $key, $val);
676 784
             }
677 785
         }
@@ -680,9 +788,12 @@  discard block
 block discarded – undo
680 788
          * filename to the end of the URL. Although not necessary for
681 789
          * many browsers, this should allow every browser to download
682 790
          * correctly. */
683
-        if ($horde_url) {
791
+        if ($horde_url)
792
+        {
684 793
             $url = Util::addParameter($url, 'fn=/' . rawurlencode($filename));
685
-        } elseif ($browser->hasQuirk('break_disposition_filename')) {
794
+        }
795
+        elseif ($browser->hasQuirk('break_disposition_filename'))
796
+        {
686 797
             /* Some browsers will only obtain the filename correctly
687 798
              * if the extension is the last argument in the query
688 799
              * string and rest of the filename appears in the
@@ -696,25 +807,33 @@  discard block
 block discarded – undo
696 807
              * NOT support PATH_INFO information being passed to the
697 808
              * PHP module by default, so disable that
698 809
              * functionality. */
699
-            if (($server != 'apache2')) {
700
-                if (($pos = strrpos($filename, '.'))) {
810
+            if (($server != 'apache2'))
811
+            {
812
+                if (($pos = strrpos($filename, '.')))
813
+                {
701 814
                     $name = '/' . preg_replace('/\./', '%2E', substr($filename, 0, $pos));
702 815
                     $ext = substr($filename, $pos);
703
-                } else {
816
+                }
817
+                else
818
+                {
704 819
                     $name = '/' . $filename;
705 820
                     $ext = '';
706 821
                 }
707 822
 
708 823
                 /* Enter the PATH_INFO information. */
709
-                if (($pos = strpos($url, '?'))) {
824
+                if (($pos = strpos($url, '?')))
825
+                {
710 826
                     $url = substr($url, 0, $pos) . $name . substr($url, $pos);
711
-                } else {
827
+                }
828
+                else
829
+                {
712 830
                     $url .= $name;
713 831
                 }
714 832
             }
715 833
 
716 834
             /* Append the extension, if it exists. */
717
-            if (($server == 'apache2') || !empty($ext)) {
835
+            if (($server == 'apache2') || !empty($ext))
836
+            {
718 837
                 $url = Util::addParameter($url, 'fn_ext=/' . $filename);
719 838
             }
720 839
         }
@@ -743,26 +862,33 @@  discard block
 block discarded – undo
743 862
                   $title = '', $accesskey = '', $attributes = array())
744 863
     {
745 864
         $ret = "<a href=\"$url\"";
746
-        if (!empty($onclick)) {
865
+        if (!empty($onclick))
866
+        {
747 867
             $ret .= " onclick=\"$onclick\"";
748 868
         }
749
-        if (!empty($status)) {
869
+        if (!empty($status))
870
+        {
750 871
             $ret .= ' onmouseout="window.status=\'\';" onmouseover="window.status=\'' . @htmlspecialchars(strtr(addslashes($status), array("\r" => '', "\n" => '')), ENT_QUOTES, NLS::getCharset()) . '\'; return true;"';
751 872
         }
752
-        if (!empty($class)) {
873
+        if (!empty($class))
874
+        {
753 875
             $ret .= " class=\"$class\"";
754 876
         }
755
-        if (!empty($target)) {
877
+        if (!empty($target))
878
+        {
756 879
             $ret .= " target=\"$target\"";
757 880
         }
758
-        if (!empty($title)) {
881
+        if (!empty($title))
882
+        {
759 883
             $ret .= ' title="' . @htmlspecialchars($title, ENT_QUOTES, NLS::getCharset()) . '"';
760 884
         }
761
-        if (!empty($accesskey)) {
885
+        if (!empty($accesskey))
886
+        {
762 887
             $ret .= ' accesskey="' . htmlspecialchars($accesskey) . '"';
763 888
         }
764 889
 
765
-        foreach ($attributes as $name => $value) {
890
+        foreach ($attributes as $name => $value)
891
+        {
766 892
             $ret .= ' ' . htmlspecialchars($name) . '="' . htmlspecialchars($value) . '"';
767 893
         }
768 894
 
@@ -811,15 +937,19 @@  discard block
 block discarded – undo
811 937
     {
812 938
         $url = $_SERVER['PHP_SELF'];
813 939
 
814
-        if ($query_string && !empty($_SERVER['QUERY_STRING'])) {
940
+        if ($query_string && !empty($_SERVER['QUERY_STRING']))
941
+        {
815 942
             $url .= '?' . $_SERVER['QUERY_STRING'];
816 943
         }
817 944
 
818 945
         $url = Horde::url($url, $full, 0, $force_ssl);
819 946
 
820
-        if ($nocache) {
947
+        if ($nocache)
948
+        {
821 949
             return Util::nocacheUrl($url);
822
-        } else {
950
+        }
951
+        else
952
+        {
823 953
             return $url;
824 954
         }
825 955
     }
@@ -841,18 +971,21 @@  discard block
 block discarded – undo
841 971
     function img($src, $alt = '', $attr = '', $dir = null)
842 972
     {
843 973
         /* If browser does not support images, simply return the ALT text. */
844
-        if (!$GLOBALS['browser']->hasFeature('images')) {
974
+        if (!$GLOBALS['browser']->hasFeature('images'))
975
+        {
845 976
             return @htmlspecialchars($alt, ENT_COMPAT, NLS::getCharset());
846 977
         }
847 978
 
848 979
         /* If no directory has been specified, get it from the registry. */
849
-        if ($dir === null) {
980
+        if ($dir === null)
981
+        {
850 982
             global $registry;
851 983
             $dir = $registry->getImageDir();
852 984
         }
853 985
 
854 986
         /* If a directory has been provided, prepend it to the image source. */
855
-        if (!empty($dir)) {
987
+        if (!empty($dir))
988
+        {
856 989
             $src = $dir . '/' . $src;
857 990
         }
858 991
 
@@ -860,17 +993,20 @@  discard block
 block discarded – undo
860 993
         $attributes = array('src' => $src,
861 994
                             'alt' => $alt,
862 995
                             'title' => $alt);
863
-        if (is_array($attr)) {
996
+        if (is_array($attr))
997
+        {
864 998
             $attributes = array_merge($attributes, $attr);
865 999
         }
866 1000
 
867 1001
         $img = '<img';
868
-        foreach ($attributes as $attribute => $value) {
1002
+        foreach ($attributes as $attribute => $value)
1003
+        {
869 1004
             $img .= ' ' . $attribute . '="' . ($attribute == 'src' ? $value : @htmlspecialchars($value, ENT_COMPAT, NLS::getCharset())) . '"';
870 1005
         }
871 1006
 
872 1007
         /* If the user supplied a pre-built string of attributes, add that. */
873
-        if (is_string($attr) && !empty($attr)) {
1008
+        if (is_string($attr) && !empty($attr))
1009
+        {
874 1010
             $img .= ' ' . $attr;
875 1011
         }
876 1012
 
@@ -892,12 +1028,14 @@  discard block
 block discarded – undo
892 1028
         global $conf;
893 1029
 
894 1030
         /* If one has been specifically set, then use that */
895
-        if (!empty($conf['tmpdir'])) {
1031
+        if (!empty($conf['tmpdir']))
1032
+        {
896 1033
             $tmp = $conf['tmpdir'];
897 1034
         }
898 1035
 
899 1036
         /* Next, try Util::getTempDir(). */
900
-        if (empty($tmp)) {
1037
+        if (empty($tmp))
1038
+        {
901 1039
             $tmp = Util::getTempDir();
902 1040
         }
903 1041
 
@@ -925,7 +1063,8 @@  discard block
 block discarded – undo
925 1063
     function getTempFile($prefix = 'Horde', $delete = true, $dir = '',
926 1064
                          $secure = false)
927 1065
     {
928
-        if (empty($dir) || !is_dir($dir)) {
1066
+        if (empty($dir) || !is_dir($dir))
1067
+        {
929 1068
             $dir = Horde::getTempDir();
930 1069
         }
931 1070
 
@@ -943,7 +1082,8 @@  discard block
 block discarded – undo
943 1082
     {
944 1083
         static $started;
945 1084
 
946
-        if (isset($started)) {
1085
+        if (isset($started))
1086
+        {
947 1087
             return;
948 1088
         }
949 1089
 
@@ -951,8 +1091,10 @@  discard block
 block discarded – undo
951 1091
         if ($GLOBALS['conf']['compress_pages'] &&
952 1092
             !$GLOBALS['browser']->hasQuirk('buggy_compression') &&
953 1093
             ini_get('zlib.output_compression') == '' &&
954
-            ini_get('output_handler') != 'ob_gzhandler') {
955
-            if (ob_get_level()) {
1094
+            ini_get('output_handler') != 'ob_gzhandler')
1095
+        {
1096
+            if (ob_get_level())
1097
+            {
956 1098
                 ob_end_clean();
957 1099
             }
958 1100
             ob_start('ob_gzhandler');
@@ -974,7 +1116,8 @@  discard block
 block discarded – undo
974 1116
         $browser = &Browser::singleton();
975 1117
 
976 1118
         /* Turn off compression for buggy browsers. */
977
-        if ($browser->hasQuirk('buggy_compression')) {
1119
+        if ($browser->hasQuirk('buggy_compression'))
1120
+        {
978 1121
             return false;
979 1122
         }
980 1123
 
@@ -1013,12 +1156,17 @@  discard block
 block discarded – undo
1013 1156
     {
1014 1157
         $server = php_sapi_name();
1015 1158
 
1016
-        if ($server == 'apache') {
1159
+        if ($server == 'apache')
1160
+        {
1017 1161
             return 'apache1';
1018
-        } elseif (($server == 'apache2filter') ||
1019
-                  ($server == 'apache2handler')) {
1162
+        }
1163
+        elseif (($server == 'apache2filter') ||
1164
+                  ($server == 'apache2handler'))
1165
+        {
1020 1166
             return 'apache2';
1021
-        } else {
1167
+        }
1168
+        else
1169
+        {
1022 1170
             return $server;
1023 1171
         }
1024 1172
     }
@@ -1038,65 +1186,80 @@  discard block
 block discarded – undo
1038 1186
      */
1039 1187
     function stylesheetLink($apps = null, $theme = '', $inherit = true)
1040 1188
     {
1041
-        if ($theme !== false && empty($theme)) {
1189
+        if ($theme !== false && empty($theme))
1190
+        {
1042 1191
             $theme = $GLOBALS['prefs']->getValue('theme');
1043 1192
         }
1044 1193
 
1045 1194
         $css = array();
1046 1195
         $themes_fs = $GLOBALS['registry']->get('themesfs', 'horde');
1047
-        if ($inherit) {
1196
+        if ($inherit)
1197
+        {
1048 1198
             $themes_uri = Horde::url($GLOBALS['registry']->get('themesuri', 'horde'), false, -1);
1049 1199
             $css[] = $themes_uri . '/screen.css';
1050 1200
             if (!empty($theme) &&
1051
-                file_exists($themes_fs . '/' . $theme . '/screen.css')) {
1201
+                file_exists($themes_fs . '/' . $theme . '/screen.css'))
1202
+            {
1052 1203
                 $css[] = $themes_uri . '/' . $theme . '/screen.css';
1053 1204
             }
1054 1205
         }
1055 1206
 
1056
-        if (!empty($apps)) {
1057
-            if (!is_array($apps)) {
1207
+        if (!empty($apps))
1208
+        {
1209
+            if (!is_array($apps))
1210
+            {
1058 1211
                 $apps = array($apps);
1059 1212
             }
1060
-            foreach ($apps as $app) {
1061
-                if ($inherit && $app == 'horde') {
1213
+            foreach ($apps as $app)
1214
+            {
1215
+                if ($inherit && $app == 'horde')
1216
+                {
1062 1217
                     continue;
1063 1218
                 }
1064 1219
 
1065 1220
                 $themes_fs = $GLOBALS['registry']->get('themesfs', $app);
1066
-                if (file_exists($themes_fs . '/screen.css')) {
1221
+                if (file_exists($themes_fs . '/screen.css'))
1222
+                {
1067 1223
                     $themes_uri = Horde::url($GLOBALS['registry']->get('themesuri', $app), false, -1);
1068 1224
                     $css[] = $themes_uri . '/screen.css';
1069 1225
                 }
1070 1226
                 if (!empty($theme) &&
1071
-                    file_exists($themes_fs . '/' . $theme . '/screen.css')) {
1227
+                    file_exists($themes_fs . '/' . $theme . '/screen.css'))
1228
+                {
1072 1229
                     $css[] = $themes_uri . '/' . $theme . '/screen.css';
1073 1230
                 }
1074 1231
             }
1075 1232
         }
1076 1233
 
1077 1234
         $html = '';
1078
-        foreach ($css as $css_link) {
1235
+        foreach ($css as $css_link)
1236
+        {
1079 1237
             $html .= '<link href="' . $css_link . '" rel="stylesheet" type="text/css" />' . "\n";
1080 1238
         }
1081 1239
 
1082 1240
         /* Load IE PNG transparency code if needed. */
1083 1241
         if ($GLOBALS['browser']->hasQuirk('png_transparency') &&
1084
-            $GLOBALS['prefs']->getValue('alpha_filter')) {
1242
+            $GLOBALS['prefs']->getValue('alpha_filter'))
1243
+        {
1085 1244
             $url = Horde::url($GLOBALS['registry']->get('jsuri', 'horde') . '/alphaImageLoader.php', true, -1);
1086 1245
             $html .= '<style type="text/css"> img { behavior: url("' . $url . '"); } </style>';
1087 1246
         }
1088 1247
 
1089 1248
         /* Load browser specific stylesheets if needed. */
1090
-        if ($GLOBALS['browser']->isBrowser('msie')) {
1249
+        if ($GLOBALS['browser']->isBrowser('msie'))
1250
+        {
1091 1251
             $html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/ie.css" rel="stylesheet" type="text/css" />' . "\n";
1092
-            if ($GLOBALS['browser']->getPlatform() == 'mac') {
1252
+            if ($GLOBALS['browser']->getPlatform() == 'mac')
1253
+            {
1093 1254
                 $html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/ie5mac.css" rel="stylesheet" type="text/css" />' . "\n";
1094 1255
             }
1095 1256
         }
1096
-        if ($GLOBALS['browser']->isBrowser('opera')) {
1257
+        if ($GLOBALS['browser']->isBrowser('opera'))
1258
+        {
1097 1259
             $html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/opera.css" rel="stylesheet" type="text/css" />' . "\n";
1098 1260
         }
1099
-        if (strpos(strtolower($GLOBALS['browser']->getAgentString()), 'safari') !== false) {
1261
+        if (strpos(strtolower($GLOBALS['browser']->getAgentString()), 'safari') !== false)
1262
+        {
1100 1263
             $html .= '<link href="' . $GLOBALS['registry']->get('themesuri', 'horde') . '/safari.css" rel="stylesheet" type="text/css" />' . "\n";
1101 1264
         }
1102 1265
 
@@ -1120,7 +1283,8 @@  discard block
 block discarded – undo
1120 1283
 
1121 1284
         $type = !empty($conf['sessionhandler']['type']) ? $conf['sessionhandler']['type'] : 'none';
1122 1285
 
1123
-        if ($type == 'external') {
1286
+        if ($type == 'external')
1287
+        {
1124 1288
             $calls = $conf['sessionhandler']['params'];
1125 1289
             session_set_save_handler($calls['open'],
1126 1290
                                      $calls['close'],
@@ -1128,12 +1292,15 @@  discard block
 block discarded – undo
1128 1292
                                      $calls['write'],
1129 1293
                                      $calls['destroy'],
1130 1294
                                      $calls['gc']);
1131
-        } elseif ($type != 'none') {
1295
+        }
1296
+        elseif ($type != 'none')
1297
+        {
1132 1298
             global $_session_handler;
1133 1299
             require_once 'Horde/SessionHandler.php';
1134 1300
             $_session_handler = &SessionHandler::singleton($conf['sessionhandler']['type']);
1135 1301
             if (!empty($_session_handler) &&
1136
-                !is_a($_session_handler, 'PEAR_Error')) {
1302
+                !is_a($_session_handler, 'PEAR_Error'))
1303
+            {
1137 1304
                 ini_set('session.save_handler', 'user');
1138 1305
                 session_set_save_handler(array(&$_session_handler, 'open'),
1139 1306
                                          array(&$_session_handler, 'close'),
@@ -1141,7 +1308,9 @@  discard block
 block discarded – undo
1141 1308
                                          array(&$_session_handler, 'write'),
1142 1309
                                          array(&$_session_handler, 'destroy'),
1143 1310
                                          array(&$_session_handler, 'gc'));
1144
-            } else {
1311
+            }
1312
+            else
1313
+            {
1145 1314
                 Horde::fatal(PEAR::raiseError('Horde is unable to correctly start the custom session handler.'), __FILE__, __LINE__, false);
1146 1315
             }
1147 1316
         }
@@ -1168,8 +1337,10 @@  discard block
 block discarded – undo
1168 1337
         static $_labels = array();
1169 1338
 
1170 1339
         /* Shutdown call for translators? */
1171
-        if ($shutdown) {
1172
-            if (!count($_labels)) {
1340
+        if ($shutdown)
1341
+        {
1342
+            if (!count($_labels))
1343
+            {
1173 1344
                 return;
1174 1345
             }
1175 1346
             $script = basename($_SERVER['PHP_SELF']);
@@ -1187,19 +1358,22 @@  discard block
 block discarded – undo
1187 1358
 
1188 1359
         /* Use access keys at all? */
1189 1360
         static $notsupported;
1190
-        if (!isset($notsupported)) {
1361
+        if (!isset($notsupported))
1362
+        {
1191 1363
             $notsupported = !$GLOBALS['browser']->hasFeature('accesskey') ||
1192 1364
                 !$GLOBALS['prefs']->getValue('widget_accesskey');
1193 1365
         }
1194 1366
 
1195
-        if ($notsupported || !preg_match('/_([A-Za-z])/', $label, $match)) {
1367
+        if ($notsupported || !preg_match('/_([A-Za-z])/', $label, $match))
1368
+        {
1196 1369
             return '';
1197 1370
         }
1198 1371
         $key = $match[1];
1199 1372
 
1200 1373
         /* Has this key already been used? */
1201 1374
         if (isset($_used[strtolower($key)]) &&
1202
-            !($nocheck && isset($_labels[$label]))) {
1375
+            !($nocheck && isset($_labels[$label])))
1376
+        {
1203 1377
             return '';
1204 1378
         }
1205 1379
 
@@ -1246,14 +1420,18 @@  discard block
 block discarded – undo
1246 1420
     {
1247 1421
         $stripped_label = Horde::stripAccesskey($label);
1248 1422
 
1249
-        if (empty($accessKey)) {
1423
+        if (empty($accessKey))
1424
+        {
1250 1425
             return $stripped_label;
1251 1426
         }
1252 1427
 
1253
-        if (isset($GLOBALS['nls']['multibyte'][NLS::getCharset(true)])) {
1428
+        if (isset($GLOBALS['nls']['multibyte'][NLS::getCharset(true)]))
1429
+        {
1254 1430
             return $stripped_label . '(' . '<span class="accessKey">' .
1255 1431
                 strtoupper($accessKey) . '</span>' . ')';
1256
-        } else {
1432
+        }
1433
+        else
1434
+        {
1257 1435
             return str_replace('_' . $accessKey, '<span class="accessKey">' . $accessKey . '</span>', $label);
1258 1436
         }
1259 1437
     }
@@ -1273,7 +1451,8 @@  discard block
 block discarded – undo
1273 1451
     {
1274 1452
         $ak = Horde::getAccessKey($label, $nocheck);
1275 1453
         $attributes = 'title="' . Horde::stripAccessKey($label);
1276
-        if (!empty($ak)) {
1454
+        if (!empty($ak))
1455
+        {
1277 1456
             $attributes .= sprintf(_(" (Accesskey %s)"), $ak);
1278 1457
             $attributes .= '" accesskey="' . $ak;
1279 1458
         }
@@ -1296,7 +1475,8 @@  discard block
 block discarded – undo
1296 1475
     {
1297 1476
         global $prefs;
1298 1477
 
1299
-        if (is_null($ak)) {
1478
+        if (is_null($ak))
1479
+        {
1300 1480
             $ak = Horde::getAccesskey($label, 1);
1301 1481
         }
1302 1482
         $label = Horde::highlightAccessKey($label, $ak);
@@ -1315,7 +1495,8 @@  discard block
 block discarded – undo
1315 1495
     function authenticationFailureRedirect()
1316 1496
     {
1317 1497
         require_once 'Horde/CLI.php';
1318
-        if (Horde_CLI::runningFromCLI()) {
1498
+        if (Horde_CLI::runningFromCLI())
1499
+        {
1319 1500
             $cli = &Horde_CLI::singleton();
1320 1501
             $cli->fatal(_("You are not authenticated."));
1321 1502
         }
@@ -1354,12 +1535,14 @@  discard block
 block discarded – undo
1354 1535
     {
1355 1536
         $url = substr(Horde::link($url, null, $class, $target, $onclick, null, $accesskey, $attributes), 0, -1);
1356 1537
 
1357
-        if (strlen($status)) {
1538
+        if (strlen($status))
1539
+        {
1358 1540
             $status = @htmlspecialchars(addslashes($status), ENT_QUOTES, NLS::getCharset());
1359 1541
         }
1360 1542
 
1361 1543
         $title = trim($title);
1362
-        if (strlen($title)) {
1544
+        if (strlen($title))
1545
+        {
1363 1546
             require_once 'Horde/Text/Filter.php';
1364 1547
             $title = Text_Filter::filter($title, 'text2html', array('parselevel' => TEXT_HTML_NOHTML, 'charset' => '', 'class' => ''));
1365 1548
             $title = '<pre style="margin:0px;">' . strtr(addslashes($title), array("\r" => '', "\n" => '')) . '</pre>';
@@ -1395,19 +1578,25 @@  discard block
 block discarded – undo
1395 1578
         global $registry;
1396 1579
         static $hooks_loaded;
1397 1580
 
1398
-        if (!isset($hooks_loaded)) {
1399
-            if (file_exists($registry->get('fileroot', $app) . '/config/hooks.php')) {
1581
+        if (!isset($hooks_loaded))
1582
+        {
1583
+            if (file_exists($registry->get('fileroot', $app) . '/config/hooks.php'))
1584
+            {
1400 1585
                 require_once $registry->get('fileroot', $app) . '/config/hooks.php';
1401 1586
                 $hooks_loaded = true;
1402
-            } else {
1587
+            }
1588
+            else
1589
+            {
1403 1590
                 $hooks_loaded = false;
1404 1591
             }
1405 1592
         }
1406
-        if ($hooks_loaded && function_exists($hook)) {
1593
+        if ($hooks_loaded && function_exists($hook))
1594
+        {
1407 1595
             return call_user_func_array($hook, $args);
1408 1596
         }
1409 1597
 
1410
-        if (is_string($error) && strcmp($error, 'PEAR_Error') == 0) {
1598
+        if (is_string($error) && strcmp($error, 'PEAR_Error') == 0)
1599
+        {
1411 1600
             $error = PEAR::raiseError(sprintf('Hook %s in application %s not called.', $hook, $app));
1412 1601
             Horde::logMessage($error, __FILE__, __LINE__, PEAR_LOG_DEBUG);
1413 1602
         }
@@ -1425,13 +1614,20 @@  discard block
 block discarded – undo
1425 1614
         global $prefs, $registry, $perms;
1426 1615
 
1427 1616
         $initial_app = $prefs->getValue('initial_application');
1428
-        if (!empty($initial_app) && $registry->hasPermission($initial_app)) {
1617
+        if (!empty($initial_app) && $registry->hasPermission($initial_app))
1618
+        {
1429 1619
             return Horde::url($registry->getInitialPage($initial_app), true);
1430
-        } elseif (isset($registry->applications['horde']['initial_page'])) {
1620
+        }
1621
+        elseif (isset($registry->applications['horde']['initial_page']))
1622
+        {
1431 1623
             return Horde::applicationUrl($registry->applications['horde']['initial_page'], true);
1432
-        } elseif (Auth::getAuth()) {
1624
+        }
1625
+        elseif (Auth::getAuth())
1626
+        {
1433 1627
             return Horde::applicationUrl('services/portal/', true);
1434
-        } else {
1628
+        }
1629
+        else
1630
+        {
1435 1631
             return Horde::applicationUrl('login.php', true);
1436 1632
         }
1437 1633
     }
@@ -1451,9 +1647,12 @@  discard block
 block discarded – undo
1451 1647
          * prefs this will default to that application. Otherwise it will go
1452 1648
          * to the portal screen. */
1453 1649
         $initial_app = $prefs->getValue('initial_application');
1454
-        if (!empty($initial_app)) {
1650
+        if (!empty($initial_app))
1651
+        {
1455 1652
             $url = Horde::url($registry->getInitialPage($initial_app));
1456
-        } else {
1653
+        }
1654
+        else
1655
+        {
1457 1656
             $url = Horde::applicationUrl('services/portal/');
1458 1657
         }
1459 1658
         $menu[] = array('url' => $url,
@@ -1461,7 +1660,8 @@  discard block
 block discarded – undo
1461 1660
                         'icon' => 'horde.png',
1462 1661
                         'icon_path' => $registry->getImageDir());
1463 1662
 
1464
-        if (Auth::isAdmin()) {
1663
+        if (Auth::isAdmin())
1664
+        {
1465 1665
             $menu[] = array('url' => Horde::applicationUrl('admin/'),
1466 1666
                             'text' =>  _("_Administration"),
1467 1667
                             'icon' => 'administration.png',
Please login to merge, or discard this patch.
Upper-Lower-Casing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -218,7 +218,7 @@
 block discarded – undo
218 218
 <head><title>Horde :: Fatal Error</title></head>
219 219
 <body style="background-color: white; color: black;">$errortext</body>
220 220
 </html>
221
-HTML;
221
+html;
222 222
         }
223 223
         exit;
224 224
     }
Please login to merge, or discard this patch.
phpgwapi/inc/horde/Horde/Date.php 4 patches
Doc Comments   +8 added lines, -3 removed lines patch added patch discarded remove patch
@@ -181,6 +181,8 @@  discard block
 block discarded – undo
181 181
 
182 182
     /**
183 183
      * @static
184
+     * @param integer $month
185
+     * @param integer $year
184 186
      */
185 187
     function daysInMonth($month, $year)
186 188
     {
@@ -243,7 +245,7 @@  discard block
 block discarded – undo
243 245
      *
244 246
      * @since Horde 3.2
245 247
      *
246
-     * @return integer  The week number.
248
+     * @return double  The week number.
247 249
      */
248 250
     function weekOfMonth()
249 251
     {
@@ -253,7 +255,7 @@  discard block
 block discarded – undo
253 255
     /**
254 256
      * Returns the week of the year, first Monday is first day of first week.
255 257
      *
256
-     * @return integer  The week number.
258
+     * @return string  The week number.
257 259
      */
258 260
     function weekOfYear()
259 261
     {
@@ -267,7 +269,7 @@  discard block
 block discarded – undo
267 269
      *
268 270
      * @param integer $year  The year to count the number of weeks in.
269 271
      *
270
-     * @return integer $numWeeks   The number of weeks in $year.
272
+     * @return string $numWeeks   The number of weeks in $year.
271 273
      */
272 274
     function weeksInYear($year)
273 275
     {
@@ -668,6 +670,9 @@  discard block
 block discarded – undo
668 670
      * This does NOT work with pre-1970 daylight saving times.
669 671
      *
670 672
      * @static
673
+     * @param integer $hr
674
+     * @param integer $min
675
+     * @param integer $sec
671 676
      */
672 677
     function _mktime($hr, $min, $sec, $mon = false, $day = false,
673 678
                      $year = false, $is_dst = false, $is_gmt = false)
Please login to merge, or discard this patch.
Indentation   +728 added lines, -728 removed lines patch added patch discarded remove patch
@@ -37,733 +37,733 @@
 block discarded – undo
37 37
  */
38 38
 class Horde_Date {
39 39
 
40
-    /**
41
-     * Year
42
-     *
43
-     * @var integer
44
-     */
45
-    var $year;
46
-
47
-    /**
48
-     * Month
49
-     *
50
-     * @var integer
51
-     */
52
-    var $month;
53
-
54
-    /**
55
-     * Day
56
-     *
57
-     * @var integer
58
-     */
59
-    var $mday;
60
-
61
-    /**
62
-     * Hour
63
-     *
64
-     * @var integer
65
-     */
66
-    var $hour = 0;
67
-
68
-    /**
69
-     * Minute
70
-     *
71
-     * @var integer
72
-     */
73
-    var $min = 0;
74
-
75
-    /**
76
-     * Second
77
-     *
78
-     * @var integer
79
-     */
80
-    var $sec = 0;
81
-
82
-    /**
83
-     * Internally supported strftime() specifiers.
84
-     *
85
-     * @var string
86
-     */
87
-    var $_supportedSpecs = '%CdDeHImMnRStTyY';
88
-
89
-    /**
90
-     * Build a new date object. If $date contains date parts, use them to
91
-     * initialize the object.
92
-     *
93
-     * Recognized formats:
94
-     * - arrays with keys 'year', 'month', 'mday', 'day' (since Horde 3.2),
95
-     *   'hour', 'min', 'minute' (since Horde 3.2), 'sec'
96
-     * - objects with properties 'year', 'month', 'mday', 'hour', 'min', 'sec'
97
-     * - yyyy-mm-dd hh:mm:ss (since Horde 3.1)
98
-     * - yyyymmddhhmmss (since Horde 3.1)
99
-     * - yyyymmddThhmmssZ (since Horde 3.1.4)
100
-     * - unix timestamps
101
-     */
102
-    function Horde_Date($date = null)
103
-    {
104
-        if (function_exists('nl_langinfo')) {
105
-            $this->_supportedSpecs .= 'bBpxX';
106
-        }
107
-
108
-        if (is_array($date) || is_object($date)) {
109
-            foreach ($date as $key => $val) {
110
-                if (in_array($key, array('year', 'month', 'mday', 'hour', 'min', 'sec'))) {
111
-                    $this->$key = (int)$val;
112
-                }
113
-            }
114
-
115
-            // If $date['day'] is present and numeric we may have been passed
116
-            // a Horde_Form_datetime array.
117
-            if (is_array($date) && isset($date['day']) &&
118
-                is_numeric($date['day'])) {
119
-                $this->mday = (int)$date['day'];
120
-            }
121
-            // 'minute' key also from Horde_Form_datetime
122
-            if (is_array($date) && isset($date['minute'])) {
123
-                $this->min = $date['minute'];
124
-            }
125
-        } elseif (!is_null($date)) {
126
-            // Match YYYY-MM-DD HH:MM:SS, YYYYMMDDHHMMSS and YYYYMMDD'T'HHMMSS'Z'.
127
-            if (preg_match('/(\d{4})-?(\d{2})-?(\d{2})T? ?(\d{2}):?(\d{2}):?(\d{2})Z?/', $date, $parts)) {
128
-                $this->year = (int)$parts[1];
129
-                $this->month = (int)$parts[2];
130
-                $this->mday = (int)$parts[3];
131
-                $this->hour = (int)$parts[4];
132
-                $this->min = (int)$parts[5];
133
-                $this->sec = (int)$parts[6];
134
-            } else {
135
-                // Try as a timestamp.
136
-                $parts = @getdate($date);
137
-                if ($parts) {
138
-                    $this->year = $parts['year'];
139
-                    $this->month = $parts['mon'];
140
-                    $this->mday = $parts['mday'];
141
-                    $this->hour = $parts['hours'];
142
-                    $this->min = $parts['minutes'];
143
-                    $this->sec = $parts['seconds'];
144
-                }
145
-            }
146
-        }
147
-    }
148
-
149
-    /**
150
-     * @static
151
-     */
152
-    function isLeapYear($year)
153
-    {
154
-        if (strlen($year) != 4 || preg_match('/\D/', $year)) {
155
-            return false;
156
-        }
157
-
158
-        return (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0);
159
-    }
160
-
161
-    /**
162
-     * Returns the day of the year (1-366) that corresponds to the
163
-     * first day of the given week.
164
-     *
165
-     * TODO: with PHP 5.1+, see http://derickrethans.nl/calculating_start_and_end_dates_of_a_week.php
166
-     *
167
-     * @param integer $week  The week of the year to find the first day of.
168
-     * @param integer $year  The year to calculate for.
169
-     *
170
-     * @return integer  The day of the year of the first day of the given week.
171
-     */
172
-    function firstDayOfWeek($week, $year)
173
-    {
174
-        $jan1 = new Horde_Date(array('year' => $year, 'month' => 1, 'mday' => 1));
175
-        $start = $jan1->dayOfWeek();
176
-        if ($start > HORDE_DATE_THURSDAY) {
177
-            $start -= 7;
178
-        }
179
-        return (($week * 7) - (7 + $start)) + 1;
180
-    }
181
-
182
-    /**
183
-     * @static
184
-     */
185
-    function daysInMonth($month, $year)
186
-    {
187
-        if ($month == 2) {
188
-            if (Horde_Date::isLeapYear($year)) {
189
-                return 29;
190
-            } else {
191
-                return 28;
192
-            }
193
-        } elseif ($month == 4 || $month == 6 || $month == 9 || $month == 11) {
194
-            return 30;
195
-        } else {
196
-            return 31;
197
-        }
198
-    }
199
-
200
-    /**
201
-     * Return the day of the week (0 = Sunday, 6 = Saturday) of this
202
-     * object's date.
203
-     *
204
-     * @return integer  The day of the week.
205
-     */
206
-    function dayOfWeek()
207
-    {
208
-        if ($this->month > 2) {
209
-            $month = $this->month - 2;
210
-            $year = $this->year;
211
-        } else {
212
-            $month = $this->month + 10;
213
-            $year = $this->year - 1;
214
-        }
215
-
216
-        $day = (floor((13 * $month - 1) / 5) +
217
-                $this->mday + ($year % 100) +
218
-                floor(($year % 100) / 4) +
219
-                floor(($year / 100) / 4) - 2 *
220
-                floor($year / 100) + 77);
221
-
222
-        return (int)($day - 7 * floor($day / 7));
223
-    }
224
-
225
-    /**
226
-     * Returns the day number of the year (1 to 365/366).
227
-     *
228
-     * @return integer  The day of the year.
229
-     */
230
-    function dayOfYear()
231
-    {
232
-        $monthTotals = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
233
-        $dayOfYear = $this->mday + $monthTotals[$this->month - 1];
234
-        if (Horde_Date::isLeapYear($this->year) && $this->month > 2) {
235
-            ++$dayOfYear;
236
-        }
237
-
238
-        return $dayOfYear;
239
-    }
240
-
241
-    /**
242
-     * Returns the week of the month.
243
-     *
244
-     * @since Horde 3.2
245
-     *
246
-     * @return integer  The week number.
247
-     */
248
-    function weekOfMonth()
249
-    {
250
-        return ceil($this->mday / 7);
251
-    }
252
-
253
-    /**
254
-     * Returns the week of the year, first Monday is first day of first week.
255
-     *
256
-     * @return integer  The week number.
257
-     */
258
-    function weekOfYear()
259
-    {
260
-        return $this->format('W');
261
-    }
262
-
263
-    /**
264
-     * Return the number of weeks in the given year (52 or 53).
265
-     *
266
-     * @static
267
-     *
268
-     * @param integer $year  The year to count the number of weeks in.
269
-     *
270
-     * @return integer $numWeeks   The number of weeks in $year.
271
-     */
272
-    function weeksInYear($year)
273
-    {
274
-        // Find the last Thursday of the year.
275
-        $day = 31;
276
-        $date = new Horde_Date(array('year' => $year, 'month' => 12, 'mday' => $day, 'hour' => 0, 'min' => 0, 'sec' => 0));
277
-        while ($date->dayOfWeek() != HORDE_DATE_THURSDAY) {
278
-            --$date->mday;
279
-        }
280
-        return $date->weekOfYear();
281
-    }
282
-
283
-    /**
284
-     * Set the date of this object to the $nth weekday of $weekday.
285
-     *
286
-     * @param integer $weekday  The day of the week (0 = Sunday, etc).
287
-     * @param integer $nth      The $nth $weekday to set to (defaults to 1).
288
-     */
289
-    function setNthWeekday($weekday, $nth = 1)
290
-    {
291
-        if ($weekday < HORDE_DATE_SUNDAY || $weekday > HORDE_DATE_SATURDAY) {
292
-            return false;
293
-        }
294
-
295
-        $this->mday = 1;
296
-        $first = $this->dayOfWeek();
297
-        if ($weekday < $first) {
298
-            $this->mday = 8 + $weekday - $first;
299
-        } else {
300
-            $this->mday = $weekday - $first + 1;
301
-        }
302
-        $this->mday += 7 * $nth - 7;
303
-
304
-        $this->correct();
305
-
306
-        return true;
307
-    }
308
-
309
-    function dump($prefix = '')
310
-    {
311
-        echo ($prefix ? $prefix . ': ' : '') . $this->year . '-' . $this->month . '-' . $this->mday . "<br />\n";
312
-    }
313
-
314
-    /**
315
-     * Is the date currently represented by this object a valid date?
316
-     *
317
-     * @return boolean  Validity, counting leap years, etc.
318
-     */
319
-    function isValid()
320
-    {
321
-        if ($this->year < 0 || $this->year > 9999) {
322
-            return false;
323
-        }
324
-        return checkdate($this->month, $this->mday, $this->year);
325
-    }
326
-
327
-    /**
328
-     * Correct any over- or underflows in any of the date's members.
329
-     *
330
-     * @param integer $mask  We may not want to correct some overflows.
331
-     */
332
-    function correct($mask = HORDE_DATE_MASK_ALLPARTS)
333
-    {
334
-        if ($mask & HORDE_DATE_MASK_SECOND) {
335
-            while ($this->sec < 0) {
336
-                --$this->min;
337
-                $this->sec += 60;
338
-            }
339
-            while ($this->sec > 59) {
340
-                ++$this->min;
341
-                $this->sec -= 60;
342
-            }
343
-        }
344
-
345
-        if ($mask & HORDE_DATE_MASK_MINUTE) {
346
-            while ($this->min < 0) {
347
-                --$this->hour;
348
-                $this->min += 60;
349
-            }
350
-            while ($this->min > 59) {
351
-                ++$this->hour;
352
-                $this->min -= 60;
353
-            }
354
-        }
355
-
356
-        if ($mask & HORDE_DATE_MASK_HOUR) {
357
-            while ($this->hour < 0) {
358
-                --$this->mday;
359
-                $this->hour += 24;
360
-            }
361
-            while ($this->hour > 23) {
362
-                ++$this->mday;
363
-                $this->hour -= 24;
364
-            }
365
-        }
366
-
367
-        if ($mask & HORDE_DATE_MASK_MONTH) {
368
-            while ($this->month > 12) {
369
-                ++$this->year;
370
-                $this->month -= 12;
371
-            }
372
-            while ($this->month < 1) {
373
-                --$this->year;
374
-                $this->month += 12;
375
-            }
376
-        }
377
-
378
-        if ($mask & HORDE_DATE_MASK_DAY) {
379
-            while ($this->mday > Horde_Date::daysInMonth($this->month, $this->year)) {
380
-                $this->mday -= Horde_Date::daysInMonth($this->month, $this->year);
381
-                ++$this->month;
382
-                $this->correct(HORDE_DATE_MASK_MONTH);
383
-            }
384
-            while ($this->mday < 1) {
385
-                --$this->month;
386
-                $this->correct(HORDE_DATE_MASK_MONTH);
387
-                $this->mday += Horde_Date::daysInMonth($this->month, $this->year);
388
-            }
389
-        }
390
-    }
391
-
392
-    /**
393
-     * Compare this date to another date object to see which one is
394
-     * greater (later). Assumes that the dates are in the same
395
-     * timezone.
396
-     *
397
-     * @param mixed $date  The date to compare to.
398
-     *
399
-     * @return integer  ==  0 if the dates are equal
400
-     *                  >=  1 if this date is greater (later)
401
-     *                  <= -1 if the other date is greater (later)
402
-     */
403
-    function compareDate($date)
404
-    {
405
-        if (!is_a($date, 'Horde_Date')) {
406
-            $date = new Horde_Date($date);
407
-        }
408
-
409
-        if ($this->year != $date->year) {
410
-            return $this->year - $date->year;
411
-        }
412
-        if ($this->month != $date->month) {
413
-            return $this->month - $date->month;
414
-        }
415
-
416
-        return $this->mday - $date->mday;
417
-    }
418
-
419
-    /**
420
-     * Compare this to another date object by time, to see which one
421
-     * is greater (later). Assumes that the dates are in the same
422
-     * timezone.
423
-     *
424
-     * @param mixed $date  The date to compare to.
425
-     *
426
-     * @return integer  ==  0 if the dates are equal
427
-     *                  >=  1 if this date is greater (later)
428
-     *                  <= -1 if the other date is greater (later)
429
-     */
430
-    function compareTime($date)
431
-    {
432
-        if (!is_a($date, 'Horde_Date')) {
433
-            $date = new Horde_Date($date);
434
-        }
435
-
436
-        if ($this->hour != $date->hour) {
437
-            return $this->hour - $date->hour;
438
-        }
439
-        if ($this->min != $date->min) {
440
-            return $this->min - $date->min;
441
-        }
442
-
443
-        return $this->sec - $date->sec;
444
-    }
445
-
446
-    /**
447
-     * Compare this to another date object, including times, to see
448
-     * which one is greater (later). Assumes that the dates are in the
449
-     * same timezone.
450
-     *
451
-     * @param mixed $date  The date to compare to.
452
-     *
453
-     * @return integer  ==  0 if the dates are equal
454
-     *                  >=  1 if this date is greater (later)
455
-     *                  <= -1 if the other date is greater (later)
456
-     */
457
-    function compareDateTime($date)
458
-    {
459
-        if (!is_a($date, 'Horde_Date')) {
460
-            $date = new Horde_Date($date);
461
-        }
462
-
463
-        if ($diff = $this->compareDate($date)) {
464
-            return $diff;
465
-        }
466
-
467
-        return $this->compareTime($date);
468
-    }
469
-
470
-    /**
471
-     * Get the time offset for local time zone.
472
-     *
473
-     * @param boolean $colon  Place a colon between hours and minutes?
474
-     *
475
-     * @return string  Timezone offset as a string in the format +HH:MM.
476
-     */
477
-    function tzOffset($colon = true)
478
-    {
479
-        $secs = $this->format('Z');
480
-
481
-        if ($secs < 0) {
482
-            $sign = '-';
483
-            $secs = -$secs;
484
-        } else {
485
-            $sign = '+';
486
-        }
487
-        $colon = $colon ? ':' : '';
488
-        $mins = intval(($secs + 30) / 60);
489
-        return sprintf('%s%02d%s%02d',
490
-                       $sign, $mins / 60, $colon, $mins % 60);
491
-    }
492
-
493
-    /**
494
-     * Return the unix timestamp representation of this date.
495
-     *
496
-     * @return integer  A unix timestamp.
497
-     */
498
-    function timestamp()
499
-    {
500
-        if (class_exists('DateTime')) {
501
-            return $this->format('U');
502
-        } else {
503
-            return Horde_Date::_mktime($this->hour, $this->min, $this->sec, $this->month, $this->mday, $this->year);
504
-        }
505
-    }
506
-
507
-    /**
508
-     * Return the unix timestamp representation of this date, 12:00am.
509
-     *
510
-     * @return integer  A unix timestamp.
511
-     */
512
-    function datestamp()
513
-    {
514
-        if (class_exists('DateTime')) {
515
-            $dt = new DateTime();
516
-            $dt->setDate($this->year, $this->month, $this->mday);
517
-            $dt->setTime(0, 0, 0);
518
-            return $dt->format('U');
519
-        } else {
520
-            return Horde_Date::_mktime(0, 0, 0, $this->month, $this->mday, $this->year);
521
-        }
522
-    }
523
-
524
-    /**
525
-     * Format time using the specifiers available in date() or in the DateTime
526
-     * class' format() method.
527
-     *
528
-     * @since Horde 3.3
529
-     *
530
-     * @param string $format
531
-     *
532
-     * @return string  Formatted time.
533
-     */
534
-    function format($format)
535
-    {
536
-        if (class_exists('DateTime')) {
537
-            $dt = new DateTime();
538
-            $dt->setDate($this->year, $this->month, $this->mday);
539
-            $dt->setTime($this->hour, $this->min, $this->sec);
540
-            return $dt->format($format);
541
-        } else {
542
-            return date($format, $this->timestamp());
543
-        }
544
-    }
545
-
546
-    /**
547
-     * Format time in ISO-8601 format. Works correctly since Horde 3.2.
548
-     *
549
-     * @return string  Date and time in ISO-8601 format.
550
-     */
551
-    function iso8601DateTime()
552
-    {
553
-        return $this->rfc3339DateTime() . $this->tzOffset();
554
-    }
555
-
556
-    /**
557
-     * Format time in RFC 2822 format.
558
-     *
559
-     * @return string  Date and time in RFC 2822 format.
560
-     */
561
-    function rfc2822DateTime()
562
-    {
563
-        return $this->format('D, j M Y H:i:s') . ' ' . $this->tzOffset(false);
564
-    }
565
-
566
-    /**
567
-     * Format time in RFC 3339 format.
568
-     *
569
-     * @since Horde 3.1
570
-     *
571
-     * @return string  Date and time in RFC 3339 format. The seconds part has
572
-     *                 been added with Horde 3.2.
573
-     */
574
-    function rfc3339DateTime()
575
-    {
576
-        return $this->format('Y-m-d\TH:i:s');
577
-    }
578
-
579
-    /**
580
-     * Format time to standard 'ctime' format.
581
-     *
582
-     * @return string  Date and time.
583
-     */
584
-    function cTime()
585
-    {
586
-        return $this->format('D M j H:i:s Y');
587
-    }
588
-
589
-    /**
590
-     * Format date and time using strftime() format.
591
-     *
592
-     * @since Horde 3.1
593
-     *
594
-     * @return string  strftime() formatted date and time.
595
-     */
596
-    function strftime($format)
597
-    {
598
-        if (preg_match('/%[^' . $this->_supportedSpecs . ']/', $format)) {
599
-            return strftime($format, $this->timestamp());
600
-        } else {
601
-            return $this->_strftime($format);
602
-        }
603
-    }
604
-
605
-    /**
606
-     * Format date and time using a limited set of the strftime() format.
607
-     *
608
-     * @return string  strftime() formatted date and time.
609
-     */
610
-    function _strftime($format)
611
-    {
612
-        if (preg_match('/%[bBpxX]/', $format)) {
613
-            require_once 'Horde/NLS.php';
614
-        }
615
-
616
-        return preg_replace(
617
-            array('/%b/e',
618
-                  '/%B/e',
619
-                  '/%C/e',
620
-                  '/%d/e',
621
-                  '/%D/e',
622
-                  '/%e/e',
623
-                  '/%H/e',
624
-                  '/%I/e',
625
-                  '/%m/e',
626
-                  '/%M/e',
627
-                  '/%n/',
628
-                  '/%p/e',
629
-                  '/%R/e',
630
-                  '/%S/e',
631
-                  '/%t/',
632
-                  '/%T/e',
633
-                  '/%x/e',
634
-                  '/%X/e',
635
-                  '/%y/e',
636
-                  '/%Y/',
637
-                  '/%%/'),
638
-            array('$this->_strftime(NLS::getLangInfo(constant(\'ABMON_\' . (int)$this->month)))',
639
-                  '$this->_strftime(NLS::getLangInfo(constant(\'MON_\' . (int)$this->month)))',
640
-                  '(int)($this->year / 100)',
641
-                  'sprintf(\'%02d\', $this->mday)',
642
-                  '$this->_strftime(\'%m/%d/%y\')',
643
-                  'sprintf(\'%2d\', $this->mday)',
644
-                  'sprintf(\'%02d\', $this->hour)',
645
-                  'sprintf(\'%02d\', $this->hour == 0 ? 12 : ($this->hour > 12 ? $this->hour - 12 : $this->hour))',
646
-                  'sprintf(\'%02d\', $this->month)',
647
-                  'sprintf(\'%02d\', $this->min)',
648
-                  "\n",
649
-                  '$this->_strftime(NLS::getLangInfo($this->hour < 12 ? AM_STR : PM_STR))',
650
-                  '$this->_strftime(\'%H:%M\')',
651
-                  'sprintf(\'%02d\', $this->sec)',
652
-                  "\t",
653
-                  '$this->_strftime(\'%H:%M:%S\')',
654
-                  '$this->_strftime(NLS::getLangInfo(D_FMT))',
655
-                  '$this->_strftime(NLS::getLangInfo(T_FMT))',
656
-                  'substr(sprintf(\'%04d\', $this->year), -2)',
657
-                  (int)$this->year,
658
-                  '%'),
659
-            $format);
660
-    }
661
-
662
-    /**
663
-     * mktime() implementation that supports dates outside of 1970-2038,
664
-     * from http://phplens.com/phpeverywhere/adodb_date_library.
665
-     *
666
-     * @TODO remove in Horde 4
667
-     *
668
-     * This does NOT work with pre-1970 daylight saving times.
669
-     *
670
-     * @static
671
-     */
672
-    function _mktime($hr, $min, $sec, $mon = false, $day = false,
673
-                     $year = false, $is_dst = false, $is_gmt = false)
674
-    {
675
-        if ($mon === false) {
676
-            return $is_gmt
677
-                ? @gmmktime($hr, $min, $sec)
678
-                : @mktime($hr, $min, $sec);
679
-        }
680
-
681
-        if ($year > 1901 && $year < 2038 &&
682
-            ($year >= 1970 || version_compare(PHP_VERSION, '5.0.0', '>='))) {
683
-            return $is_gmt
684
-                ? @gmmktime($hr, $min, $sec, $mon, $day, $year)
685
-                : @mktime($hr, $min, $sec, $mon, $day, $year);
686
-        }
687
-
688
-        $gmt_different = $is_gmt
689
-            ? 0
690
-            : (mktime(0, 0, 0, 1, 2, 1970, 0) - gmmktime(0, 0, 0, 1, 2, 1970, 0));
691
-
692
-        $mon = intval($mon);
693
-        $day = intval($day);
694
-        $year = intval($year);
695
-
696
-        if ($mon > 12) {
697
-            $y = floor($mon / 12);
698
-            $year += $y;
699
-            $mon -= $y * 12;
700
-        } elseif ($mon < 1) {
701
-            $y = ceil((1 - $mon) / 12);
702
-            $year -= $y;
703
-            $mon += $y * 12;
704
-        }
705
-
706
-        $_day_power = 86400;
707
-        $_hour_power = 3600;
708
-        $_min_power = 60;
709
-
710
-        $_month_table_normal = array('', 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
711
-        $_month_table_leaf = array('', 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
712
-
713
-        $_total_date = 0;
714
-        if ($year >= 1970) {
715
-            for ($a = 1970; $a <= $year; $a++) {
716
-                $leaf = Horde_Date::isLeapYear($a);
717
-                if ($leaf == true) {
718
-                    $loop_table = $_month_table_leaf;
719
-                    $_add_date = 366;
720
-                } else {
721
-                    $loop_table = $_month_table_normal;
722
-                    $_add_date = 365;
723
-                }
724
-                if ($a < $year) {
725
-                    $_total_date += $_add_date;
726
-                } else {
727
-                    for ($b = 1; $b < $mon; $b++) {
728
-                        $_total_date += $loop_table[$b];
729
-                    }
730
-                }
731
-            }
732
-
733
-            return ($_total_date + $day - 1) * $_day_power + $hr * $_hour_power + $min * $_min_power + $sec + $gmt_different;
734
-        }
735
-
736
-        for ($a = 1969 ; $a >= $year; $a--) {
737
-            $leaf = Horde_Date::isLeapYear($a);
738
-            if ($leaf == true) {
739
-                $loop_table = $_month_table_leaf;
740
-                $_add_date = 366;
741
-            } else {
742
-                $loop_table = $_month_table_normal;
743
-                $_add_date = 365;
744
-            }
745
-            if ($a > $year) {
746
-                $_total_date += $_add_date;
747
-            } else {
748
-                for ($b = 12; $b > $mon; $b--) {
749
-                    $_total_date += $loop_table[$b];
750
-                }
751
-            }
752
-        }
753
-
754
-        $_total_date += $loop_table[$mon] - $day;
755
-        $_day_time = $hr * $_hour_power + $min * $_min_power + $sec;
756
-        $_day_time = $_day_power - $_day_time;
757
-        $ret = -($_total_date * $_day_power + $_day_time - $gmt_different);
758
-        if ($ret < -12220185600) {
759
-            // If earlier than 5 Oct 1582 - gregorian correction.
760
-            return $ret + 10 * 86400;
761
-        } elseif ($ret < -12219321600) {
762
-            // If in limbo, reset to 15 Oct 1582.
763
-            return -12219321600;
764
-        } else {
765
-            return $ret;
766
-        }
767
-    }
40
+	/**
41
+	 * Year
42
+	 *
43
+	 * @var integer
44
+	 */
45
+	var $year;
46
+
47
+	/**
48
+	 * Month
49
+	 *
50
+	 * @var integer
51
+	 */
52
+	var $month;
53
+
54
+	/**
55
+	 * Day
56
+	 *
57
+	 * @var integer
58
+	 */
59
+	var $mday;
60
+
61
+	/**
62
+	 * Hour
63
+	 *
64
+	 * @var integer
65
+	 */
66
+	var $hour = 0;
67
+
68
+	/**
69
+	 * Minute
70
+	 *
71
+	 * @var integer
72
+	 */
73
+	var $min = 0;
74
+
75
+	/**
76
+	 * Second
77
+	 *
78
+	 * @var integer
79
+	 */
80
+	var $sec = 0;
81
+
82
+	/**
83
+	 * Internally supported strftime() specifiers.
84
+	 *
85
+	 * @var string
86
+	 */
87
+	var $_supportedSpecs = '%CdDeHImMnRStTyY';
88
+
89
+	/**
90
+	 * Build a new date object. If $date contains date parts, use them to
91
+	 * initialize the object.
92
+	 *
93
+	 * Recognized formats:
94
+	 * - arrays with keys 'year', 'month', 'mday', 'day' (since Horde 3.2),
95
+	 *   'hour', 'min', 'minute' (since Horde 3.2), 'sec'
96
+	 * - objects with properties 'year', 'month', 'mday', 'hour', 'min', 'sec'
97
+	 * - yyyy-mm-dd hh:mm:ss (since Horde 3.1)
98
+	 * - yyyymmddhhmmss (since Horde 3.1)
99
+	 * - yyyymmddThhmmssZ (since Horde 3.1.4)
100
+	 * - unix timestamps
101
+	 */
102
+	function Horde_Date($date = null)
103
+	{
104
+		if (function_exists('nl_langinfo')) {
105
+			$this->_supportedSpecs .= 'bBpxX';
106
+		}
107
+
108
+		if (is_array($date) || is_object($date)) {
109
+			foreach ($date as $key => $val) {
110
+				if (in_array($key, array('year', 'month', 'mday', 'hour', 'min', 'sec'))) {
111
+					$this->$key = (int)$val;
112
+				}
113
+			}
114
+
115
+			// If $date['day'] is present and numeric we may have been passed
116
+			// a Horde_Form_datetime array.
117
+			if (is_array($date) && isset($date['day']) &&
118
+				is_numeric($date['day'])) {
119
+				$this->mday = (int)$date['day'];
120
+			}
121
+			// 'minute' key also from Horde_Form_datetime
122
+			if (is_array($date) && isset($date['minute'])) {
123
+				$this->min = $date['minute'];
124
+			}
125
+		} elseif (!is_null($date)) {
126
+			// Match YYYY-MM-DD HH:MM:SS, YYYYMMDDHHMMSS and YYYYMMDD'T'HHMMSS'Z'.
127
+			if (preg_match('/(\d{4})-?(\d{2})-?(\d{2})T? ?(\d{2}):?(\d{2}):?(\d{2})Z?/', $date, $parts)) {
128
+				$this->year = (int)$parts[1];
129
+				$this->month = (int)$parts[2];
130
+				$this->mday = (int)$parts[3];
131
+				$this->hour = (int)$parts[4];
132
+				$this->min = (int)$parts[5];
133
+				$this->sec = (int)$parts[6];
134
+			} else {
135
+				// Try as a timestamp.
136
+				$parts = @getdate($date);
137
+				if ($parts) {
138
+					$this->year = $parts['year'];
139
+					$this->month = $parts['mon'];
140
+					$this->mday = $parts['mday'];
141
+					$this->hour = $parts['hours'];
142
+					$this->min = $parts['minutes'];
143
+					$this->sec = $parts['seconds'];
144
+				}
145
+			}
146
+		}
147
+	}
148
+
149
+	/**
150
+	 * @static
151
+	 */
152
+	function isLeapYear($year)
153
+	{
154
+		if (strlen($year) != 4 || preg_match('/\D/', $year)) {
155
+			return false;
156
+		}
157
+
158
+		return (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0);
159
+	}
160
+
161
+	/**
162
+	 * Returns the day of the year (1-366) that corresponds to the
163
+	 * first day of the given week.
164
+	 *
165
+	 * TODO: with PHP 5.1+, see http://derickrethans.nl/calculating_start_and_end_dates_of_a_week.php
166
+	 *
167
+	 * @param integer $week  The week of the year to find the first day of.
168
+	 * @param integer $year  The year to calculate for.
169
+	 *
170
+	 * @return integer  The day of the year of the first day of the given week.
171
+	 */
172
+	function firstDayOfWeek($week, $year)
173
+	{
174
+		$jan1 = new Horde_Date(array('year' => $year, 'month' => 1, 'mday' => 1));
175
+		$start = $jan1->dayOfWeek();
176
+		if ($start > HORDE_DATE_THURSDAY) {
177
+			$start -= 7;
178
+		}
179
+		return (($week * 7) - (7 + $start)) + 1;
180
+	}
181
+
182
+	/**
183
+	 * @static
184
+	 */
185
+	function daysInMonth($month, $year)
186
+	{
187
+		if ($month == 2) {
188
+			if (Horde_Date::isLeapYear($year)) {
189
+				return 29;
190
+			} else {
191
+				return 28;
192
+			}
193
+		} elseif ($month == 4 || $month == 6 || $month == 9 || $month == 11) {
194
+			return 30;
195
+		} else {
196
+			return 31;
197
+		}
198
+	}
199
+
200
+	/**
201
+	 * Return the day of the week (0 = Sunday, 6 = Saturday) of this
202
+	 * object's date.
203
+	 *
204
+	 * @return integer  The day of the week.
205
+	 */
206
+	function dayOfWeek()
207
+	{
208
+		if ($this->month > 2) {
209
+			$month = $this->month - 2;
210
+			$year = $this->year;
211
+		} else {
212
+			$month = $this->month + 10;
213
+			$year = $this->year - 1;
214
+		}
215
+
216
+		$day = (floor((13 * $month - 1) / 5) +
217
+				$this->mday + ($year % 100) +
218
+				floor(($year % 100) / 4) +
219
+				floor(($year / 100) / 4) - 2 *
220
+				floor($year / 100) + 77);
221
+
222
+		return (int)($day - 7 * floor($day / 7));
223
+	}
224
+
225
+	/**
226
+	 * Returns the day number of the year (1 to 365/366).
227
+	 *
228
+	 * @return integer  The day of the year.
229
+	 */
230
+	function dayOfYear()
231
+	{
232
+		$monthTotals = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
233
+		$dayOfYear = $this->mday + $monthTotals[$this->month - 1];
234
+		if (Horde_Date::isLeapYear($this->year) && $this->month > 2) {
235
+			++$dayOfYear;
236
+		}
237
+
238
+		return $dayOfYear;
239
+	}
240
+
241
+	/**
242
+	 * Returns the week of the month.
243
+	 *
244
+	 * @since Horde 3.2
245
+	 *
246
+	 * @return integer  The week number.
247
+	 */
248
+	function weekOfMonth()
249
+	{
250
+		return ceil($this->mday / 7);
251
+	}
252
+
253
+	/**
254
+	 * Returns the week of the year, first Monday is first day of first week.
255
+	 *
256
+	 * @return integer  The week number.
257
+	 */
258
+	function weekOfYear()
259
+	{
260
+		return $this->format('W');
261
+	}
262
+
263
+	/**
264
+	 * Return the number of weeks in the given year (52 or 53).
265
+	 *
266
+	 * @static
267
+	 *
268
+	 * @param integer $year  The year to count the number of weeks in.
269
+	 *
270
+	 * @return integer $numWeeks   The number of weeks in $year.
271
+	 */
272
+	function weeksInYear($year)
273
+	{
274
+		// Find the last Thursday of the year.
275
+		$day = 31;
276
+		$date = new Horde_Date(array('year' => $year, 'month' => 12, 'mday' => $day, 'hour' => 0, 'min' => 0, 'sec' => 0));
277
+		while ($date->dayOfWeek() != HORDE_DATE_THURSDAY) {
278
+			--$date->mday;
279
+		}
280
+		return $date->weekOfYear();
281
+	}
282
+
283
+	/**
284
+	 * Set the date of this object to the $nth weekday of $weekday.
285
+	 *
286
+	 * @param integer $weekday  The day of the week (0 = Sunday, etc).
287
+	 * @param integer $nth      The $nth $weekday to set to (defaults to 1).
288
+	 */
289
+	function setNthWeekday($weekday, $nth = 1)
290
+	{
291
+		if ($weekday < HORDE_DATE_SUNDAY || $weekday > HORDE_DATE_SATURDAY) {
292
+			return false;
293
+		}
294
+
295
+		$this->mday = 1;
296
+		$first = $this->dayOfWeek();
297
+		if ($weekday < $first) {
298
+			$this->mday = 8 + $weekday - $first;
299
+		} else {
300
+			$this->mday = $weekday - $first + 1;
301
+		}
302
+		$this->mday += 7 * $nth - 7;
303
+
304
+		$this->correct();
305
+
306
+		return true;
307
+	}
308
+
309
+	function dump($prefix = '')
310
+	{
311
+		echo ($prefix ? $prefix . ': ' : '') . $this->year . '-' . $this->month . '-' . $this->mday . "<br />\n";
312
+	}
313
+
314
+	/**
315
+	 * Is the date currently represented by this object a valid date?
316
+	 *
317
+	 * @return boolean  Validity, counting leap years, etc.
318
+	 */
319
+	function isValid()
320
+	{
321
+		if ($this->year < 0 || $this->year > 9999) {
322
+			return false;
323
+		}
324
+		return checkdate($this->month, $this->mday, $this->year);
325
+	}
326
+
327
+	/**
328
+	 * Correct any over- or underflows in any of the date's members.
329
+	 *
330
+	 * @param integer $mask  We may not want to correct some overflows.
331
+	 */
332
+	function correct($mask = HORDE_DATE_MASK_ALLPARTS)
333
+	{
334
+		if ($mask & HORDE_DATE_MASK_SECOND) {
335
+			while ($this->sec < 0) {
336
+				--$this->min;
337
+				$this->sec += 60;
338
+			}
339
+			while ($this->sec > 59) {
340
+				++$this->min;
341
+				$this->sec -= 60;
342
+			}
343
+		}
344
+
345
+		if ($mask & HORDE_DATE_MASK_MINUTE) {
346
+			while ($this->min < 0) {
347
+				--$this->hour;
348
+				$this->min += 60;
349
+			}
350
+			while ($this->min > 59) {
351
+				++$this->hour;
352
+				$this->min -= 60;
353
+			}
354
+		}
355
+
356
+		if ($mask & HORDE_DATE_MASK_HOUR) {
357
+			while ($this->hour < 0) {
358
+				--$this->mday;
359
+				$this->hour += 24;
360
+			}
361
+			while ($this->hour > 23) {
362
+				++$this->mday;
363
+				$this->hour -= 24;
364
+			}
365
+		}
366
+
367
+		if ($mask & HORDE_DATE_MASK_MONTH) {
368
+			while ($this->month > 12) {
369
+				++$this->year;
370
+				$this->month -= 12;
371
+			}
372
+			while ($this->month < 1) {
373
+				--$this->year;
374
+				$this->month += 12;
375
+			}
376
+		}
377
+
378
+		if ($mask & HORDE_DATE_MASK_DAY) {
379
+			while ($this->mday > Horde_Date::daysInMonth($this->month, $this->year)) {
380
+				$this->mday -= Horde_Date::daysInMonth($this->month, $this->year);
381
+				++$this->month;
382
+				$this->correct(HORDE_DATE_MASK_MONTH);
383
+			}
384
+			while ($this->mday < 1) {
385
+				--$this->month;
386
+				$this->correct(HORDE_DATE_MASK_MONTH);
387
+				$this->mday += Horde_Date::daysInMonth($this->month, $this->year);
388
+			}
389
+		}
390
+	}
391
+
392
+	/**
393
+	 * Compare this date to another date object to see which one is
394
+	 * greater (later). Assumes that the dates are in the same
395
+	 * timezone.
396
+	 *
397
+	 * @param mixed $date  The date to compare to.
398
+	 *
399
+	 * @return integer  ==  0 if the dates are equal
400
+	 *                  >=  1 if this date is greater (later)
401
+	 *                  <= -1 if the other date is greater (later)
402
+	 */
403
+	function compareDate($date)
404
+	{
405
+		if (!is_a($date, 'Horde_Date')) {
406
+			$date = new Horde_Date($date);
407
+		}
408
+
409
+		if ($this->year != $date->year) {
410
+			return $this->year - $date->year;
411
+		}
412
+		if ($this->month != $date->month) {
413
+			return $this->month - $date->month;
414
+		}
415
+
416
+		return $this->mday - $date->mday;
417
+	}
418
+
419
+	/**
420
+	 * Compare this to another date object by time, to see which one
421
+	 * is greater (later). Assumes that the dates are in the same
422
+	 * timezone.
423
+	 *
424
+	 * @param mixed $date  The date to compare to.
425
+	 *
426
+	 * @return integer  ==  0 if the dates are equal
427
+	 *                  >=  1 if this date is greater (later)
428
+	 *                  <= -1 if the other date is greater (later)
429
+	 */
430
+	function compareTime($date)
431
+	{
432
+		if (!is_a($date, 'Horde_Date')) {
433
+			$date = new Horde_Date($date);
434
+		}
435
+
436
+		if ($this->hour != $date->hour) {
437
+			return $this->hour - $date->hour;
438
+		}
439
+		if ($this->min != $date->min) {
440
+			return $this->min - $date->min;
441
+		}
442
+
443
+		return $this->sec - $date->sec;
444
+	}
445
+
446
+	/**
447
+	 * Compare this to another date object, including times, to see
448
+	 * which one is greater (later). Assumes that the dates are in the
449
+	 * same timezone.
450
+	 *
451
+	 * @param mixed $date  The date to compare to.
452
+	 *
453
+	 * @return integer  ==  0 if the dates are equal
454
+	 *                  >=  1 if this date is greater (later)
455
+	 *                  <= -1 if the other date is greater (later)
456
+	 */
457
+	function compareDateTime($date)
458
+	{
459
+		if (!is_a($date, 'Horde_Date')) {
460
+			$date = new Horde_Date($date);
461
+		}
462
+
463
+		if ($diff = $this->compareDate($date)) {
464
+			return $diff;
465
+		}
466
+
467
+		return $this->compareTime($date);
468
+	}
469
+
470
+	/**
471
+	 * Get the time offset for local time zone.
472
+	 *
473
+	 * @param boolean $colon  Place a colon between hours and minutes?
474
+	 *
475
+	 * @return string  Timezone offset as a string in the format +HH:MM.
476
+	 */
477
+	function tzOffset($colon = true)
478
+	{
479
+		$secs = $this->format('Z');
480
+
481
+		if ($secs < 0) {
482
+			$sign = '-';
483
+			$secs = -$secs;
484
+		} else {
485
+			$sign = '+';
486
+		}
487
+		$colon = $colon ? ':' : '';
488
+		$mins = intval(($secs + 30) / 60);
489
+		return sprintf('%s%02d%s%02d',
490
+					   $sign, $mins / 60, $colon, $mins % 60);
491
+	}
492
+
493
+	/**
494
+	 * Return the unix timestamp representation of this date.
495
+	 *
496
+	 * @return integer  A unix timestamp.
497
+	 */
498
+	function timestamp()
499
+	{
500
+		if (class_exists('DateTime')) {
501
+			return $this->format('U');
502
+		} else {
503
+			return Horde_Date::_mktime($this->hour, $this->min, $this->sec, $this->month, $this->mday, $this->year);
504
+		}
505
+	}
506
+
507
+	/**
508
+	 * Return the unix timestamp representation of this date, 12:00am.
509
+	 *
510
+	 * @return integer  A unix timestamp.
511
+	 */
512
+	function datestamp()
513
+	{
514
+		if (class_exists('DateTime')) {
515
+			$dt = new DateTime();
516
+			$dt->setDate($this->year, $this->month, $this->mday);
517
+			$dt->setTime(0, 0, 0);
518
+			return $dt->format('U');
519
+		} else {
520
+			return Horde_Date::_mktime(0, 0, 0, $this->month, $this->mday, $this->year);
521
+		}
522
+	}
523
+
524
+	/**
525
+	 * Format time using the specifiers available in date() or in the DateTime
526
+	 * class' format() method.
527
+	 *
528
+	 * @since Horde 3.3
529
+	 *
530
+	 * @param string $format
531
+	 *
532
+	 * @return string  Formatted time.
533
+	 */
534
+	function format($format)
535
+	{
536
+		if (class_exists('DateTime')) {
537
+			$dt = new DateTime();
538
+			$dt->setDate($this->year, $this->month, $this->mday);
539
+			$dt->setTime($this->hour, $this->min, $this->sec);
540
+			return $dt->format($format);
541
+		} else {
542
+			return date($format, $this->timestamp());
543
+		}
544
+	}
545
+
546
+	/**
547
+	 * Format time in ISO-8601 format. Works correctly since Horde 3.2.
548
+	 *
549
+	 * @return string  Date and time in ISO-8601 format.
550
+	 */
551
+	function iso8601DateTime()
552
+	{
553
+		return $this->rfc3339DateTime() . $this->tzOffset();
554
+	}
555
+
556
+	/**
557
+	 * Format time in RFC 2822 format.
558
+	 *
559
+	 * @return string  Date and time in RFC 2822 format.
560
+	 */
561
+	function rfc2822DateTime()
562
+	{
563
+		return $this->format('D, j M Y H:i:s') . ' ' . $this->tzOffset(false);
564
+	}
565
+
566
+	/**
567
+	 * Format time in RFC 3339 format.
568
+	 *
569
+	 * @since Horde 3.1
570
+	 *
571
+	 * @return string  Date and time in RFC 3339 format. The seconds part has
572
+	 *                 been added with Horde 3.2.
573
+	 */
574
+	function rfc3339DateTime()
575
+	{
576
+		return $this->format('Y-m-d\TH:i:s');
577
+	}
578
+
579
+	/**
580
+	 * Format time to standard 'ctime' format.
581
+	 *
582
+	 * @return string  Date and time.
583
+	 */
584
+	function cTime()
585
+	{
586
+		return $this->format('D M j H:i:s Y');
587
+	}
588
+
589
+	/**
590
+	 * Format date and time using strftime() format.
591
+	 *
592
+	 * @since Horde 3.1
593
+	 *
594
+	 * @return string  strftime() formatted date and time.
595
+	 */
596
+	function strftime($format)
597
+	{
598
+		if (preg_match('/%[^' . $this->_supportedSpecs . ']/', $format)) {
599
+			return strftime($format, $this->timestamp());
600
+		} else {
601
+			return $this->_strftime($format);
602
+		}
603
+	}
604
+
605
+	/**
606
+	 * Format date and time using a limited set of the strftime() format.
607
+	 *
608
+	 * @return string  strftime() formatted date and time.
609
+	 */
610
+	function _strftime($format)
611
+	{
612
+		if (preg_match('/%[bBpxX]/', $format)) {
613
+			require_once 'Horde/NLS.php';
614
+		}
615
+
616
+		return preg_replace(
617
+			array('/%b/e',
618
+				  '/%B/e',
619
+				  '/%C/e',
620
+				  '/%d/e',
621
+				  '/%D/e',
622
+				  '/%e/e',
623
+				  '/%H/e',
624
+				  '/%I/e',
625
+				  '/%m/e',
626
+				  '/%M/e',
627
+				  '/%n/',
628
+				  '/%p/e',
629
+				  '/%R/e',
630
+				  '/%S/e',
631
+				  '/%t/',
632
+				  '/%T/e',
633
+				  '/%x/e',
634
+				  '/%X/e',
635
+				  '/%y/e',
636
+				  '/%Y/',
637
+				  '/%%/'),
638
+			array('$this->_strftime(NLS::getLangInfo(constant(\'ABMON_\' . (int)$this->month)))',
639
+				  '$this->_strftime(NLS::getLangInfo(constant(\'MON_\' . (int)$this->month)))',
640
+				  '(int)($this->year / 100)',
641
+				  'sprintf(\'%02d\', $this->mday)',
642
+				  '$this->_strftime(\'%m/%d/%y\')',
643
+				  'sprintf(\'%2d\', $this->mday)',
644
+				  'sprintf(\'%02d\', $this->hour)',
645
+				  'sprintf(\'%02d\', $this->hour == 0 ? 12 : ($this->hour > 12 ? $this->hour - 12 : $this->hour))',
646
+				  'sprintf(\'%02d\', $this->month)',
647
+				  'sprintf(\'%02d\', $this->min)',
648
+				  "\n",
649
+				  '$this->_strftime(NLS::getLangInfo($this->hour < 12 ? AM_STR : PM_STR))',
650
+				  '$this->_strftime(\'%H:%M\')',
651
+				  'sprintf(\'%02d\', $this->sec)',
652
+				  "\t",
653
+				  '$this->_strftime(\'%H:%M:%S\')',
654
+				  '$this->_strftime(NLS::getLangInfo(D_FMT))',
655
+				  '$this->_strftime(NLS::getLangInfo(T_FMT))',
656
+				  'substr(sprintf(\'%04d\', $this->year), -2)',
657
+				  (int)$this->year,
658
+				  '%'),
659
+			$format);
660
+	}
661
+
662
+	/**
663
+	 * mktime() implementation that supports dates outside of 1970-2038,
664
+	 * from http://phplens.com/phpeverywhere/adodb_date_library.
665
+	 *
666
+	 * @TODO remove in Horde 4
667
+	 *
668
+	 * This does NOT work with pre-1970 daylight saving times.
669
+	 *
670
+	 * @static
671
+	 */
672
+	function _mktime($hr, $min, $sec, $mon = false, $day = false,
673
+					 $year = false, $is_dst = false, $is_gmt = false)
674
+	{
675
+		if ($mon === false) {
676
+			return $is_gmt
677
+				? @gmmktime($hr, $min, $sec)
678
+				: @mktime($hr, $min, $sec);
679
+		}
680
+
681
+		if ($year > 1901 && $year < 2038 &&
682
+			($year >= 1970 || version_compare(PHP_VERSION, '5.0.0', '>='))) {
683
+			return $is_gmt
684
+				? @gmmktime($hr, $min, $sec, $mon, $day, $year)
685
+				: @mktime($hr, $min, $sec, $mon, $day, $year);
686
+		}
687
+
688
+		$gmt_different = $is_gmt
689
+			? 0
690
+			: (mktime(0, 0, 0, 1, 2, 1970, 0) - gmmktime(0, 0, 0, 1, 2, 1970, 0));
691
+
692
+		$mon = intval($mon);
693
+		$day = intval($day);
694
+		$year = intval($year);
695
+
696
+		if ($mon > 12) {
697
+			$y = floor($mon / 12);
698
+			$year += $y;
699
+			$mon -= $y * 12;
700
+		} elseif ($mon < 1) {
701
+			$y = ceil((1 - $mon) / 12);
702
+			$year -= $y;
703
+			$mon += $y * 12;
704
+		}
705
+
706
+		$_day_power = 86400;
707
+		$_hour_power = 3600;
708
+		$_min_power = 60;
709
+
710
+		$_month_table_normal = array('', 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
711
+		$_month_table_leaf = array('', 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
712
+
713
+		$_total_date = 0;
714
+		if ($year >= 1970) {
715
+			for ($a = 1970; $a <= $year; $a++) {
716
+				$leaf = Horde_Date::isLeapYear($a);
717
+				if ($leaf == true) {
718
+					$loop_table = $_month_table_leaf;
719
+					$_add_date = 366;
720
+				} else {
721
+					$loop_table = $_month_table_normal;
722
+					$_add_date = 365;
723
+				}
724
+				if ($a < $year) {
725
+					$_total_date += $_add_date;
726
+				} else {
727
+					for ($b = 1; $b < $mon; $b++) {
728
+						$_total_date += $loop_table[$b];
729
+					}
730
+				}
731
+			}
732
+
733
+			return ($_total_date + $day - 1) * $_day_power + $hr * $_hour_power + $min * $_min_power + $sec + $gmt_different;
734
+		}
735
+
736
+		for ($a = 1969 ; $a >= $year; $a--) {
737
+			$leaf = Horde_Date::isLeapYear($a);
738
+			if ($leaf == true) {
739
+				$loop_table = $_month_table_leaf;
740
+				$_add_date = 366;
741
+			} else {
742
+				$loop_table = $_month_table_normal;
743
+				$_add_date = 365;
744
+			}
745
+			if ($a > $year) {
746
+				$_total_date += $_add_date;
747
+			} else {
748
+				for ($b = 12; $b > $mon; $b--) {
749
+					$_total_date += $loop_table[$b];
750
+				}
751
+			}
752
+		}
753
+
754
+		$_total_date += $loop_table[$mon] - $day;
755
+		$_day_time = $hr * $_hour_power + $min * $_min_power + $sec;
756
+		$_day_time = $_day_power - $_day_time;
757
+		$ret = -($_total_date * $_day_power + $_day_time - $gmt_different);
758
+		if ($ret < -12220185600) {
759
+			// If earlier than 5 Oct 1582 - gregorian correction.
760
+			return $ret + 10 * 86400;
761
+		} elseif ($ret < -12219321600) {
762
+			// If in limbo, reset to 15 Oct 1582.
763
+			return -12219321600;
764
+		} else {
765
+			return $ret;
766
+		}
767
+	}
768 768
 
769 769
 }
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -1,30 +1,30 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-define('HORDE_DATE_SUNDAY',    0);
4
-define('HORDE_DATE_MONDAY',    1);
5
-define('HORDE_DATE_TUESDAY',   2);
3
+define('HORDE_DATE_SUNDAY', 0);
4
+define('HORDE_DATE_MONDAY', 1);
5
+define('HORDE_DATE_TUESDAY', 2);
6 6
 define('HORDE_DATE_WEDNESDAY', 3);
7
-define('HORDE_DATE_THURSDAY',  4);
8
-define('HORDE_DATE_FRIDAY',    5);
9
-define('HORDE_DATE_SATURDAY',  6);
7
+define('HORDE_DATE_THURSDAY', 4);
8
+define('HORDE_DATE_FRIDAY', 5);
9
+define('HORDE_DATE_SATURDAY', 6);
10 10
 
11
-define('HORDE_DATE_MASK_SUNDAY',    1);
12
-define('HORDE_DATE_MASK_MONDAY',    2);
13
-define('HORDE_DATE_MASK_TUESDAY',   4);
11
+define('HORDE_DATE_MASK_SUNDAY', 1);
12
+define('HORDE_DATE_MASK_MONDAY', 2);
13
+define('HORDE_DATE_MASK_TUESDAY', 4);
14 14
 define('HORDE_DATE_MASK_WEDNESDAY', 8);
15 15
 define('HORDE_DATE_MASK_THURSDAY', 16);
16
-define('HORDE_DATE_MASK_FRIDAY',   32);
16
+define('HORDE_DATE_MASK_FRIDAY', 32);
17 17
 define('HORDE_DATE_MASK_SATURDAY', 64);
18 18
 define('HORDE_DATE_MASK_WEEKDAYS', 62);
19
-define('HORDE_DATE_MASK_WEEKEND',  65);
19
+define('HORDE_DATE_MASK_WEEKEND', 65);
20 20
 define('HORDE_DATE_MASK_ALLDAYS', 127);
21 21
 
22
-define('HORDE_DATE_MASK_SECOND',    1);
23
-define('HORDE_DATE_MASK_MINUTE',    2);
24
-define('HORDE_DATE_MASK_HOUR',      4);
25
-define('HORDE_DATE_MASK_DAY',       8);
26
-define('HORDE_DATE_MASK_MONTH',    16);
27
-define('HORDE_DATE_MASK_YEAR',     32);
22
+define('HORDE_DATE_MASK_SECOND', 1);
23
+define('HORDE_DATE_MASK_MINUTE', 2);
24
+define('HORDE_DATE_MASK_HOUR', 4);
25
+define('HORDE_DATE_MASK_DAY', 8);
26
+define('HORDE_DATE_MASK_MONTH', 16);
27
+define('HORDE_DATE_MASK_YEAR', 32);
28 28
 define('HORDE_DATE_MASK_ALLPARTS', 63);
29 29
 
30 30
 /**
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
 
309 309
     function dump($prefix = '')
310 310
     {
311
-        echo ($prefix ? $prefix . ': ' : '') . $this->year . '-' . $this->month . '-' . $this->mday . "<br />\n";
311
+        echo ($prefix ? $prefix.': ' : '').$this->year.'-'.$this->month.'-'.$this->mday."<br />\n";
312 312
     }
313 313
 
314 314
     /**
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
      */
332 332
     function correct($mask = HORDE_DATE_MASK_ALLPARTS)
333 333
     {
334
-        if ($mask & HORDE_DATE_MASK_SECOND) {
334
+        if ($mask&HORDE_DATE_MASK_SECOND) {
335 335
             while ($this->sec < 0) {
336 336
                 --$this->min;
337 337
                 $this->sec += 60;
@@ -342,7 +342,7 @@  discard block
 block discarded – undo
342 342
             }
343 343
         }
344 344
 
345
-        if ($mask & HORDE_DATE_MASK_MINUTE) {
345
+        if ($mask&HORDE_DATE_MASK_MINUTE) {
346 346
             while ($this->min < 0) {
347 347
                 --$this->hour;
348 348
                 $this->min += 60;
@@ -353,7 +353,7 @@  discard block
 block discarded – undo
353 353
             }
354 354
         }
355 355
 
356
-        if ($mask & HORDE_DATE_MASK_HOUR) {
356
+        if ($mask&HORDE_DATE_MASK_HOUR) {
357 357
             while ($this->hour < 0) {
358 358
                 --$this->mday;
359 359
                 $this->hour += 24;
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
             }
365 365
         }
366 366
 
367
-        if ($mask & HORDE_DATE_MASK_MONTH) {
367
+        if ($mask&HORDE_DATE_MASK_MONTH) {
368 368
             while ($this->month > 12) {
369 369
                 ++$this->year;
370 370
                 $this->month -= 12;
@@ -375,7 +375,7 @@  discard block
 block discarded – undo
375 375
             }
376 376
         }
377 377
 
378
-        if ($mask & HORDE_DATE_MASK_DAY) {
378
+        if ($mask&HORDE_DATE_MASK_DAY) {
379 379
             while ($this->mday > Horde_Date::daysInMonth($this->month, $this->year)) {
380 380
                 $this->mday -= Horde_Date::daysInMonth($this->month, $this->year);
381 381
                 ++$this->month;
@@ -550,7 +550,7 @@  discard block
 block discarded – undo
550 550
      */
551 551
     function iso8601DateTime()
552 552
     {
553
-        return $this->rfc3339DateTime() . $this->tzOffset();
553
+        return $this->rfc3339DateTime().$this->tzOffset();
554 554
     }
555 555
 
556 556
     /**
@@ -560,7 +560,7 @@  discard block
 block discarded – undo
560 560
      */
561 561
     function rfc2822DateTime()
562 562
     {
563
-        return $this->format('D, j M Y H:i:s') . ' ' . $this->tzOffset(false);
563
+        return $this->format('D, j M Y H:i:s').' '.$this->tzOffset(false);
564 564
     }
565 565
 
566 566
     /**
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
      */
596 596
     function strftime($format)
597 597
     {
598
-        if (preg_match('/%[^' . $this->_supportedSpecs . ']/', $format)) {
598
+        if (preg_match('/%[^'.$this->_supportedSpecs.']/', $format)) {
599 599
             return strftime($format, $this->timestamp());
600 600
         } else {
601 601
             return $this->_strftime($format);
@@ -733,7 +733,7 @@  discard block
 block discarded – undo
733 733
             return ($_total_date + $day - 1) * $_day_power + $hr * $_hour_power + $min * $_min_power + $sec + $gmt_different;
734 734
         }
735 735
 
736
-        for ($a = 1969 ; $a >= $year; $a--) {
736
+        for ($a = 1969; $a >= $year; $a--) {
737 737
             $leaf = Horde_Date::isLeapYear($a);
738 738
             if ($leaf == true) {
739 739
                 $loop_table = $_month_table_leaf;
Please login to merge, or discard this patch.
Braces   +179 added lines, -80 removed lines patch added patch discarded remove patch
@@ -35,7 +35,8 @@  discard block
 block discarded – undo
35 35
  *
36 36
  * @package Horde_Date
37 37
  */
38
-class Horde_Date {
38
+class Horde_Date
39
+{
39 40
 
40 41
     /**
41 42
      * Year
@@ -101,13 +102,17 @@  discard block
 block discarded – undo
101 102
      */
102 103
     function Horde_Date($date = null)
103 104
     {
104
-        if (function_exists('nl_langinfo')) {
105
+        if (function_exists('nl_langinfo'))
106
+        {
105 107
             $this->_supportedSpecs .= 'bBpxX';
106 108
         }
107 109
 
108
-        if (is_array($date) || is_object($date)) {
109
-            foreach ($date as $key => $val) {
110
-                if (in_array($key, array('year', 'month', 'mday', 'hour', 'min', 'sec'))) {
110
+        if (is_array($date) || is_object($date))
111
+        {
112
+            foreach ($date as $key => $val)
113
+            {
114
+                if (in_array($key, array('year', 'month', 'mday', 'hour', 'min', 'sec')))
115
+                {
111 116
                     $this->$key = (int)$val;
112 117
                 }
113 118
             }
@@ -115,26 +120,34 @@  discard block
 block discarded – undo
115 120
             // If $date['day'] is present and numeric we may have been passed
116 121
             // a Horde_Form_datetime array.
117 122
             if (is_array($date) && isset($date['day']) &&
118
-                is_numeric($date['day'])) {
123
+                is_numeric($date['day']))
124
+            {
119 125
                 $this->mday = (int)$date['day'];
120 126
             }
121 127
             // 'minute' key also from Horde_Form_datetime
122
-            if (is_array($date) && isset($date['minute'])) {
128
+            if (is_array($date) && isset($date['minute']))
129
+            {
123 130
                 $this->min = $date['minute'];
124 131
             }
125
-        } elseif (!is_null($date)) {
132
+        }
133
+        elseif (!is_null($date))
134
+        {
126 135
             // Match YYYY-MM-DD HH:MM:SS, YYYYMMDDHHMMSS and YYYYMMDD'T'HHMMSS'Z'.
127
-            if (preg_match('/(\d{4})-?(\d{2})-?(\d{2})T? ?(\d{2}):?(\d{2}):?(\d{2})Z?/', $date, $parts)) {
136
+            if (preg_match('/(\d{4})-?(\d{2})-?(\d{2})T? ?(\d{2}):?(\d{2}):?(\d{2})Z?/', $date, $parts))
137
+            {
128 138
                 $this->year = (int)$parts[1];
129 139
                 $this->month = (int)$parts[2];
130 140
                 $this->mday = (int)$parts[3];
131 141
                 $this->hour = (int)$parts[4];
132 142
                 $this->min = (int)$parts[5];
133 143
                 $this->sec = (int)$parts[6];
134
-            } else {
144
+            }
145
+            else
146
+            {
135 147
                 // Try as a timestamp.
136 148
                 $parts = @getdate($date);
137
-                if ($parts) {
149
+                if ($parts)
150
+                {
138 151
                     $this->year = $parts['year'];
139 152
                     $this->month = $parts['mon'];
140 153
                     $this->mday = $parts['mday'];
@@ -151,7 +164,8 @@  discard block
 block discarded – undo
151 164
      */
152 165
     function isLeapYear($year)
153 166
     {
154
-        if (strlen($year) != 4 || preg_match('/\D/', $year)) {
167
+        if (strlen($year) != 4 || preg_match('/\D/', $year))
168
+        {
155 169
             return false;
156 170
         }
157 171
 
@@ -173,7 +187,8 @@  discard block
 block discarded – undo
173 187
     {
174 188
         $jan1 = new Horde_Date(array('year' => $year, 'month' => 1, 'mday' => 1));
175 189
         $start = $jan1->dayOfWeek();
176
-        if ($start > HORDE_DATE_THURSDAY) {
190
+        if ($start > HORDE_DATE_THURSDAY)
191
+        {
177 192
             $start -= 7;
178 193
         }
179 194
         return (($week * 7) - (7 + $start)) + 1;
@@ -184,15 +199,23 @@  discard block
 block discarded – undo
184 199
      */
185 200
     function daysInMonth($month, $year)
186 201
     {
187
-        if ($month == 2) {
188
-            if (Horde_Date::isLeapYear($year)) {
202
+        if ($month == 2)
203
+        {
204
+            if (Horde_Date::isLeapYear($year))
205
+            {
189 206
                 return 29;
190
-            } else {
207
+            }
208
+            else
209
+            {
191 210
                 return 28;
192 211
             }
193
-        } elseif ($month == 4 || $month == 6 || $month == 9 || $month == 11) {
212
+        }
213
+        elseif ($month == 4 || $month == 6 || $month == 9 || $month == 11)
214
+        {
194 215
             return 30;
195
-        } else {
216
+        }
217
+        else
218
+        {
196 219
             return 31;
197 220
         }
198 221
     }
@@ -205,10 +228,13 @@  discard block
 block discarded – undo
205 228
      */
206 229
     function dayOfWeek()
207 230
     {
208
-        if ($this->month > 2) {
231
+        if ($this->month > 2)
232
+        {
209 233
             $month = $this->month - 2;
210 234
             $year = $this->year;
211
-        } else {
235
+        }
236
+        else
237
+        {
212 238
             $month = $this->month + 10;
213 239
             $year = $this->year - 1;
214 240
         }
@@ -231,7 +257,8 @@  discard block
 block discarded – undo
231 257
     {
232 258
         $monthTotals = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
233 259
         $dayOfYear = $this->mday + $monthTotals[$this->month - 1];
234
-        if (Horde_Date::isLeapYear($this->year) && $this->month > 2) {
260
+        if (Horde_Date::isLeapYear($this->year) && $this->month > 2)
261
+        {
235 262
             ++$dayOfYear;
236 263
         }
237 264
 
@@ -274,7 +301,8 @@  discard block
 block discarded – undo
274 301
         // Find the last Thursday of the year.
275 302
         $day = 31;
276 303
         $date = new Horde_Date(array('year' => $year, 'month' => 12, 'mday' => $day, 'hour' => 0, 'min' => 0, 'sec' => 0));
277
-        while ($date->dayOfWeek() != HORDE_DATE_THURSDAY) {
304
+        while ($date->dayOfWeek() != HORDE_DATE_THURSDAY)
305
+        {
278 306
             --$date->mday;
279 307
         }
280 308
         return $date->weekOfYear();
@@ -288,15 +316,19 @@  discard block
 block discarded – undo
288 316
      */
289 317
     function setNthWeekday($weekday, $nth = 1)
290 318
     {
291
-        if ($weekday < HORDE_DATE_SUNDAY || $weekday > HORDE_DATE_SATURDAY) {
319
+        if ($weekday < HORDE_DATE_SUNDAY || $weekday > HORDE_DATE_SATURDAY)
320
+        {
292 321
             return false;
293 322
         }
294 323
 
295 324
         $this->mday = 1;
296 325
         $first = $this->dayOfWeek();
297
-        if ($weekday < $first) {
326
+        if ($weekday < $first)
327
+        {
298 328
             $this->mday = 8 + $weekday - $first;
299
-        } else {
329
+        }
330
+        else
331
+        {
300 332
             $this->mday = $weekday - $first + 1;
301 333
         }
302 334
         $this->mday += 7 * $nth - 7;
@@ -318,7 +350,8 @@  discard block
 block discarded – undo
318 350
      */
319 351
     function isValid()
320 352
     {
321
-        if ($this->year < 0 || $this->year > 9999) {
353
+        if ($this->year < 0 || $this->year > 9999)
354
+        {
322 355
             return false;
323 356
         }
324 357
         return checkdate($this->month, $this->mday, $this->year);
@@ -331,57 +364,72 @@  discard block
 block discarded – undo
331 364
      */
332 365
     function correct($mask = HORDE_DATE_MASK_ALLPARTS)
333 366
     {
334
-        if ($mask & HORDE_DATE_MASK_SECOND) {
335
-            while ($this->sec < 0) {
367
+        if ($mask & HORDE_DATE_MASK_SECOND)
368
+        {
369
+            while ($this->sec < 0)
370
+            {
336 371
                 --$this->min;
337 372
                 $this->sec += 60;
338 373
             }
339
-            while ($this->sec > 59) {
374
+            while ($this->sec > 59)
375
+            {
340 376
                 ++$this->min;
341 377
                 $this->sec -= 60;
342 378
             }
343 379
         }
344 380
 
345
-        if ($mask & HORDE_DATE_MASK_MINUTE) {
346
-            while ($this->min < 0) {
381
+        if ($mask & HORDE_DATE_MASK_MINUTE)
382
+        {
383
+            while ($this->min < 0)
384
+            {
347 385
                 --$this->hour;
348 386
                 $this->min += 60;
349 387
             }
350
-            while ($this->min > 59) {
388
+            while ($this->min > 59)
389
+            {
351 390
                 ++$this->hour;
352 391
                 $this->min -= 60;
353 392
             }
354 393
         }
355 394
 
356
-        if ($mask & HORDE_DATE_MASK_HOUR) {
357
-            while ($this->hour < 0) {
395
+        if ($mask & HORDE_DATE_MASK_HOUR)
396
+        {
397
+            while ($this->hour < 0)
398
+            {
358 399
                 --$this->mday;
359 400
                 $this->hour += 24;
360 401
             }
361
-            while ($this->hour > 23) {
402
+            while ($this->hour > 23)
403
+            {
362 404
                 ++$this->mday;
363 405
                 $this->hour -= 24;
364 406
             }
365 407
         }
366 408
 
367
-        if ($mask & HORDE_DATE_MASK_MONTH) {
368
-            while ($this->month > 12) {
409
+        if ($mask & HORDE_DATE_MASK_MONTH)
410
+        {
411
+            while ($this->month > 12)
412
+            {
369 413
                 ++$this->year;
370 414
                 $this->month -= 12;
371 415
             }
372
-            while ($this->month < 1) {
416
+            while ($this->month < 1)
417
+            {
373 418
                 --$this->year;
374 419
                 $this->month += 12;
375 420
             }
376 421
         }
377 422
 
378
-        if ($mask & HORDE_DATE_MASK_DAY) {
379
-            while ($this->mday > Horde_Date::daysInMonth($this->month, $this->year)) {
423
+        if ($mask & HORDE_DATE_MASK_DAY)
424
+        {
425
+            while ($this->mday > Horde_Date::daysInMonth($this->month, $this->year))
426
+            {
380 427
                 $this->mday -= Horde_Date::daysInMonth($this->month, $this->year);
381 428
                 ++$this->month;
382 429
                 $this->correct(HORDE_DATE_MASK_MONTH);
383 430
             }
384
-            while ($this->mday < 1) {
431
+            while ($this->mday < 1)
432
+            {
385 433
                 --$this->month;
386 434
                 $this->correct(HORDE_DATE_MASK_MONTH);
387 435
                 $this->mday += Horde_Date::daysInMonth($this->month, $this->year);
@@ -402,14 +450,17 @@  discard block
 block discarded – undo
402 450
      */
403 451
     function compareDate($date)
404 452
     {
405
-        if (!is_a($date, 'Horde_Date')) {
453
+        if (!is_a($date, 'Horde_Date'))
454
+        {
406 455
             $date = new Horde_Date($date);
407 456
         }
408 457
 
409
-        if ($this->year != $date->year) {
458
+        if ($this->year != $date->year)
459
+        {
410 460
             return $this->year - $date->year;
411 461
         }
412
-        if ($this->month != $date->month) {
462
+        if ($this->month != $date->month)
463
+        {
413 464
             return $this->month - $date->month;
414 465
         }
415 466
 
@@ -429,14 +480,17 @@  discard block
 block discarded – undo
429 480
      */
430 481
     function compareTime($date)
431 482
     {
432
-        if (!is_a($date, 'Horde_Date')) {
483
+        if (!is_a($date, 'Horde_Date'))
484
+        {
433 485
             $date = new Horde_Date($date);
434 486
         }
435 487
 
436
-        if ($this->hour != $date->hour) {
488
+        if ($this->hour != $date->hour)
489
+        {
437 490
             return $this->hour - $date->hour;
438 491
         }
439
-        if ($this->min != $date->min) {
492
+        if ($this->min != $date->min)
493
+        {
440 494
             return $this->min - $date->min;
441 495
         }
442 496
 
@@ -456,11 +510,13 @@  discard block
 block discarded – undo
456 510
      */
457 511
     function compareDateTime($date)
458 512
     {
459
-        if (!is_a($date, 'Horde_Date')) {
513
+        if (!is_a($date, 'Horde_Date'))
514
+        {
460 515
             $date = new Horde_Date($date);
461 516
         }
462 517
 
463
-        if ($diff = $this->compareDate($date)) {
518
+        if ($diff = $this->compareDate($date))
519
+        {
464 520
             return $diff;
465 521
         }
466 522
 
@@ -478,10 +534,13 @@  discard block
 block discarded – undo
478 534
     {
479 535
         $secs = $this->format('Z');
480 536
 
481
-        if ($secs < 0) {
537
+        if ($secs < 0)
538
+        {
482 539
             $sign = '-';
483 540
             $secs = -$secs;
484
-        } else {
541
+        }
542
+        else
543
+        {
485 544
             $sign = '+';
486 545
         }
487 546
         $colon = $colon ? ':' : '';
@@ -497,9 +556,12 @@  discard block
 block discarded – undo
497 556
      */
498 557
     function timestamp()
499 558
     {
500
-        if (class_exists('DateTime')) {
559
+        if (class_exists('DateTime'))
560
+        {
501 561
             return $this->format('U');
502
-        } else {
562
+        }
563
+        else
564
+        {
503 565
             return Horde_Date::_mktime($this->hour, $this->min, $this->sec, $this->month, $this->mday, $this->year);
504 566
         }
505 567
     }
@@ -511,12 +573,15 @@  discard block
 block discarded – undo
511 573
      */
512 574
     function datestamp()
513 575
     {
514
-        if (class_exists('DateTime')) {
576
+        if (class_exists('DateTime'))
577
+        {
515 578
             $dt = new DateTime();
516 579
             $dt->setDate($this->year, $this->month, $this->mday);
517 580
             $dt->setTime(0, 0, 0);
518 581
             return $dt->format('U');
519
-        } else {
582
+        }
583
+        else
584
+        {
520 585
             return Horde_Date::_mktime(0, 0, 0, $this->month, $this->mday, $this->year);
521 586
         }
522 587
     }
@@ -533,12 +598,15 @@  discard block
 block discarded – undo
533 598
      */
534 599
     function format($format)
535 600
     {
536
-        if (class_exists('DateTime')) {
601
+        if (class_exists('DateTime'))
602
+        {
537 603
             $dt = new DateTime();
538 604
             $dt->setDate($this->year, $this->month, $this->mday);
539 605
             $dt->setTime($this->hour, $this->min, $this->sec);
540 606
             return $dt->format($format);
541
-        } else {
607
+        }
608
+        else
609
+        {
542 610
             return date($format, $this->timestamp());
543 611
         }
544 612
     }
@@ -595,9 +663,12 @@  discard block
 block discarded – undo
595 663
      */
596 664
     function strftime($format)
597 665
     {
598
-        if (preg_match('/%[^' . $this->_supportedSpecs . ']/', $format)) {
666
+        if (preg_match('/%[^' . $this->_supportedSpecs . ']/', $format))
667
+        {
599 668
             return strftime($format, $this->timestamp());
600
-        } else {
669
+        }
670
+        else
671
+        {
601 672
             return $this->_strftime($format);
602 673
         }
603 674
     }
@@ -609,7 +680,8 @@  discard block
 block discarded – undo
609 680
      */
610 681
     function _strftime($format)
611 682
     {
612
-        if (preg_match('/%[bBpxX]/', $format)) {
683
+        if (preg_match('/%[bBpxX]/', $format))
684
+        {
613 685
             require_once 'Horde/NLS.php';
614 686
         }
615 687
 
@@ -672,14 +744,16 @@  discard block
 block discarded – undo
672 744
     function _mktime($hr, $min, $sec, $mon = false, $day = false,
673 745
                      $year = false, $is_dst = false, $is_gmt = false)
674 746
     {
675
-        if ($mon === false) {
747
+        if ($mon === false)
748
+        {
676 749
             return $is_gmt
677 750
                 ? @gmmktime($hr, $min, $sec)
678 751
                 : @mktime($hr, $min, $sec);
679 752
         }
680 753
 
681 754
         if ($year > 1901 && $year < 2038 &&
682
-            ($year >= 1970 || version_compare(PHP_VERSION, '5.0.0', '>='))) {
755
+            ($year >= 1970 || version_compare(PHP_VERSION, '5.0.0', '>=')))
756
+        {
683 757
             return $is_gmt
684 758
                 ? @gmmktime($hr, $min, $sec, $mon, $day, $year)
685 759
                 : @mktime($hr, $min, $sec, $mon, $day, $year);
@@ -693,11 +767,14 @@  discard block
 block discarded – undo
693 767
         $day = intval($day);
694 768
         $year = intval($year);
695 769
 
696
-        if ($mon > 12) {
770
+        if ($mon > 12)
771
+        {
697 772
             $y = floor($mon / 12);
698 773
             $year += $y;
699 774
             $mon -= $y * 12;
700
-        } elseif ($mon < 1) {
775
+        }
776
+        elseif ($mon < 1)
777
+        {
701 778
             $y = ceil((1 - $mon) / 12);
702 779
             $year -= $y;
703 780
             $mon += $y * 12;
@@ -711,20 +788,29 @@  discard block
 block discarded – undo
711 788
         $_month_table_leaf = array('', 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
712 789
 
713 790
         $_total_date = 0;
714
-        if ($year >= 1970) {
715
-            for ($a = 1970; $a <= $year; $a++) {
791
+        if ($year >= 1970)
792
+        {
793
+            for ($a = 1970; $a <= $year; $a++)
794
+            {
716 795
                 $leaf = Horde_Date::isLeapYear($a);
717
-                if ($leaf == true) {
796
+                if ($leaf == true)
797
+                {
718 798
                     $loop_table = $_month_table_leaf;
719 799
                     $_add_date = 366;
720
-                } else {
800
+                }
801
+                else
802
+                {
721 803
                     $loop_table = $_month_table_normal;
722 804
                     $_add_date = 365;
723 805
                 }
724
-                if ($a < $year) {
806
+                if ($a < $year)
807
+                {
725 808
                     $_total_date += $_add_date;
726
-                } else {
727
-                    for ($b = 1; $b < $mon; $b++) {
809
+                }
810
+                else
811
+                {
812
+                    for ($b = 1; $b < $mon; $b++)
813
+                    {
728 814
                         $_total_date += $loop_table[$b];
729 815
                     }
730 816
                 }
@@ -733,19 +819,27 @@  discard block
 block discarded – undo
733 819
             return ($_total_date + $day - 1) * $_day_power + $hr * $_hour_power + $min * $_min_power + $sec + $gmt_different;
734 820
         }
735 821
 
736
-        for ($a = 1969 ; $a >= $year; $a--) {
822
+        for ($a = 1969 ; $a >= $year; $a--)
823
+        {
737 824
             $leaf = Horde_Date::isLeapYear($a);
738
-            if ($leaf == true) {
825
+            if ($leaf == true)
826
+            {
739 827
                 $loop_table = $_month_table_leaf;
740 828
                 $_add_date = 366;
741
-            } else {
829
+            }
830
+            else
831
+            {
742 832
                 $loop_table = $_month_table_normal;
743 833
                 $_add_date = 365;
744 834
             }
745
-            if ($a > $year) {
835
+            if ($a > $year)
836
+            {
746 837
                 $_total_date += $_add_date;
747
-            } else {
748
-                for ($b = 12; $b > $mon; $b--) {
838
+            }
839
+            else
840
+            {
841
+                for ($b = 12; $b > $mon; $b--)
842
+                {
749 843
                     $_total_date += $loop_table[$b];
750 844
                 }
751 845
             }
@@ -755,13 +849,18 @@  discard block
 block discarded – undo
755 849
         $_day_time = $hr * $_hour_power + $min * $_min_power + $sec;
756 850
         $_day_time = $_day_power - $_day_time;
757 851
         $ret = -($_total_date * $_day_power + $_day_time - $gmt_different);
758
-        if ($ret < -12220185600) {
852
+        if ($ret < -12220185600)
853
+        {
759 854
             // If earlier than 5 Oct 1582 - gregorian correction.
760 855
             return $ret + 10 * 86400;
761
-        } elseif ($ret < -12219321600) {
856
+        }
857
+        elseif ($ret < -12219321600)
858
+        {
762 859
             // If in limbo, reset to 15 Oct 1582.
763 860
             return -12219321600;
764
-        } else {
861
+        }
862
+        else
863
+        {
765 864
             return $ret;
766 865
         }
767 866
     }
Please login to merge, or discard this patch.
phpgwapi/inc/horde/Horde/iCalendar.php 5 patches
Doc Comments   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
      * if the attribute does not exist.
243 243
      *
244 244
      * @param string $name    The name of the attribute.
245
-     * @param mixed $default  What to return if the attribute specified by
245
+     * @param string $default  What to return if the attribute specified by
246 246
      *                        $name does not exist.
247 247
      *
248 248
      * @return mixed (string) The value of $name.
@@ -371,7 +371,6 @@  discard block
 block discarded – undo
371 371
      * Locates the first child component of the specified class, and returns a
372 372
      * reference to it.
373 373
      *
374
-     * @param string $type  The type of component to find.
375 374
      *
376 375
      * @return boolean|Horde_iCalendar_*  False if no subcomponent of the
377 376
      *                                    specified class exists or a reference
@@ -1316,6 +1315,7 @@  discard block
 block discarded – undo
1316 1315
 
1317 1316
     /**
1318 1317
      * Parse a Time Period field.
1318
+     * @param string $text
1319 1319
      */
1320 1320
     function _parsePeriod($text)
1321 1321
     {
@@ -1348,6 +1348,7 @@  discard block
 block discarded – undo
1348 1348
     /**
1349 1349
      * Grok the TZID and return an offset in seconds from UTC for this
1350 1350
      * date and time.
1351
+     * @param boolean $tzid
1351 1352
      */
1352 1353
     function _parseTZID($date, $time, $tzid)
1353 1354
     {
Please login to merge, or discard this patch.
Indentation   +1633 added lines, -1633 removed lines patch added patch discarded remove patch
@@ -22,1687 +22,1687 @@
 block discarded – undo
22 22
  */
23 23
 class Horde_iCalendar {
24 24
 
25
-    /**
26
-     * The parent (containing) iCalendar object.
27
-     *
28
-     * @var Horde_iCalendar
29
-     */
30
-    var $_container = false;
31
-
32
-    /**
33
-     * The name/value pairs of attributes for this object (UID,
34
-     * DTSTART, etc.). Which are present depends on the object and on
35
-     * what kind of component it is.
36
-     *
37
-     * @var array
38
-     */
39
-    var $_attributes = array();
40
-
41
-    /**
42
-     * Any children (contained) iCalendar components of this object.
43
-     *
44
-     * @var array
45
-     */
46
-    var $_components = array();
47
-
48
-    /**
49
-     * According to RFC 2425, we should always use CRLF-terminated lines.
50
-     *
51
-     * @var string
52
-     */
53
-    var $_newline = "\r\n";
54
-
55
-    /**
56
-     * iCalendar format version (different behavior for 1.0 and 2.0
57
-     * especially with recurring events).
58
-     *
59
-     * @var string
60
-     */
61
-    var $_version;
62
-
63
-    function Horde_iCalendar($version = '2.0')
64
-    {
65
-        $this->_version = $version;
66
-        $this->setAttribute('VERSION', $version);
67
-    }
68
-
69
-    /**
70
-     * Return a reference to a new component.
71
-     *
72
-     * @param string          $type       The type of component to return
73
-     * @param Horde_iCalendar $container  A container that this component
74
-     *                                    will be associated with.
75
-     *
76
-     * @return object  Reference to a Horde_iCalendar_* object as specified.
77
-     *
78
-     * @static
79
-     */
80
-    function &newComponent($type, &$container)
81
-    {
82
-        $type = String::lower($type);
83
-        $class = 'Horde_iCalendar_' . $type;
84
-        if (!class_exists($class)) {
25
+	/**
26
+	 * The parent (containing) iCalendar object.
27
+	 *
28
+	 * @var Horde_iCalendar
29
+	 */
30
+	var $_container = false;
31
+
32
+	/**
33
+	 * The name/value pairs of attributes for this object (UID,
34
+	 * DTSTART, etc.). Which are present depends on the object and on
35
+	 * what kind of component it is.
36
+	 *
37
+	 * @var array
38
+	 */
39
+	var $_attributes = array();
40
+
41
+	/**
42
+	 * Any children (contained) iCalendar components of this object.
43
+	 *
44
+	 * @var array
45
+	 */
46
+	var $_components = array();
47
+
48
+	/**
49
+	 * According to RFC 2425, we should always use CRLF-terminated lines.
50
+	 *
51
+	 * @var string
52
+	 */
53
+	var $_newline = "\r\n";
54
+
55
+	/**
56
+	 * iCalendar format version (different behavior for 1.0 and 2.0
57
+	 * especially with recurring events).
58
+	 *
59
+	 * @var string
60
+	 */
61
+	var $_version;
62
+
63
+	function Horde_iCalendar($version = '2.0')
64
+	{
65
+		$this->_version = $version;
66
+		$this->setAttribute('VERSION', $version);
67
+	}
68
+
69
+	/**
70
+	 * Return a reference to a new component.
71
+	 *
72
+	 * @param string          $type       The type of component to return
73
+	 * @param Horde_iCalendar $container  A container that this component
74
+	 *                                    will be associated with.
75
+	 *
76
+	 * @return object  Reference to a Horde_iCalendar_* object as specified.
77
+	 *
78
+	 * @static
79
+	 */
80
+	function &newComponent($type, &$container)
81
+	{
82
+		$type = String::lower($type);
83
+		$class = 'Horde_iCalendar_' . $type;
84
+		if (!class_exists($class)) {
85 85
 			// include relative from current dir, as we no longer set (old) Horde dir in include path
86
-            include 'iCalendar/' . $type . '.php';
87
-        }
88
-        if (class_exists($class)) {
89
-            $component = new $class();
90
-            if ($container !== false) {
91
-                $component->_container = &$container;
92
-                // Use version of container, not default set by component
93
-                // constructor.
94
-                $component->_version = $container->_version;
95
-            }
96
-        } else {
97
-            // Should return an dummy x-unknown type class here.
98
-            $component = false;
99
-        }
100
-
101
-        return $component;
102
-    }
103
-
104
-    /**
105
-     * Sets the value of an attribute.
106
-     *
107
-     * @param string $name     The name of the attribute.
108
-     * @param string $value    The value of the attribute.
109
-     * @param array $params    Array containing any addition parameters for
110
-     *                         this attribute.
111
-     * @param boolean $append  True to append the attribute, False to replace
112
-     *                         the first matching attribute found.
113
-     * @param array $values    Array representation of $value.  For
114
-     *                         comma/semicolon seperated lists of values.  If
115
-     *                         not set use $value as single array element.
116
-     */
117
-    function setAttribute($name, $value, $params = array(), $append = true,
118
-                          $values = false)
119
-    {
120
-        // Make sure we update the internal format version if
121
-        // setAttribute('VERSION', ...) is called.
122
-        if ($name == 'VERSION') {
123
-            $this->_version = $value;
124
-            if ($this->_container !== false) {
125
-                $this->_container->_version = $value;
126
-            }
127
-        }
128
-
129
-        if (!$values) {
130
-            $values = array($value);
131
-        }
132
-        $found = false;
133
-        if (!$append) {
134
-            foreach (array_keys($this->_attributes) as $key) {
135
-                if ($this->_attributes[$key]['name'] == String::upper($name)) {
136
-                    $this->_attributes[$key]['params'] = $params;
137
-                    $this->_attributes[$key]['value'] = $value;
138
-                    $this->_attributes[$key]['values'] = $values;
139
-                    $found = true;
140
-                    break;
141
-                }
142
-            }
143
-        }
144
-
145
-        if ($append || !$found) {
146
-            $this->_attributes[] = array(
147
-                'name'      => String::upper($name),
148
-                'params'    => $params,
149
-                'value'     => $value,
150
-                'values'    => $values
151
-            );
152
-        }
153
-    }
154
-
155
-    /**
156
-     * Sets parameter(s) for an (already existing) attribute.  The
157
-     * parameter set is merged into the existing set.
158
-     *
159
-     * @param string $name   The name of the attribute.
160
-     * @param array $params  Array containing any additional parameters for
161
-     *                       this attribute.
162
-     * @return boolean  True on success, false if no attribute $name exists.
163
-     */
164
-    function setParameter($name, $params = array())
165
-    {
166
-        $keys = array_keys($this->_attributes);
167
-        foreach ($keys as $key) {
168
-            if ($this->_attributes[$key]['name'] == $name) {
169
-                $this->_attributes[$key]['params'] =
170
-                    array_merge($this->_attributes[$key]['params'], $params);
171
-                return true;
172
-            }
173
-        }
174
-
175
-        return false;
176
-    }
177
-
178
-    /**
179
-     * Get the value of an attribute.
180
-     *
181
-     * @param string $name     The name of the attribute.
182
-     * @param boolean $params  Return the parameters for this attribute instead
183
-     *                         of its value.
184
-     *
185
-     * @return mixed (object)  PEAR_Error if the attribute does not exist.
186
-     *               (string)  The value of the attribute.
187
-     *               (array)   The parameters for the attribute or
188
-     *                         multiple values for an attribute.
189
-     */
190
-    function getAttribute($name, $params = false)
191
-    {
192
-        $result = array();
193
-        foreach ($this->_attributes as $attribute) {
194
-            if ($attribute['name'] == $name) {
195
-                if ($params) {
196
-                    $result[] = $attribute['params'];
197
-                } else {
198
-                    $result[] = $attribute['value'];
199
-                }
200
-            }
201
-        }
202
-        if (!count($result)) {
203
-            require_once 'PEAR.php';
204
-            return PEAR::raiseError('Attribute "' . $name . '" Not Found');
205
-        } if (count($result) == 1 && !$params) {
206
-            return $result[0];
207
-        } else {
208
-            return $result;
209
-        }
210
-    }
211
-
212
-    /**
213
-     * Gets the values of an attribute as an array.  Multiple values
214
-     * are possible due to:
215
-     *
216
-     *  a) multiplce occurences of 'name'
217
-     *  b) (unsecapd) comma seperated lists.
218
-     *
219
-     * So for a vcard like "KEY:a,b\nKEY:c" getAttributesValues('KEY')
220
-     * will return array('a', 'b', 'c').
221
-     *
222
-     * @param string  $name    The name of the attribute.
223
-     * @return mixed (object)  PEAR_Error if the attribute does not exist.
224
-     *               (array)   Multiple values for an attribute.
225
-     */
226
-    function getAttributeValues($name)
227
-    {
228
-        $result = array();
229
-        foreach ($this->_attributes as $attribute) {
230
-            if ($attribute['name'] == $name) {
231
-                $result = array_merge($attribute['values'], $result);
232
-            }
233
-        }
234
-        if (!count($result)) {
235
-            return PEAR::raiseError('Attribute "' . $name . '" Not Found');
236
-        }
237
-        return $result;
238
-    }
239
-
240
-    /**
241
-     * Returns the value of an attribute, or a specified default value
242
-     * if the attribute does not exist.
243
-     *
244
-     * @param string $name    The name of the attribute.
245
-     * @param mixed $default  What to return if the attribute specified by
246
-     *                        $name does not exist.
247
-     *
248
-     * @return mixed (string) The value of $name.
249
-     *               (mixed)  $default if $name does not exist.
250
-     */
251
-    function getAttributeDefault($name, $default = '')
252
-    {
253
-        $value = $this->getAttribute($name);
254
-        return is_a($value, 'PEAR_Error') ? $default : $value;
255
-    }
256
-
257
-    /**
258
-     * Remove all occurences of an attribute.
259
-     *
260
-     * @param string $name  The name of the attribute.
261
-     */
262
-    function removeAttribute($name)
263
-    {
264
-        $keys = array_keys($this->_attributes);
265
-        foreach ($keys as $key) {
266
-            if ($this->_attributes[$key]['name'] == $name) {
267
-                unset($this->_attributes[$key]);
268
-            }
269
-        }
270
-    }
271
-
272
-    /**
273
-     * Get attributes for all tags or for a given tag.
274
-     *
275
-     * @param string $tag  Return attributes for this tag, or all attributes if
276
-     *                     not given.
277
-     *
278
-     * @return array  An array containing all the attributes and their types.
279
-     */
280
-    function getAllAttributes($tag = false)
281
-    {
282
-        if ($tag === false) {
283
-            return $this->_attributes;
284
-        }
285
-        $result = array();
286
-        foreach ($this->_attributes as $attribute) {
287
-            if ($attribute['name'] == $tag) {
288
-                $result[] = $attribute;
289
-            }
290
-        }
291
-        return $result;
292
-    }
293
-
294
-    /**
295
-     * Add a vCalendar component (eg vEvent, vTimezone, etc.).
296
-     *
297
-     * @param Horde_iCalendar $component  Component (subclass) to add.
298
-     */
299
-    function addComponent($component)
300
-    {
301
-        if (is_a($component, 'Horde_iCalendar')) {
302
-            $component->_container = &$this;
303
-            $this->_components[] = &$component;
304
-        }
305
-    }
306
-
307
-    /**
308
-     * Retrieve all the components.
309
-     *
310
-     * @return array  Array of Horde_iCalendar objects.
311
-     */
312
-    function getComponents()
313
-    {
314
-        return $this->_components;
315
-    }
316
-
317
-    function getType()
318
-    {
319
-        return 'vcalendar';
320
-    }
321
-
322
-    /**
323
-     * Return the classes (entry types) we have.
324
-     *
325
-     * @return array  Hash with class names Horde_iCalendar_xxx as keys
326
-     *                and number of components of this class as value.
327
-     */
328
-    function getComponentClasses()
329
-    {
330
-        $r = array();
331
-        foreach ($this->_components as $c) {
332
-            $cn = strtolower(get_class($c));
333
-            if (empty($r[$cn])) {
334
-                $r[$cn] = 1;
335
-            } else {
336
-                $r[$cn]++;
337
-            }
338
-        }
339
-
340
-        return $r;
341
-    }
342
-
343
-    /**
344
-     * Number of components in this container.
345
-     *
346
-     * @return integer  Number of components in this container.
347
-     */
348
-    function getComponentCount()
349
-    {
350
-        return count($this->_components);
351
-    }
352
-
353
-    /**
354
-     * Retrieve a specific component.
355
-     *
356
-     * @param integer $idx  The index of the object to retrieve.
357
-     *
358
-     * @return mixed    (boolean) False if the index does not exist.
359
-     *                  (Horde_iCalendar_*) The requested component.
360
-     */
361
-    function getComponent($idx)
362
-    {
363
-        if (isset($this->_components[$idx])) {
364
-            return $this->_components[$idx];
365
-        } else {
366
-            return false;
367
-        }
368
-    }
369
-
370
-    /**
371
-     * Locates the first child component of the specified class, and returns a
372
-     * reference to it.
373
-     *
374
-     * @param string $type  The type of component to find.
375
-     *
376
-     * @return boolean|Horde_iCalendar_*  False if no subcomponent of the
377
-     *                                    specified class exists or a reference
378
-     *                                    to the requested component.
379
-     */
380
-    function &findComponent($childclass)
381
-    {
382
-        $childclass = 'Horde_iCalendar_' . String::lower($childclass);
383
-        $keys = array_keys($this->_components);
384
-        foreach ($keys as $key) {
385
-            if (is_a($this->_components[$key], $childclass)) {
386
-                return $this->_components[$key];
387
-            }
388
-        }
389
-
390
-        $component = false;
391
-        return $component;
392
-    }
393
-
394
-    /**
395
-     * Locates the first matching child component of the specified class, and
396
-     * returns a reference to it.
397
-     *
398
-     * @param string $childclass  The type of component to find.
399
-     * @param string $attribute   This attribute must be set in the component
400
-     *                            for it to match.
401
-     * @param string $value       Optional value that $attribute must match.
402
-     *
403
-     * @return boolean|Horde_iCalendar_*  False if no matching subcomponent of
404
-     *                                    the specified class exists, or a
405
-     *                                    reference to the requested component.
406
-     */
407
-    function &findComponentByAttribute($childclass, $attribute, $value = null)
408
-    {
409
-        $childclass = 'Horde_iCalendar_' . String::lower($childclass);
410
-        $keys = array_keys($this->_components);
411
-        foreach ($keys as $key) {
412
-            if (is_a($this->_components[$key], $childclass)) {
413
-                $attr = $this->_components[$key]->getAttribute($attribute);
414
-                if (is_a($attr, 'PEAR_Error')) {
415
-                    continue;
416
-                }
417
-                if ($value !== null && $value != $attr) {
418
-                    continue;
419
-                }
420
-                return $this->_components[$key];
421
-            }
422
-        }
423
-
424
-        $component = false;
425
-        return $component;
426
-    }
427
-
428
-    /**
429
-     * Clears the iCalendar object (resets the components and attributes
430
-     * arrays).
431
-     */
432
-    function clear()
433
-    {
434
-        $this->_components = array();
435
-        $this->_attributes = array();
436
-    }
437
-
438
-    /**
439
-     * Checks if entry is vcalendar 1.0, vcard 2.1 or vnote 1.1.
440
-     *
441
-     * These 'old' formats are defined by www.imc.org. The 'new' (non-old)
442
-     * formats icalendar 2.0 and vcard 3.0 are defined in rfc2426 and rfc2445
443
-     * respectively.
444
-     *
445
-     * @since Horde 3.1.2
446
-     */
447
-    function isOldFormat()
448
-    {
86
+			include 'iCalendar/' . $type . '.php';
87
+		}
88
+		if (class_exists($class)) {
89
+			$component = new $class();
90
+			if ($container !== false) {
91
+				$component->_container = &$container;
92
+				// Use version of container, not default set by component
93
+				// constructor.
94
+				$component->_version = $container->_version;
95
+			}
96
+		} else {
97
+			// Should return an dummy x-unknown type class here.
98
+			$component = false;
99
+		}
100
+
101
+		return $component;
102
+	}
103
+
104
+	/**
105
+	 * Sets the value of an attribute.
106
+	 *
107
+	 * @param string $name     The name of the attribute.
108
+	 * @param string $value    The value of the attribute.
109
+	 * @param array $params    Array containing any addition parameters for
110
+	 *                         this attribute.
111
+	 * @param boolean $append  True to append the attribute, False to replace
112
+	 *                         the first matching attribute found.
113
+	 * @param array $values    Array representation of $value.  For
114
+	 *                         comma/semicolon seperated lists of values.  If
115
+	 *                         not set use $value as single array element.
116
+	 */
117
+	function setAttribute($name, $value, $params = array(), $append = true,
118
+						  $values = false)
119
+	{
120
+		// Make sure we update the internal format version if
121
+		// setAttribute('VERSION', ...) is called.
122
+		if ($name == 'VERSION') {
123
+			$this->_version = $value;
124
+			if ($this->_container !== false) {
125
+				$this->_container->_version = $value;
126
+			}
127
+		}
128
+
129
+		if (!$values) {
130
+			$values = array($value);
131
+		}
132
+		$found = false;
133
+		if (!$append) {
134
+			foreach (array_keys($this->_attributes) as $key) {
135
+				if ($this->_attributes[$key]['name'] == String::upper($name)) {
136
+					$this->_attributes[$key]['params'] = $params;
137
+					$this->_attributes[$key]['value'] = $value;
138
+					$this->_attributes[$key]['values'] = $values;
139
+					$found = true;
140
+					break;
141
+				}
142
+			}
143
+		}
144
+
145
+		if ($append || !$found) {
146
+			$this->_attributes[] = array(
147
+				'name'      => String::upper($name),
148
+				'params'    => $params,
149
+				'value'     => $value,
150
+				'values'    => $values
151
+			);
152
+		}
153
+	}
154
+
155
+	/**
156
+	 * Sets parameter(s) for an (already existing) attribute.  The
157
+	 * parameter set is merged into the existing set.
158
+	 *
159
+	 * @param string $name   The name of the attribute.
160
+	 * @param array $params  Array containing any additional parameters for
161
+	 *                       this attribute.
162
+	 * @return boolean  True on success, false if no attribute $name exists.
163
+	 */
164
+	function setParameter($name, $params = array())
165
+	{
166
+		$keys = array_keys($this->_attributes);
167
+		foreach ($keys as $key) {
168
+			if ($this->_attributes[$key]['name'] == $name) {
169
+				$this->_attributes[$key]['params'] =
170
+					array_merge($this->_attributes[$key]['params'], $params);
171
+				return true;
172
+			}
173
+		}
174
+
175
+		return false;
176
+	}
177
+
178
+	/**
179
+	 * Get the value of an attribute.
180
+	 *
181
+	 * @param string $name     The name of the attribute.
182
+	 * @param boolean $params  Return the parameters for this attribute instead
183
+	 *                         of its value.
184
+	 *
185
+	 * @return mixed (object)  PEAR_Error if the attribute does not exist.
186
+	 *               (string)  The value of the attribute.
187
+	 *               (array)   The parameters for the attribute or
188
+	 *                         multiple values for an attribute.
189
+	 */
190
+	function getAttribute($name, $params = false)
191
+	{
192
+		$result = array();
193
+		foreach ($this->_attributes as $attribute) {
194
+			if ($attribute['name'] == $name) {
195
+				if ($params) {
196
+					$result[] = $attribute['params'];
197
+				} else {
198
+					$result[] = $attribute['value'];
199
+				}
200
+			}
201
+		}
202
+		if (!count($result)) {
203
+			require_once 'PEAR.php';
204
+			return PEAR::raiseError('Attribute "' . $name . '" Not Found');
205
+		} if (count($result) == 1 && !$params) {
206
+			return $result[0];
207
+		} else {
208
+			return $result;
209
+		}
210
+	}
211
+
212
+	/**
213
+	 * Gets the values of an attribute as an array.  Multiple values
214
+	 * are possible due to:
215
+	 *
216
+	 *  a) multiplce occurences of 'name'
217
+	 *  b) (unsecapd) comma seperated lists.
218
+	 *
219
+	 * So for a vcard like "KEY:a,b\nKEY:c" getAttributesValues('KEY')
220
+	 * will return array('a', 'b', 'c').
221
+	 *
222
+	 * @param string  $name    The name of the attribute.
223
+	 * @return mixed (object)  PEAR_Error if the attribute does not exist.
224
+	 *               (array)   Multiple values for an attribute.
225
+	 */
226
+	function getAttributeValues($name)
227
+	{
228
+		$result = array();
229
+		foreach ($this->_attributes as $attribute) {
230
+			if ($attribute['name'] == $name) {
231
+				$result = array_merge($attribute['values'], $result);
232
+			}
233
+		}
234
+		if (!count($result)) {
235
+			return PEAR::raiseError('Attribute "' . $name . '" Not Found');
236
+		}
237
+		return $result;
238
+	}
239
+
240
+	/**
241
+	 * Returns the value of an attribute, or a specified default value
242
+	 * if the attribute does not exist.
243
+	 *
244
+	 * @param string $name    The name of the attribute.
245
+	 * @param mixed $default  What to return if the attribute specified by
246
+	 *                        $name does not exist.
247
+	 *
248
+	 * @return mixed (string) The value of $name.
249
+	 *               (mixed)  $default if $name does not exist.
250
+	 */
251
+	function getAttributeDefault($name, $default = '')
252
+	{
253
+		$value = $this->getAttribute($name);
254
+		return is_a($value, 'PEAR_Error') ? $default : $value;
255
+	}
256
+
257
+	/**
258
+	 * Remove all occurences of an attribute.
259
+	 *
260
+	 * @param string $name  The name of the attribute.
261
+	 */
262
+	function removeAttribute($name)
263
+	{
264
+		$keys = array_keys($this->_attributes);
265
+		foreach ($keys as $key) {
266
+			if ($this->_attributes[$key]['name'] == $name) {
267
+				unset($this->_attributes[$key]);
268
+			}
269
+		}
270
+	}
271
+
272
+	/**
273
+	 * Get attributes for all tags or for a given tag.
274
+	 *
275
+	 * @param string $tag  Return attributes for this tag, or all attributes if
276
+	 *                     not given.
277
+	 *
278
+	 * @return array  An array containing all the attributes and their types.
279
+	 */
280
+	function getAllAttributes($tag = false)
281
+	{
282
+		if ($tag === false) {
283
+			return $this->_attributes;
284
+		}
285
+		$result = array();
286
+		foreach ($this->_attributes as $attribute) {
287
+			if ($attribute['name'] == $tag) {
288
+				$result[] = $attribute;
289
+			}
290
+		}
291
+		return $result;
292
+	}
293
+
294
+	/**
295
+	 * Add a vCalendar component (eg vEvent, vTimezone, etc.).
296
+	 *
297
+	 * @param Horde_iCalendar $component  Component (subclass) to add.
298
+	 */
299
+	function addComponent($component)
300
+	{
301
+		if (is_a($component, 'Horde_iCalendar')) {
302
+			$component->_container = &$this;
303
+			$this->_components[] = &$component;
304
+		}
305
+	}
306
+
307
+	/**
308
+	 * Retrieve all the components.
309
+	 *
310
+	 * @return array  Array of Horde_iCalendar objects.
311
+	 */
312
+	function getComponents()
313
+	{
314
+		return $this->_components;
315
+	}
316
+
317
+	function getType()
318
+	{
319
+		return 'vcalendar';
320
+	}
321
+
322
+	/**
323
+	 * Return the classes (entry types) we have.
324
+	 *
325
+	 * @return array  Hash with class names Horde_iCalendar_xxx as keys
326
+	 *                and number of components of this class as value.
327
+	 */
328
+	function getComponentClasses()
329
+	{
330
+		$r = array();
331
+		foreach ($this->_components as $c) {
332
+			$cn = strtolower(get_class($c));
333
+			if (empty($r[$cn])) {
334
+				$r[$cn] = 1;
335
+			} else {
336
+				$r[$cn]++;
337
+			}
338
+		}
339
+
340
+		return $r;
341
+	}
342
+
343
+	/**
344
+	 * Number of components in this container.
345
+	 *
346
+	 * @return integer  Number of components in this container.
347
+	 */
348
+	function getComponentCount()
349
+	{
350
+		return count($this->_components);
351
+	}
352
+
353
+	/**
354
+	 * Retrieve a specific component.
355
+	 *
356
+	 * @param integer $idx  The index of the object to retrieve.
357
+	 *
358
+	 * @return mixed    (boolean) False if the index does not exist.
359
+	 *                  (Horde_iCalendar_*) The requested component.
360
+	 */
361
+	function getComponent($idx)
362
+	{
363
+		if (isset($this->_components[$idx])) {
364
+			return $this->_components[$idx];
365
+		} else {
366
+			return false;
367
+		}
368
+	}
369
+
370
+	/**
371
+	 * Locates the first child component of the specified class, and returns a
372
+	 * reference to it.
373
+	 *
374
+	 * @param string $type  The type of component to find.
375
+	 *
376
+	 * @return boolean|Horde_iCalendar_*  False if no subcomponent of the
377
+	 *                                    specified class exists or a reference
378
+	 *                                    to the requested component.
379
+	 */
380
+	function &findComponent($childclass)
381
+	{
382
+		$childclass = 'Horde_iCalendar_' . String::lower($childclass);
383
+		$keys = array_keys($this->_components);
384
+		foreach ($keys as $key) {
385
+			if (is_a($this->_components[$key], $childclass)) {
386
+				return $this->_components[$key];
387
+			}
388
+		}
389
+
390
+		$component = false;
391
+		return $component;
392
+	}
393
+
394
+	/**
395
+	 * Locates the first matching child component of the specified class, and
396
+	 * returns a reference to it.
397
+	 *
398
+	 * @param string $childclass  The type of component to find.
399
+	 * @param string $attribute   This attribute must be set in the component
400
+	 *                            for it to match.
401
+	 * @param string $value       Optional value that $attribute must match.
402
+	 *
403
+	 * @return boolean|Horde_iCalendar_*  False if no matching subcomponent of
404
+	 *                                    the specified class exists, or a
405
+	 *                                    reference to the requested component.
406
+	 */
407
+	function &findComponentByAttribute($childclass, $attribute, $value = null)
408
+	{
409
+		$childclass = 'Horde_iCalendar_' . String::lower($childclass);
410
+		$keys = array_keys($this->_components);
411
+		foreach ($keys as $key) {
412
+			if (is_a($this->_components[$key], $childclass)) {
413
+				$attr = $this->_components[$key]->getAttribute($attribute);
414
+				if (is_a($attr, 'PEAR_Error')) {
415
+					continue;
416
+				}
417
+				if ($value !== null && $value != $attr) {
418
+					continue;
419
+				}
420
+				return $this->_components[$key];
421
+			}
422
+		}
423
+
424
+		$component = false;
425
+		return $component;
426
+	}
427
+
428
+	/**
429
+	 * Clears the iCalendar object (resets the components and attributes
430
+	 * arrays).
431
+	 */
432
+	function clear()
433
+	{
434
+		$this->_components = array();
435
+		$this->_attributes = array();
436
+	}
437
+
438
+	/**
439
+	 * Checks if entry is vcalendar 1.0, vcard 2.1 or vnote 1.1.
440
+	 *
441
+	 * These 'old' formats are defined by www.imc.org. The 'new' (non-old)
442
+	 * formats icalendar 2.0 and vcard 3.0 are defined in rfc2426 and rfc2445
443
+	 * respectively.
444
+	 *
445
+	 * @since Horde 3.1.2
446
+	 */
447
+	function isOldFormat()
448
+	{
449 449
 	$retval = true;
450 450
 	switch ($this->getType()) {
451 451
 		case 'vcard':
452
-            		$retval = ($this->_version < 3);
452
+					$retval = ($this->_version < 3);
453 453
 			break;
454 454
 		case 'vNote':
455
-            		$retval = ($this->_version < 2);
455
+					$retval = ($this->_version < 2);
456 456
 			break;
457 457
 		default:
458 458
 			$retval = ($this->_version < 2);
459 459
 			break;
460 460
 	}
461
-        return $retval;
462
-    }
463
-
464
-    /**
465
-     * Export as vCalendar format.
466
-     *
467
-     * @param string $charset  The encoding charset for $text. Defaults to
468
-     *                         utf-8 for new format, standard character set for old format.
469
-     */
470
-    function exportvCalendar($charset = null)
471
-    {
472
-        // Default values.
473
-        $requiredAttributes['PRODID'] = '-//The Horde Project//Horde_iCalendar Library' . (defined('HORDE_VERSION') ? ', Horde ' . constant('HORDE_VERSION') : '') . '//EN';
474
-        // METHOD is only required for iTip, but not for CalDAV, therefore removing it here calendar_ical sets it anyway by default
475
-        //$requiredAttributes['METHOD'] = 'PUBLISH';
476
-
477
-        foreach ($requiredAttributes as $name => $default_value) {
478
-            if (is_a($this->getattribute($name), 'PEAR_Error')) {
479
-                $this->setAttribute($name, $default_value);
480
-            }
481
-        }
482
-
483
-        return $this->_exportvData('VCALENDAR', $charset);
484
-    }
485
-
486
-    /**
487
-     * Export this entry as a hash array with tag names as keys.
488
-     *
489
-     * @param boolean $paramsInKeys
490
-     *                If false, the operation can be quite lossy as the
491
-     *                parameters are ignored when building the array keys.
492
-     *                So if you export a vcard with
493
-     *                LABEL;TYPE=WORK:foo
494
-     *                LABEL;TYPE=HOME:bar
495
-     *                the resulting hash contains only one label field!
496
-     *                If set to true, array keys look like 'LABEL;TYPE=WORK'
497
-     * @return array  A hash array with tag names as keys.
498
-     */
499
-    function toHash($paramsInKeys = false)
500
-    {
501
-        $hash = array();
502
-        foreach ($this->_attributes as $a)  {
503
-            $k = $a['name'];
504
-            if ($paramsInKeys && is_array($a['params'])) {
505
-                foreach ($a['params'] as $p => $v) {
506
-                    $k .= ";$p=$v";
507
-                }
508
-            }
509
-            $hash[$k] = $a['value'];
510
-        }
511
-
512
-        return $hash;
513
-    }
514
-
515
-    /**
516
-     * Parses a string containing vCalendar data.
517
-     *
518
-     * @todo This method doesn't work well at all, if $base is VCARD.
519
-     *
520
-     * @param string $text     The data to parse.
521
-     * @param string $base     The type of the base object.
522
-     * @param string $charset  The encoding charset for $text. Defaults to
523
-     *                         utf-8 for new format, iso-8859-1 for old format.
524
-     * @param boolean $clear   If true clears the iCal object before parsing.
525
-     *
526
-     * @return boolean  True on successful import, false otherwise.
527
-     */
528
-    function parsevCalendar($text, $base = 'VCALENDAR', $charset = null, $clear = true)
529
-    {
530
-        if ($clear) {
531
-            $this->clear();
532
-        }
533
-
534
-        if ($base == 'VTODO' &&
535
-        	preg_match('/^BEGIN:VTODO(.*)^END:VEVENT/ism', $text, $matches)) {
536
-        	// Workaround for Funambol VTODO bug in Mozilla Sync Plugins
537
-        	Horde::logMessage('iCalendar: Funambol VTODO-bug detected, workaround activated...',
538
-        		__FILE__, __LINE__, PEAR_LOG_WARNING);
539
-            $container = true;
540
-            $vCal = $matches[1];
541
-        } elseif (preg_match('/^BEGIN:' . $base . '(.*)^END:' . $base . '/ism', $text, $matches)) {
542
-            $container = true;
543
-            $vCal = $matches[1];
544
-        } else {
545
-            // Text isn't enclosed in BEGIN:VCALENDAR
546
-            // .. END:VCALENDAR. We'll try to parse it anyway.
547
-            $container = false;
548
-            $vCal = $text;
549
-        }
550
-
551
-        if (preg_match('/^VERSION:(\d\.\d)\s*$/ism', $vCal, $matches)) {
552
-            // define the version asap
553
-            #Horde::logMessage("iCalendar VERSION:" . $matches[1], __FILE__, __LINE__, PEAR_LOG_DEBUG);
554
-            $this->setAttribute('VERSION', $matches[1]);
555
-        }
461
+		return $retval;
462
+	}
463
+
464
+	/**
465
+	 * Export as vCalendar format.
466
+	 *
467
+	 * @param string $charset  The encoding charset for $text. Defaults to
468
+	 *                         utf-8 for new format, standard character set for old format.
469
+	 */
470
+	function exportvCalendar($charset = null)
471
+	{
472
+		// Default values.
473
+		$requiredAttributes['PRODID'] = '-//The Horde Project//Horde_iCalendar Library' . (defined('HORDE_VERSION') ? ', Horde ' . constant('HORDE_VERSION') : '') . '//EN';
474
+		// METHOD is only required for iTip, but not for CalDAV, therefore removing it here calendar_ical sets it anyway by default
475
+		//$requiredAttributes['METHOD'] = 'PUBLISH';
476
+
477
+		foreach ($requiredAttributes as $name => $default_value) {
478
+			if (is_a($this->getattribute($name), 'PEAR_Error')) {
479
+				$this->setAttribute($name, $default_value);
480
+			}
481
+		}
482
+
483
+		return $this->_exportvData('VCALENDAR', $charset);
484
+	}
485
+
486
+	/**
487
+	 * Export this entry as a hash array with tag names as keys.
488
+	 *
489
+	 * @param boolean $paramsInKeys
490
+	 *                If false, the operation can be quite lossy as the
491
+	 *                parameters are ignored when building the array keys.
492
+	 *                So if you export a vcard with
493
+	 *                LABEL;TYPE=WORK:foo
494
+	 *                LABEL;TYPE=HOME:bar
495
+	 *                the resulting hash contains only one label field!
496
+	 *                If set to true, array keys look like 'LABEL;TYPE=WORK'
497
+	 * @return array  A hash array with tag names as keys.
498
+	 */
499
+	function toHash($paramsInKeys = false)
500
+	{
501
+		$hash = array();
502
+		foreach ($this->_attributes as $a)  {
503
+			$k = $a['name'];
504
+			if ($paramsInKeys && is_array($a['params'])) {
505
+				foreach ($a['params'] as $p => $v) {
506
+					$k .= ";$p=$v";
507
+				}
508
+			}
509
+			$hash[$k] = $a['value'];
510
+		}
511
+
512
+		return $hash;
513
+	}
514
+
515
+	/**
516
+	 * Parses a string containing vCalendar data.
517
+	 *
518
+	 * @todo This method doesn't work well at all, if $base is VCARD.
519
+	 *
520
+	 * @param string $text     The data to parse.
521
+	 * @param string $base     The type of the base object.
522
+	 * @param string $charset  The encoding charset for $text. Defaults to
523
+	 *                         utf-8 for new format, iso-8859-1 for old format.
524
+	 * @param boolean $clear   If true clears the iCal object before parsing.
525
+	 *
526
+	 * @return boolean  True on successful import, false otherwise.
527
+	 */
528
+	function parsevCalendar($text, $base = 'VCALENDAR', $charset = null, $clear = true)
529
+	{
530
+		if ($clear) {
531
+			$this->clear();
532
+		}
533
+
534
+		if ($base == 'VTODO' &&
535
+			preg_match('/^BEGIN:VTODO(.*)^END:VEVENT/ism', $text, $matches)) {
536
+			// Workaround for Funambol VTODO bug in Mozilla Sync Plugins
537
+			Horde::logMessage('iCalendar: Funambol VTODO-bug detected, workaround activated...',
538
+				__FILE__, __LINE__, PEAR_LOG_WARNING);
539
+			$container = true;
540
+			$vCal = $matches[1];
541
+		} elseif (preg_match('/^BEGIN:' . $base . '(.*)^END:' . $base . '/ism', $text, $matches)) {
542
+			$container = true;
543
+			$vCal = $matches[1];
544
+		} else {
545
+			// Text isn't enclosed in BEGIN:VCALENDAR
546
+			// .. END:VCALENDAR. We'll try to parse it anyway.
547
+			$container = false;
548
+			$vCal = $text;
549
+		}
550
+
551
+		if (preg_match('/^VERSION:(\d\.\d)\s*$/ism', $vCal, $matches)) {
552
+			// define the version asap
553
+			#Horde::logMessage("iCalendar VERSION:" . $matches[1], __FILE__, __LINE__, PEAR_LOG_DEBUG);
554
+			$this->setAttribute('VERSION', $matches[1]);
555
+		}
556 556
 
557 557
 		// Preserve a trailing CR
558
-        $vCal = trim($vCal) . "\n";
559
-
560
-        // All subcomponents.
561
-        $matches = null;
562
-        // Workaround for Funambol VTODO bug in Mozilla Sync Plugins
563
-        if (preg_match_all('/^BEGIN:(VTODO)(\r\n|\r|\n)(.*)^END:VEVENT/Uims', $vCal, $matches) ||
564
-        	preg_match_all('/^BEGIN:(.*)(\r\n|\r|\n)(.*)^END:\1/Uims', $vCal, $matches)) {
565
-            // vTimezone components are processed first. They are
566
-            // needed to process vEvents that may use a TZID.
567
-            foreach ($matches[0] as $key => $data) {
568
-                $type = trim($matches[1][$key]);
569
-                if ($type != 'VTIMEZONE') {
570
-                    continue;
571
-                }
572
-                $component = &Horde_iCalendar::newComponent($type, $this);
573
-                if ($component === false) {
574
-                    return PEAR::raiseError("Unable to create object for type $type");
575
-                }
576
-                $component->parsevCalendar($data, $type, $charset);
577
-
578
-                $this->addComponent($component);
579
-
580
-                // Remove from the vCalendar data.
581
-                $vCal = str_replace($data, '', $vCal);
582
-            }
583
-
584
-            // Now process the non-vTimezone components.
585
-            foreach ($matches[0] as $key => $data) {
586
-                $type = trim($matches[1][$key]);
587
-                if ($type == 'VTIMEZONE') {
588
-                    continue;
589
-                }
590
-                $component = &Horde_iCalendar::newComponent($type, $this);
591
-                if ($component === false) {
592
-                    return PEAR::raiseError("Unable to create object for type $type");
593
-                }
594
-                $component->parsevCalendar($data, $type, $charset);
595
-
596
-                $this->addComponent($component);
597
-
598
-                // Remove from the vCalendar data.
599
-                $vCal = str_replace($data, '', $vCal);
600
-            }
601
-        } elseif (!$container) {
602
-            return false;
603
-        }
604
-
605
-        // Unfold "quoted printable" folded lines like:
606
-        //  BODY;ENCODING=QUOTED-PRINTABLE:=
607
-        //  another=20line=
608
-        //  last=20line
609
-        while (preg_match_all('/^([^:]+;\s*((ENCODING=)?QUOTED-PRINTABLE|ENCODING=[Q|q])(.*=\r?\n)+(.*[^=])?\r?\n)/mU', $vCal, $matches)) {
610
-            foreach ($matches[1] as $s) {
611
-            	if ($this->isOldFormat()) {
612
-                	$r = preg_replace('/=\r?\n([ \t])?/', '\1', $s);
613
-            	} else {
614
-            		$r = preg_replace('/=\r?\n[ \t]*/', '', $s);
615
-            	}
616
-                $vCal = str_replace($s, $r, $vCal);
617
-            }
618
-        }
619
-
620
-        // Unfold any folded lines.
621
-        if ($this->isOldFormat()) {
622
-        	// old formats force folding at whitespace which must therefore be preserved
623
-        	$vCal = preg_replace('/[\r\n]+([ \t])/', '\1', $vCal);
624
-        } else {
625
-        	$vCal = preg_replace('/[\r\n]+[ \t]/', '', $vCal);
626
-        }
558
+		$vCal = trim($vCal) . "\n";
559
+
560
+		// All subcomponents.
561
+		$matches = null;
562
+		// Workaround for Funambol VTODO bug in Mozilla Sync Plugins
563
+		if (preg_match_all('/^BEGIN:(VTODO)(\r\n|\r|\n)(.*)^END:VEVENT/Uims', $vCal, $matches) ||
564
+			preg_match_all('/^BEGIN:(.*)(\r\n|\r|\n)(.*)^END:\1/Uims', $vCal, $matches)) {
565
+			// vTimezone components are processed first. They are
566
+			// needed to process vEvents that may use a TZID.
567
+			foreach ($matches[0] as $key => $data) {
568
+				$type = trim($matches[1][$key]);
569
+				if ($type != 'VTIMEZONE') {
570
+					continue;
571
+				}
572
+				$component = &Horde_iCalendar::newComponent($type, $this);
573
+				if ($component === false) {
574
+					return PEAR::raiseError("Unable to create object for type $type");
575
+				}
576
+				$component->parsevCalendar($data, $type, $charset);
577
+
578
+				$this->addComponent($component);
579
+
580
+				// Remove from the vCalendar data.
581
+				$vCal = str_replace($data, '', $vCal);
582
+			}
583
+
584
+			// Now process the non-vTimezone components.
585
+			foreach ($matches[0] as $key => $data) {
586
+				$type = trim($matches[1][$key]);
587
+				if ($type == 'VTIMEZONE') {
588
+					continue;
589
+				}
590
+				$component = &Horde_iCalendar::newComponent($type, $this);
591
+				if ($component === false) {
592
+					return PEAR::raiseError("Unable to create object for type $type");
593
+				}
594
+				$component->parsevCalendar($data, $type, $charset);
595
+
596
+				$this->addComponent($component);
597
+
598
+				// Remove from the vCalendar data.
599
+				$vCal = str_replace($data, '', $vCal);
600
+			}
601
+		} elseif (!$container) {
602
+			return false;
603
+		}
604
+
605
+		// Unfold "quoted printable" folded lines like:
606
+		//  BODY;ENCODING=QUOTED-PRINTABLE:=
607
+		//  another=20line=
608
+		//  last=20line
609
+		while (preg_match_all('/^([^:]+;\s*((ENCODING=)?QUOTED-PRINTABLE|ENCODING=[Q|q])(.*=\r?\n)+(.*[^=])?\r?\n)/mU', $vCal, $matches)) {
610
+			foreach ($matches[1] as $s) {
611
+				if ($this->isOldFormat()) {
612
+					$r = preg_replace('/=\r?\n([ \t])?/', '\1', $s);
613
+				} else {
614
+					$r = preg_replace('/=\r?\n[ \t]*/', '', $s);
615
+				}
616
+				$vCal = str_replace($s, $r, $vCal);
617
+			}
618
+		}
619
+
620
+		// Unfold any folded lines.
621
+		if ($this->isOldFormat()) {
622
+			// old formats force folding at whitespace which must therefore be preserved
623
+			$vCal = preg_replace('/[\r\n]+([ \t])/', '\1', $vCal);
624
+		} else {
625
+			$vCal = preg_replace('/[\r\n]+[ \t]/', '', $vCal);
626
+		}
627 627
 
628 628
 		$isDate = false;
629 629
 
630
-        // Parse the remaining attributes.
631
-        if (preg_match_all('/^((?:[^":]+|(?:"[^"]*")+)*):([^\r\n]*)\r?$/m', $vCal, $matches)) {
632
-            foreach ($matches[0] as $attribute) {
633
-                preg_match('/([^:;]*)((;(?:(?:[^":\\\]*(?:\\\.)?)+|(?:"[^"]*")+)*)?):([^\r\n]*)[\r\n]*/', $attribute, $parts);
634
-                $tag = trim(String::upper($parts[1]));
635
-                $value = $parts[4];
636
-                $params = array();
637
-
638
-                // Parse parameters.
639
-                if (!empty($parts[2])) {
640
-                    preg_match_all('/;(([^;=]*)(=("[^"]*"|(?:[^;\\\]*(?:\\\.)?)*))?)/', $parts[2], $param_parts);
641
-                    foreach ($param_parts[2] as $key => $paramName) {
642
-                        $paramName = String::upper($paramName);
643
-                        $paramValue = $param_parts[4][$key];
644
-                        if ($paramName == 'TYPE') {
645
-                            $paramValue = preg_split('/(?<!\\\\),/', $paramValue);
646
-                            if (isset($params[$paramName])) {
647
-                        		if (!is_array($params[$paramName])) {
648
-                        			$params[$paramName] = array($params[$paramName]);
649
-                        		}
650
-                        		$params[$paramName] = array_merge($params[$paramName], $paramValue);
651
-                        	} else {
652
-                        		if (count($paramValue) == 1) {
653
-                                	$paramValue = $paramValue[0];
654
-                            	}
655
-                            	$params[$paramName] = $paramValue;
656
-                        	}
657
-                        } else {
658
-                        	$params[$paramName] = $paramValue;
659
-                        }
660
-                    }
661
-                }
662
-
663
-                // Charset and encoding handling.
664
-                if (isset($params['QUOTED-PRINTABLE'])) {
665
-	                $params['ENCODING'] = 'QUOTED-PRINTABLE';
666
-                }
667
-                if (isset($params['BASE64'])) {
668
-	                $params['ENCODING'] = 'BASE64';
669
-                }
670
-                if (isset($params['ENCODING'])) {
671
-	                switch (String::upper($params['ENCODING'])) {
672
-		                case 'Q':
673
-		                case 'QUOTED-PRINTABLE':
674
-			                $value = quoted_printable_decode($value);
675
-			                if (isset($params['CHARSET'])) {
676
-				                $value = $GLOBALS['egw']->translation->convert($value, $params['CHARSET']);
677
-			                } else {
678
-				                $value = $GLOBALS['egw']->translation->convert($value,
679
-					                empty($charset) ? ($this->isOldFormat() ? 'iso-8859-1' : 'utf-8') : $charset);
680
-			                }
681
-			                // Funambol hack :-(
682
-			                $value = str_replace('\\\\n', "\n", $value);
683
-			                break;
684
-		                case 'B':
685
-		                case 'BASE64':
686
-			                $value = base64_decode($value);
687
-			                break;
688
-	                }
689
-                } elseif (isset($params['CHARSET'])) {
690
-	                $value = $GLOBALS['egw']->translation->convert($value, $params['CHARSET']);
691
-                } else {
692
-	                // As per RFC 2279, assume UTF8 if we don't have an
693
-	                // explicit charset parameter.
694
-	                $value = $GLOBALS['egw']->translation->convert($value,
695
-		                empty($charset) ? ($this->isOldFormat() ? 'iso-8859-1' : 'utf-8') : $charset);
696
-                }
697
-
698
-                // Get timezone info for date fields from $params.
699
-                $tzid = isset($params['TZID']) ? trim($params['TZID'], '\"') : false;
700
-
701
-                switch ($tag) {
702
-	                case 'VERSION': // already processed
703
-		                break;
704
-		                // Date fields.
705
-	                case 'COMPLETED':
706
-	                case 'CREATED':
707
-	                case 'LAST-MODIFIED':
708
-		                $this->setAttribute($tag, $this->_parseDateTime($value, $tzid), $params);
709
-		                break;
710
-
711
-	                case 'BDAY':
712
-	                case 'X-SYNCJE-ANNIVERSARY':
713
-		                $this->setAttribute($tag, $value, $params, true, $this->_parseDate($value));
714
-		                break;
715
-
716
-	                case 'DTEND':
717
-	                case 'DTSTART':
718
-	                case 'DTSTAMP':
719
-	                case 'DUE':
720
-	                case 'AALARM':
721
-	                case 'DALARM':
722
-	                case 'RECURRENCE-ID':
723
-	                case 'X-RECURRENCE-ID':
724
-		                // types like AALARM may contain additional data after a ;
725
-		                // ignore these.
726
-		                $ts = explode(';', $value);
727
-		                if (isset($params['VALUE']) && $params['VALUE'] == 'DATE') {
728
-			                $isDate = true;
729
-			                $this->setAttribute($tag, $this->_parseDateTime($ts[0], $tzid), $params, true, $this->_parseDate($ts[0]));
730
-		                } else {
731
-			                $this->setAttribute($tag, $this->_parseDateTime($ts[0], $tzid), $params);
732
-		                }
733
-		                break;
734
-
735
-	                case 'TRIGGER':
736
-		                if (isset($params['VALUE'])) {
737
-			                if ($params['VALUE'] == 'DATE-TIME') {
738
-				                $this->setAttribute($tag, $this->_parseDateTime($value, $tzid), $params);
739
-			                } else {
740
-				                $this->setAttribute($tag, $this->_parseDuration($value), $params);
741
-			                }
742
-		                } else {
743
-			                $this->setAttribute($tag, $this->_parseDuration($value), $params);
744
-		                }
745
-		                break;
746
-
747
-		                // Comma or semicolon seperated dates.
748
-	                case 'EXDATE':
749
-	                case 'RDATE':
750
-		                $dates = array();
751
-		                preg_match_all('/[;,]([^;,]*)/', ';' . $value, $values);
752
-
753
-		                foreach ($values[1] as $value) {
754
-			                if ((isset($params['VALUE'])
755
-					                && $params['VALUE'] == 'DATE') || (!isset($params['VALUE']) && $isDate)) {
756
-				                $dates[] = $this->_parseDate(trim($value));
757
-			                } else {
758
-				                $dates[] = $this->_parseDateTime(trim($value), $tzid);
759
-			                }
760
-		                }
761
-		                $this->setAttribute($tag, isset($dates[0]) ? $dates[0] : null, $params, true, $dates);
762
-		                break;
763
-
764
-		                // Duration fields.
765
-	                case 'DURATION':
766
-		                $this->setAttribute($tag, $this->_parseDuration($value), $params);
767
-		                break;
768
-
769
-		                // Period of time fields.
770
-	                case 'FREEBUSY':
771
-		                $periods = array();
772
-		                preg_match_all('/,([^,]*)/', ',' . $value, $values);
773
-		                foreach ($values[1] as $value) {
774
-			                $periods[] = $this->_parsePeriod($value);
775
-		                }
776
-
777
-		                $this->setAttribute($tag, isset($periods[0]) ? $periods[0] : null, $params, true, $periods);
778
-		                break;
779
-
780
-		                // UTC offset fields.
781
-	                case 'TZOFFSETFROM':
782
-	                case 'TZOFFSETTO':
783
-		                $this->setAttribute($tag, $this->_parseUtcOffset($value), $params);
784
-		                break;
785
-
786
-		                // Integer fields.
787
-	                case 'PERCENT-COMPLETE':
788
-	                case 'PRIORITY':
789
-	                case 'REPEAT':
790
-	                case 'SEQUENCE':
791
-		                $this->setAttribute($tag, intval($value), $params);
792
-		                break;
793
-
794
-		                // Geo fields.
795
-	                case 'GEO':
796
-		                if ($this->isOldFormat()) {
797
-			                $floats = explode(',', $value);
798
-			                $value = array('latitude' => floatval($floats[1]),
799
-				                'longitude' => floatval($floats[0]));
800
-		                } else {
801
-			                $floats = explode(';', $value);
802
-			                $value = array('latitude' => floatval($floats[0]),
803
-				                'longitude' => floatval($floats[1]));
804
-		                }
805
-		                $this->setAttribute($tag, $value, $params);
806
-		                break;
807
-
808
-		                // Recursion fields. # add more flexibility
809
-		                #case 'EXRULE':
810
-		                #case 'RRULE':
811
-		                #    $this->setAttribute($tag, trim($value), $params);
812
-		                #    break;
813
-
814
-		                // Binary fields.
815
-	                case 'PHOTO':
816
-		                $this->setAttribute($tag, $value, $params);
817
-		                break;
818
-
819
-		                // ADR, ORG and N are lists seperated by unescaped semicolons
820
-		                // with a specific number of slots.
821
-	                case 'ADR':
822
-	                case 'N':
823
-	                case 'ORG':
824
-		                $value = trim($value);
825
-		                // As of rfc 2426 2.4.2 semicolon, comma, and colon must
826
-		                // be escaped (semicolon is unescaped after splitting below).
827
-		                $value = str_replace(array('\\n', '\\N', '\\,', '\\:'),
828
-			                array("\n", "\n", ',', ':'),
630
+		// Parse the remaining attributes.
631
+		if (preg_match_all('/^((?:[^":]+|(?:"[^"]*")+)*):([^\r\n]*)\r?$/m', $vCal, $matches)) {
632
+			foreach ($matches[0] as $attribute) {
633
+				preg_match('/([^:;]*)((;(?:(?:[^":\\\]*(?:\\\.)?)+|(?:"[^"]*")+)*)?):([^\r\n]*)[\r\n]*/', $attribute, $parts);
634
+				$tag = trim(String::upper($parts[1]));
635
+				$value = $parts[4];
636
+				$params = array();
637
+
638
+				// Parse parameters.
639
+				if (!empty($parts[2])) {
640
+					preg_match_all('/;(([^;=]*)(=("[^"]*"|(?:[^;\\\]*(?:\\\.)?)*))?)/', $parts[2], $param_parts);
641
+					foreach ($param_parts[2] as $key => $paramName) {
642
+						$paramName = String::upper($paramName);
643
+						$paramValue = $param_parts[4][$key];
644
+						if ($paramName == 'TYPE') {
645
+							$paramValue = preg_split('/(?<!\\\\),/', $paramValue);
646
+							if (isset($params[$paramName])) {
647
+								if (!is_array($params[$paramName])) {
648
+									$params[$paramName] = array($params[$paramName]);
649
+								}
650
+								$params[$paramName] = array_merge($params[$paramName], $paramValue);
651
+							} else {
652
+								if (count($paramValue) == 1) {
653
+									$paramValue = $paramValue[0];
654
+								}
655
+								$params[$paramName] = $paramValue;
656
+							}
657
+						} else {
658
+							$params[$paramName] = $paramValue;
659
+						}
660
+					}
661
+				}
662
+
663
+				// Charset and encoding handling.
664
+				if (isset($params['QUOTED-PRINTABLE'])) {
665
+					$params['ENCODING'] = 'QUOTED-PRINTABLE';
666
+				}
667
+				if (isset($params['BASE64'])) {
668
+					$params['ENCODING'] = 'BASE64';
669
+				}
670
+				if (isset($params['ENCODING'])) {
671
+					switch (String::upper($params['ENCODING'])) {
672
+						case 'Q':
673
+						case 'QUOTED-PRINTABLE':
674
+							$value = quoted_printable_decode($value);
675
+							if (isset($params['CHARSET'])) {
676
+								$value = $GLOBALS['egw']->translation->convert($value, $params['CHARSET']);
677
+							} else {
678
+								$value = $GLOBALS['egw']->translation->convert($value,
679
+									empty($charset) ? ($this->isOldFormat() ? 'iso-8859-1' : 'utf-8') : $charset);
680
+							}
681
+							// Funambol hack :-(
682
+							$value = str_replace('\\\\n', "\n", $value);
683
+							break;
684
+						case 'B':
685
+						case 'BASE64':
686
+							$value = base64_decode($value);
687
+							break;
688
+					}
689
+				} elseif (isset($params['CHARSET'])) {
690
+					$value = $GLOBALS['egw']->translation->convert($value, $params['CHARSET']);
691
+				} else {
692
+					// As per RFC 2279, assume UTF8 if we don't have an
693
+					// explicit charset parameter.
694
+					$value = $GLOBALS['egw']->translation->convert($value,
695
+						empty($charset) ? ($this->isOldFormat() ? 'iso-8859-1' : 'utf-8') : $charset);
696
+				}
697
+
698
+				// Get timezone info for date fields from $params.
699
+				$tzid = isset($params['TZID']) ? trim($params['TZID'], '\"') : false;
700
+
701
+				switch ($tag) {
702
+					case 'VERSION': // already processed
703
+						break;
704
+						// Date fields.
705
+					case 'COMPLETED':
706
+					case 'CREATED':
707
+					case 'LAST-MODIFIED':
708
+						$this->setAttribute($tag, $this->_parseDateTime($value, $tzid), $params);
709
+						break;
710
+
711
+					case 'BDAY':
712
+					case 'X-SYNCJE-ANNIVERSARY':
713
+						$this->setAttribute($tag, $value, $params, true, $this->_parseDate($value));
714
+						break;
715
+
716
+					case 'DTEND':
717
+					case 'DTSTART':
718
+					case 'DTSTAMP':
719
+					case 'DUE':
720
+					case 'AALARM':
721
+					case 'DALARM':
722
+					case 'RECURRENCE-ID':
723
+					case 'X-RECURRENCE-ID':
724
+						// types like AALARM may contain additional data after a ;
725
+						// ignore these.
726
+						$ts = explode(';', $value);
727
+						if (isset($params['VALUE']) && $params['VALUE'] == 'DATE') {
728
+							$isDate = true;
729
+							$this->setAttribute($tag, $this->_parseDateTime($ts[0], $tzid), $params, true, $this->_parseDate($ts[0]));
730
+						} else {
731
+							$this->setAttribute($tag, $this->_parseDateTime($ts[0], $tzid), $params);
732
+						}
733
+						break;
734
+
735
+					case 'TRIGGER':
736
+						if (isset($params['VALUE'])) {
737
+							if ($params['VALUE'] == 'DATE-TIME') {
738
+								$this->setAttribute($tag, $this->_parseDateTime($value, $tzid), $params);
739
+							} else {
740
+								$this->setAttribute($tag, $this->_parseDuration($value), $params);
741
+							}
742
+						} else {
743
+							$this->setAttribute($tag, $this->_parseDuration($value), $params);
744
+						}
745
+						break;
746
+
747
+						// Comma or semicolon seperated dates.
748
+					case 'EXDATE':
749
+					case 'RDATE':
750
+						$dates = array();
751
+						preg_match_all('/[;,]([^;,]*)/', ';' . $value, $values);
752
+
753
+						foreach ($values[1] as $value) {
754
+							if ((isset($params['VALUE'])
755
+									&& $params['VALUE'] == 'DATE') || (!isset($params['VALUE']) && $isDate)) {
756
+								$dates[] = $this->_parseDate(trim($value));
757
+							} else {
758
+								$dates[] = $this->_parseDateTime(trim($value), $tzid);
759
+							}
760
+						}
761
+						$this->setAttribute($tag, isset($dates[0]) ? $dates[0] : null, $params, true, $dates);
762
+						break;
763
+
764
+						// Duration fields.
765
+					case 'DURATION':
766
+						$this->setAttribute($tag, $this->_parseDuration($value), $params);
767
+						break;
768
+
769
+						// Period of time fields.
770
+					case 'FREEBUSY':
771
+						$periods = array();
772
+						preg_match_all('/,([^,]*)/', ',' . $value, $values);
773
+						foreach ($values[1] as $value) {
774
+							$periods[] = $this->_parsePeriod($value);
775
+						}
776
+
777
+						$this->setAttribute($tag, isset($periods[0]) ? $periods[0] : null, $params, true, $periods);
778
+						break;
779
+
780
+						// UTC offset fields.
781
+					case 'TZOFFSETFROM':
782
+					case 'TZOFFSETTO':
783
+						$this->setAttribute($tag, $this->_parseUtcOffset($value), $params);
784
+						break;
785
+
786
+						// Integer fields.
787
+					case 'PERCENT-COMPLETE':
788
+					case 'PRIORITY':
789
+					case 'REPEAT':
790
+					case 'SEQUENCE':
791
+						$this->setAttribute($tag, intval($value), $params);
792
+						break;
793
+
794
+						// Geo fields.
795
+					case 'GEO':
796
+						if ($this->isOldFormat()) {
797
+							$floats = explode(',', $value);
798
+							$value = array('latitude' => floatval($floats[1]),
799
+								'longitude' => floatval($floats[0]));
800
+						} else {
801
+							$floats = explode(';', $value);
802
+							$value = array('latitude' => floatval($floats[0]),
803
+								'longitude' => floatval($floats[1]));
804
+						}
805
+						$this->setAttribute($tag, $value, $params);
806
+						break;
807
+
808
+						// Recursion fields. # add more flexibility
809
+						#case 'EXRULE':
810
+						#case 'RRULE':
811
+						#    $this->setAttribute($tag, trim($value), $params);
812
+						#    break;
813
+
814
+						// Binary fields.
815
+					case 'PHOTO':
816
+						$this->setAttribute($tag, $value, $params);
817
+						break;
818
+
819
+						// ADR, ORG and N are lists seperated by unescaped semicolons
820
+						// with a specific number of slots.
821
+					case 'ADR':
822
+					case 'N':
823
+					case 'ORG':
824
+						$value = trim($value);
825
+						// As of rfc 2426 2.4.2 semicolon, comma, and colon must
826
+						// be escaped (semicolon is unescaped after splitting below).
827
+						$value = str_replace(array('\\n', '\\N', '\\,', '\\:'),
828
+							array("\n", "\n", ',', ':'),
829 829
 							$value);
830 830
 
831
-		                // Split by unescaped semicolons:
832
-		                $values = preg_split('/(?<!\\\\);/', $value);
833
-		                $value = str_replace('\\;', ';', $value);
834
-		                $values = str_replace('\\;', ';', $values);
835
-		                $this->setAttribute($tag, trim($value), $params, true, $values);
836
-		                break;
837
-
838
-		                // CATEGORIES is a lists seperated by unescaped commas
839
-		                // with a unspecific number of slots.
840
-	                case 'CATEGORIES':
841
-		                $value = trim($value);
842
-		                // As of rfc 2426 2.4.2 semicolon, comma, and colon must
843
-		                // be escaped (comma is unescaped after splitting below).
844
-		                $value = str_replace(array('\\n', '\\N', '\\;', '\\:'),
845
-			                array("\n", "\n", ';', ':'),
831
+						// Split by unescaped semicolons:
832
+						$values = preg_split('/(?<!\\\\);/', $value);
833
+						$value = str_replace('\\;', ';', $value);
834
+						$values = str_replace('\\;', ';', $values);
835
+						$this->setAttribute($tag, trim($value), $params, true, $values);
836
+						break;
837
+
838
+						// CATEGORIES is a lists seperated by unescaped commas
839
+						// with a unspecific number of slots.
840
+					case 'CATEGORIES':
841
+						$value = trim($value);
842
+						// As of rfc 2426 2.4.2 semicolon, comma, and colon must
843
+						// be escaped (comma is unescaped after splitting below).
844
+						$value = str_replace(array('\\n', '\\N', '\\;', '\\:'),
845
+							array("\n", "\n", ';', ':'),
846 846
 							$value);
847 847
 
848
-		                // Split by unescaped commas:
849
-		                $values = preg_split('/(?<!\\\\),/', $value);
850
-		                $value = str_replace('\\,', ',', $value);
851
-		                $values = str_replace('\\,', ',', $values);
852
-		                $this->setAttribute($tag, trim($value), $params, true, $values);
853
-		                break;
854
-
855
-		                // String fields.
856
-	                default:
857
-		                if ($this->isOldFormat()) {
858
-			                $value = trim($value);
859
-			                // vCalendar 1.0 and vCard 2.1 only escape semicolons
860
-			                // and use unescaped semicolons to create lists.
861
-			                $value = str_replace(array('\\n', '\\N', '\\,', '\\:'),
862
-				                array("\n", "\n", ',', ':'),
848
+						// Split by unescaped commas:
849
+						$values = preg_split('/(?<!\\\\),/', $value);
850
+						$value = str_replace('\\,', ',', $value);
851
+						$values = str_replace('\\,', ',', $values);
852
+						$this->setAttribute($tag, trim($value), $params, true, $values);
853
+						break;
854
+
855
+						// String fields.
856
+					default:
857
+						if ($this->isOldFormat()) {
858
+							$value = trim($value);
859
+							// vCalendar 1.0 and vCard 2.1 only escape semicolons
860
+							// and use unescaped semicolons to create lists.
861
+							$value = str_replace(array('\\n', '\\N', '\\,', '\\:'),
862
+								array("\n", "\n", ',', ':'),
863 863
 								$value);
864 864
 
865
-			                // Split by unescaped semicolons:
866
-			                $values = preg_split('/(?<!\\\\);/', $value);
867
-			                $value = str_replace('\\;', ';', $value);
868
-			                $values = str_replace('\\;', ';', $values);
869
-			                $this->setAttribute($tag, trim($value), $params, true, $values);
870
-		                } else {
871
-			                $value = trim($value);
872
-			                // As of rfc 2426 2.4.2 semicolon, comma, and colon
873
-			                // must be escaped (comma is unescaped after splitting
874
-			                // below).
875
-			                $value = str_replace(array('\\n', '\\N', '\\;', '\\:', '\\\\'),
876
-				                array("\n", "\n", ';', ':', '\\'),
865
+							// Split by unescaped semicolons:
866
+							$values = preg_split('/(?<!\\\\);/', $value);
867
+							$value = str_replace('\\;', ';', $value);
868
+							$values = str_replace('\\;', ';', $values);
869
+							$this->setAttribute($tag, trim($value), $params, true, $values);
870
+						} else {
871
+							$value = trim($value);
872
+							// As of rfc 2426 2.4.2 semicolon, comma, and colon
873
+							// must be escaped (comma is unescaped after splitting
874
+							// below).
875
+							$value = str_replace(array('\\n', '\\N', '\\;', '\\:', '\\\\'),
876
+								array("\n", "\n", ';', ':', '\\'),
877 877
 								$value);
878 878
 
879
-			                // Split by unescaped commas.
880
-			                $values = preg_split('/(?<!\\\\),/', $value);
881
-			                $value = str_replace('\\,', ',', $value);
882
-			                $values = str_replace('\\,', ',', $values);
883
-			                $this->setAttribute($tag, trim($value), $params, true, $values);
884
-		                }
885
-	                break;
886
-                }
887
-            }
888
-        }
889
-
890
-        return true;
891
-    }
892
-
893
-    /**
894
-     * Export this component in vCal format.
895
-     *
896
-     * @param string $base  The type of the base object.
897
-     * @param string $charset  The encoding charset for $text. Defaults to
898
-     *                         utf-8 for new format, standard character set for old format.
899
-     *
900
-     * @return string  vCal format data.
901
-     */
902
-    function _exportvData($base = 'VCALENDAR', $charset = null)
903
-    {
904
-    	$base = String::upper($base);
905
-
906
-        $result = 'BEGIN:' . $base . $this->_newline;
907
-
908
-        // VERSION is not allowed for entries enclosed in VCALENDAR/ICALENDAR,
909
-        // as it is part of the enclosing VCALENDAR/ICALENDAR. See rfc2445
910
-        if ($base !== 'VEVENT' && $base !== 'VTODO' && $base !== 'VALARM' &&
911
-            $base !== 'VJOURNAL' && $base !== 'VFREEBUSY' &&
912
-            $base !== 'VTIMEZONE' && $base !== 'STANDARD' && $base != 'DAYLIGHT') {
913
-            // Ensure that version is the first attribute.
914
-            $result .= 'VERSION:' . $this->_version . $this->_newline;
915
-        }
916
-
917
-        if (empty($charset)) {
918
-        	if ($this->isOldFormat()) {
919
-        		$charset = NLS::getCharset();
920
-        	} else {
921
-        		$charset = 'utf-8';
922
-        	}
923
-        }
924
-
925
-        foreach ($this->_attributes as $attribute) {
926
-            $name = $attribute['name'];
927
-            if ($name == 'VERSION') {
928
-                // Already done.
929
-                continue;
930
-            }
931
-
932
-            $params_str = '';
933
-            $params = $attribute['params'];
934
-            if ($params) {
935
-                foreach ($params as $param_name => $param_value) {
936
-                    /* Skip CHARSET for iCalendar 2.0 data, not allowed. */
937
-                    if ($param_name == 'CHARSET') {
938
-                    	if (!$this->isOldFormat() || empty($param_value)) {
939
-                        	continue;
940
-                    	} else {
941
-                    		$param_value = String::Upper($param_value);
942
-                    	}
943
-                    }
944
-                    if ($param_name == 'ENCODING') {
945
-                    	continue;
946
-                    }
947
-                    /* Skip VALUE=DATE for vCalendar 1.0 data, not allowed. */
948
-                    if ($this->isOldFormat() &&
949
-                        $param_name == 'VALUE' && $param_value == 'DATE') {
950
-                        continue;
951
-                    }
952
-                    /* Skip TZID for iCalendar 1.0 data, not supported. */
879
+							// Split by unescaped commas.
880
+							$values = preg_split('/(?<!\\\\),/', $value);
881
+							$value = str_replace('\\,', ',', $value);
882
+							$values = str_replace('\\,', ',', $values);
883
+							$this->setAttribute($tag, trim($value), $params, true, $values);
884
+						}
885
+					break;
886
+				}
887
+			}
888
+		}
889
+
890
+		return true;
891
+	}
892
+
893
+	/**
894
+	 * Export this component in vCal format.
895
+	 *
896
+	 * @param string $base  The type of the base object.
897
+	 * @param string $charset  The encoding charset for $text. Defaults to
898
+	 *                         utf-8 for new format, standard character set for old format.
899
+	 *
900
+	 * @return string  vCal format data.
901
+	 */
902
+	function _exportvData($base = 'VCALENDAR', $charset = null)
903
+	{
904
+		$base = String::upper($base);
905
+
906
+		$result = 'BEGIN:' . $base . $this->_newline;
907
+
908
+		// VERSION is not allowed for entries enclosed in VCALENDAR/ICALENDAR,
909
+		// as it is part of the enclosing VCALENDAR/ICALENDAR. See rfc2445
910
+		if ($base !== 'VEVENT' && $base !== 'VTODO' && $base !== 'VALARM' &&
911
+			$base !== 'VJOURNAL' && $base !== 'VFREEBUSY' &&
912
+			$base !== 'VTIMEZONE' && $base !== 'STANDARD' && $base != 'DAYLIGHT') {
913
+			// Ensure that version is the first attribute.
914
+			$result .= 'VERSION:' . $this->_version . $this->_newline;
915
+		}
916
+
917
+		if (empty($charset)) {
918
+			if ($this->isOldFormat()) {
919
+				$charset = NLS::getCharset();
920
+			} else {
921
+				$charset = 'utf-8';
922
+			}
923
+		}
924
+
925
+		foreach ($this->_attributes as $attribute) {
926
+			$name = $attribute['name'];
927
+			if ($name == 'VERSION') {
928
+				// Already done.
929
+				continue;
930
+			}
931
+
932
+			$params_str = '';
933
+			$params = $attribute['params'];
934
+			if ($params) {
935
+				foreach ($params as $param_name => $param_value) {
936
+					/* Skip CHARSET for iCalendar 2.0 data, not allowed. */
937
+					if ($param_name == 'CHARSET') {
938
+						if (!$this->isOldFormat() || empty($param_value)) {
939
+							continue;
940
+						} else {
941
+							$param_value = String::Upper($param_value);
942
+						}
943
+					}
944
+					if ($param_name == 'ENCODING') {
945
+						continue;
946
+					}
947
+					/* Skip VALUE=DATE for vCalendar 1.0 data, not allowed. */
948
+					if ($this->isOldFormat() &&
949
+						$param_name == 'VALUE' && $param_value == 'DATE') {
950
+						continue;
951
+					}
952
+					/* Skip TZID for iCalendar 1.0 data, not supported. */
953 953
 					if ($this->isOldFormat() && $param_name == 'TZID') {
954
-                        continue;
955
-                    }
956
-                    // Skip CN in ATTENDEE adn ORGANIZER for vCalendar 1.0
957
-                    if ($this->isOldFormat() && $param_name == 'CN' &&
958
-                    	($name == 'ATTENDEE' || $name == 'ORGANIZER')) {
959
-                    	continue;
960
-                    }
961
-                    if ($param_value === null) {
962
-                        $params_str .= ";$param_name";
963
-                    } else {
964
-                        $params_str .= ";$param_name=$param_value";
965
-                    }
966
-                }
967
-            }
968
-
969
-            $value = $attribute['value'];
970
-
971
-            switch ($name) {
972
-            // Date fields.
973
-            case 'COMPLETED':
974
-            case 'CREATED':
975
-            case 'DCREATED':
976
-            case 'LAST-MODIFIED':
977
-                $value = $this->_exportDateTime($value);
978
-                break;
954
+						continue;
955
+					}
956
+					// Skip CN in ATTENDEE adn ORGANIZER for vCalendar 1.0
957
+					if ($this->isOldFormat() && $param_name == 'CN' &&
958
+						($name == 'ATTENDEE' || $name == 'ORGANIZER')) {
959
+						continue;
960
+					}
961
+					if ($param_value === null) {
962
+						$params_str .= ";$param_name";
963
+					} else {
964
+						$params_str .= ";$param_name=$param_value";
965
+					}
966
+				}
967
+			}
968
+
969
+			$value = $attribute['value'];
970
+
971
+			switch ($name) {
972
+			// Date fields.
973
+			case 'COMPLETED':
974
+			case 'CREATED':
975
+			case 'DCREATED':
976
+			case 'LAST-MODIFIED':
977
+				$value = $this->_exportDateTime($value);
978
+				break;
979 979
 
980 980
 			// Support additional fields after date.
981 981
  			case 'AALARM':
982
-            case 'DALARM':
983
-            	if (isset($params['VALUE'])) {
984
-                    if ($params['VALUE'] == 'DATE') {
985
-                        // VCALENDAR 1.0 uses T000000 - T235959 for all day events:
986
-                        if ($this->isOldFormat() && $name == 'DTEND') {
987
-                            $d = new Horde_Date($value);
988
-                            $value = new Horde_Date(array(
989
-                                'year' => $d->year,
990
-                                'month' => $d->month,
991
-                                'mday' => $d->mday - 1));
992
-                            $value->correct();
993
-                            $value = $this->_exportDate($value, '235959');
994
-                        } else {
995
-                            $value = $this->_exportDate($value, '000000');
996
-                        }
997
-                    } else {
998
-                        $value = $this->_exportDateTime($value);
999
-                    }
1000
-                } else {
1001
-                    $value = $this->_exportDateTime($value);
1002
-                }
1003
-
1004
-            	if (is_array($attribute['values']) &&
1005
-		            	count($attribute['values']) > 0) {
1006
-		            $values = $attribute['values'];
1007
-	            	if ($this->isOldFormat()) {
1008
-		            	$values = str_replace(';', '\\;', $values);
1009
-	            	} else {
1010
-                        // As of rfc 2426 2.5 semicolon and comma must be
1011
-                        // escaped.
1012
-                        $values = str_replace(array('\\', ';', ','),
1013
-                                              array('\\\\', '\\;', '\\,'),
1014
-                                              $values);
1015
-	            	}
1016
-	            	$value .= ';' . implode(';', $values);
1017
-		         }
1018
-
1019
-                break;
1020
-
1021
-            case 'DTEND':
1022
-            case 'DTSTART':
1023
-            case 'DTSTAMP':
1024
-            case 'DUE':
1025
-            case 'RECURRENCE-ID':
1026
-            case 'X-RECURRENCE-ID':
1027
-                if (isset($params['VALUE'])) {
1028
-                    if ($params['VALUE'] == 'DATE') {
1029
-                        // VCALENDAR 1.0 uses T000000 - T235959 for all day events:
1030
-                        if ($this->isOldFormat() && $name == 'DTEND') {
1031
-                            $d = new Horde_Date($value);
1032
-                            $value = new Horde_Date(array(
1033
-                                'year' => $d->year,
1034
-                                'month' => $d->month,
1035
-                                'mday' => $d->mday - 1));
1036
-                            $value->correct();
1037
-                            $value = $this->_exportDate($value, '235959');
1038
-                        } else {
1039
-                            $value = $this->_exportDate($value, '000000');
1040
-                        }
1041
-                    } else {
1042
-                        $value = $this->_exportDateTime($value);
1043
-                    }
1044
-                } else {
1045
-                    $value = $this->_exportDateTime($value);
1046
-                }
1047
-                break;
1048
-
1049
-            // Comma or semicolon seperated dates.
1050
-            case 'EXDATE':
1051
-            case 'RDATE':
1052
-	            if (is_array($attribute['values'])) {
1053
-		            $values = $attribute['values'];
1054
-	            } elseif (!empty($value)) {
1055
-	            	if ($this->isOldFormat()) {
1056
-		            	$values = explode(';', $value);
1057
-	            	} else {
1058
-	            		$values = explode(',', $value);
1059
-	            	}
1060
-	            } else {
1061
-		            break;
1062
-	            }
1063
-                $dates = array();
1064
-                foreach ($values as $date) {
1065
-                    if (isset($params['VALUE'])) {
1066
-                        if ($params['VALUE'] == 'DATE') {
1067
-                            $dates[] = $this->_exportDate($date, '000000');
1068
-                        } elseif ($params['VALUE'] == 'PERIOD') {
1069
-                            $dates[] = $this->_exportPeriod($date);
1070
-                        } else {
1071
-                            $dates[] = $this->_exportDateTime($date);
1072
-                        }
1073
-                    } else {
1074
-                        $dates[] = $this->_exportDateTime($date);
1075
-                    }
1076
-                }
1077
-                if ($this->isOldFormat()) {
1078
-	                $value = implode(';', $dates);
1079
-                } else {
1080
-	                $value = implode(',', $dates);
1081
-                }
1082
-                break;
1083
-
1084
-            case 'TRIGGER':
1085
-                if (isset($params['VALUE'])) {
1086
-                    if ($params['VALUE'] == 'DATE-TIME') {
1087
-                        $value = $this->_exportDateTime($value);
1088
-                    } elseif ($params['VALUE'] == 'DURATION') {
1089
-                        $value = $this->_exportDuration($value);
1090
-                    }
1091
-                } else {
1092
-                    $value = $this->_exportDuration($value);
1093
-                }
1094
-                break;
1095
-
1096
-            // Duration fields.
1097
-            case 'DURATION':
1098
-                $value = $this->_exportDuration($value);
1099
-                break;
1100
-
1101
-            // Period of time fields.
1102
-            case 'FREEBUSY':
1103
-                $value_str = '';
1104
-                foreach ($value as $period) {
1105
-                    $value_str .= empty($value_str) ? '' : ',';
1106
-                    $value_str .= $this->_exportPeriod($period);
1107
-                }
1108
-                $value = $value_str;
1109
-                break;
1110
-
1111
-            // UTC offset fields.
1112
-            case 'TZOFFSETFROM':
1113
-            case 'TZOFFSETTO':
1114
-                $value = $this->_exportUtcOffset($value);
1115
-                break;
1116
-
1117
-            // Integer fields.
1118
-            case 'PERCENT-COMPLETE':
1119
-            case 'PRIORITY':
1120
-            case 'REPEAT':
1121
-            case 'SEQUENCE':
1122
-                $value = "$value";
1123
-                break;
1124
-
1125
-            // Geo fields.
1126
-            case 'GEO':
1127
-                if ($this->isOldFormat()) {
1128
-                    $value = $value['longitude'] . ',' . $value['latitude'];
1129
-                } else {
1130
-                    $value = $value['latitude'] . ';' . $value['longitude'];
1131
-                }
1132
-                break;
1133
-
1134
-            // Recurrence fields.
1135
-            case 'EXRULE':
1136
-            	break;
1137
-
1138
-            case 'RRULE':
1139
-                if (!empty($params_str) &&  $params_str[0] == ';')
1140
-                {
1141
-                	// The standard requires a double colon RRULE:...
1142
-                	 $params_str[0] = ':';
1143
-                }
1144
-                break;
1145
-
1146
-            case 'PHOTO':
1147
-                break;
1148
-
1149
-            default:
1150
-                if ($this->isOldFormat()) {
1151
-                    if (is_array($attribute['values']) &&
1152
-                        count($attribute['values']) > 1) {
1153
-                        $values = $attribute['values'];
1154
-                        if ($name == 'N' || $name == 'ADR' || $name == 'ORG') {
1155
-                            $glue = ';';
1156
-                        } else {
1157
-                            $glue = ',';
1158
-                        }
1159
-                        $values = str_replace(';', '\\;', $values);
1160
-                        $value = implode($glue, $values);
1161
-                    } else {
1162
-                        /* vcard 2.1 and vcalendar 1.0 escape only
982
+			case 'DALARM':
983
+				if (isset($params['VALUE'])) {
984
+					if ($params['VALUE'] == 'DATE') {
985
+						// VCALENDAR 1.0 uses T000000 - T235959 for all day events:
986
+						if ($this->isOldFormat() && $name == 'DTEND') {
987
+							$d = new Horde_Date($value);
988
+							$value = new Horde_Date(array(
989
+								'year' => $d->year,
990
+								'month' => $d->month,
991
+								'mday' => $d->mday - 1));
992
+							$value->correct();
993
+							$value = $this->_exportDate($value, '235959');
994
+						} else {
995
+							$value = $this->_exportDate($value, '000000');
996
+						}
997
+					} else {
998
+						$value = $this->_exportDateTime($value);
999
+					}
1000
+				} else {
1001
+					$value = $this->_exportDateTime($value);
1002
+				}
1003
+
1004
+				if (is_array($attribute['values']) &&
1005
+						count($attribute['values']) > 0) {
1006
+					$values = $attribute['values'];
1007
+					if ($this->isOldFormat()) {
1008
+						$values = str_replace(';', '\\;', $values);
1009
+					} else {
1010
+						// As of rfc 2426 2.5 semicolon and comma must be
1011
+						// escaped.
1012
+						$values = str_replace(array('\\', ';', ','),
1013
+											  array('\\\\', '\\;', '\\,'),
1014
+											  $values);
1015
+					}
1016
+					$value .= ';' . implode(';', $values);
1017
+				 }
1018
+
1019
+				break;
1020
+
1021
+			case 'DTEND':
1022
+			case 'DTSTART':
1023
+			case 'DTSTAMP':
1024
+			case 'DUE':
1025
+			case 'RECURRENCE-ID':
1026
+			case 'X-RECURRENCE-ID':
1027
+				if (isset($params['VALUE'])) {
1028
+					if ($params['VALUE'] == 'DATE') {
1029
+						// VCALENDAR 1.0 uses T000000 - T235959 for all day events:
1030
+						if ($this->isOldFormat() && $name == 'DTEND') {
1031
+							$d = new Horde_Date($value);
1032
+							$value = new Horde_Date(array(
1033
+								'year' => $d->year,
1034
+								'month' => $d->month,
1035
+								'mday' => $d->mday - 1));
1036
+							$value->correct();
1037
+							$value = $this->_exportDate($value, '235959');
1038
+						} else {
1039
+							$value = $this->_exportDate($value, '000000');
1040
+						}
1041
+					} else {
1042
+						$value = $this->_exportDateTime($value);
1043
+					}
1044
+				} else {
1045
+					$value = $this->_exportDateTime($value);
1046
+				}
1047
+				break;
1048
+
1049
+			// Comma or semicolon seperated dates.
1050
+			case 'EXDATE':
1051
+			case 'RDATE':
1052
+				if (is_array($attribute['values'])) {
1053
+					$values = $attribute['values'];
1054
+				} elseif (!empty($value)) {
1055
+					if ($this->isOldFormat()) {
1056
+						$values = explode(';', $value);
1057
+					} else {
1058
+						$values = explode(',', $value);
1059
+					}
1060
+				} else {
1061
+					break;
1062
+				}
1063
+				$dates = array();
1064
+				foreach ($values as $date) {
1065
+					if (isset($params['VALUE'])) {
1066
+						if ($params['VALUE'] == 'DATE') {
1067
+							$dates[] = $this->_exportDate($date, '000000');
1068
+						} elseif ($params['VALUE'] == 'PERIOD') {
1069
+							$dates[] = $this->_exportPeriod($date);
1070
+						} else {
1071
+							$dates[] = $this->_exportDateTime($date);
1072
+						}
1073
+					} else {
1074
+						$dates[] = $this->_exportDateTime($date);
1075
+					}
1076
+				}
1077
+				if ($this->isOldFormat()) {
1078
+					$value = implode(';', $dates);
1079
+				} else {
1080
+					$value = implode(',', $dates);
1081
+				}
1082
+				break;
1083
+
1084
+			case 'TRIGGER':
1085
+				if (isset($params['VALUE'])) {
1086
+					if ($params['VALUE'] == 'DATE-TIME') {
1087
+						$value = $this->_exportDateTime($value);
1088
+					} elseif ($params['VALUE'] == 'DURATION') {
1089
+						$value = $this->_exportDuration($value);
1090
+					}
1091
+				} else {
1092
+					$value = $this->_exportDuration($value);
1093
+				}
1094
+				break;
1095
+
1096
+			// Duration fields.
1097
+			case 'DURATION':
1098
+				$value = $this->_exportDuration($value);
1099
+				break;
1100
+
1101
+			// Period of time fields.
1102
+			case 'FREEBUSY':
1103
+				$value_str = '';
1104
+				foreach ($value as $period) {
1105
+					$value_str .= empty($value_str) ? '' : ',';
1106
+					$value_str .= $this->_exportPeriod($period);
1107
+				}
1108
+				$value = $value_str;
1109
+				break;
1110
+
1111
+			// UTC offset fields.
1112
+			case 'TZOFFSETFROM':
1113
+			case 'TZOFFSETTO':
1114
+				$value = $this->_exportUtcOffset($value);
1115
+				break;
1116
+
1117
+			// Integer fields.
1118
+			case 'PERCENT-COMPLETE':
1119
+			case 'PRIORITY':
1120
+			case 'REPEAT':
1121
+			case 'SEQUENCE':
1122
+				$value = "$value";
1123
+				break;
1124
+
1125
+			// Geo fields.
1126
+			case 'GEO':
1127
+				if ($this->isOldFormat()) {
1128
+					$value = $value['longitude'] . ',' . $value['latitude'];
1129
+				} else {
1130
+					$value = $value['latitude'] . ';' . $value['longitude'];
1131
+				}
1132
+				break;
1133
+
1134
+			// Recurrence fields.
1135
+			case 'EXRULE':
1136
+				break;
1137
+
1138
+			case 'RRULE':
1139
+				if (!empty($params_str) &&  $params_str[0] == ';')
1140
+				{
1141
+					// The standard requires a double colon RRULE:...
1142
+					 $params_str[0] = ':';
1143
+				}
1144
+				break;
1145
+
1146
+			case 'PHOTO':
1147
+				break;
1148
+
1149
+			default:
1150
+				if ($this->isOldFormat()) {
1151
+					if (is_array($attribute['values']) &&
1152
+						count($attribute['values']) > 1) {
1153
+						$values = $attribute['values'];
1154
+						if ($name == 'N' || $name == 'ADR' || $name == 'ORG') {
1155
+							$glue = ';';
1156
+						} else {
1157
+							$glue = ',';
1158
+						}
1159
+						$values = str_replace(';', '\\;', $values);
1160
+						$value = implode($glue, $values);
1161
+					} else {
1162
+						/* vcard 2.1 and vcalendar 1.0 escape only
1163 1163
                          * semicolons */
1164
-                        $value = str_replace(';', '\\;', $value);
1165
-                    }
1166
-                    // Text containing newlines or ASCII >= 127 must be BASE64
1167
-                    // or QUOTED-PRINTABLE encoded. Currently we use
1168
-                    // QUOTED-PRINTABLE as default.
1169
-                    if (preg_match('/[^\x20-\x7F]/', $value) &&
1170
-		                    !isset($params['ENCODING']))  {
1171
-	                    $params['ENCODING'] = 'QUOTED-PRINTABLE';
1172
-                    }
1173
-                    if (preg_match('/([\177-\377])/', $value) &&
1174
-		                    !isset($params['CHARSET'])) {
1175
-	                    // Add CHARSET as well. At least the synthesis client
1176
-	                    // gets confused otherwise
1177
-	                    $params['CHARSET'] = String::upper($charset);
1178
-	                    $params_str .= ';CHARSET=' . $params['CHARSET'];
1179
-                    }
1180
-                } else {
1181
-                    if (is_array($attribute['values']) &&
1182
-                        count($attribute['values']) > 1) {
1183
-                        $values = $attribute['values'];
1184
-                        if ($name == 'N' || $name == 'ADR' || $name == 'ORG') {
1185
-                            $glue = ';';
1186
-                        } else {
1187
-                            $glue = ',';
1188
-                        }
1189
-                        // As of rfc 2426 2.5 semicolon and comma must be
1190
-                        // escaped.
1191
-                        $values = str_replace(array('\\', ';', ','),
1192
-                                              array('\\\\', '\\;', '\\,'),
1193
-                                              $values);
1194
-                        $value = implode($glue, $values);
1195
-                    } else {
1196
-                        // As of rfc 2426 2.5 semicolon and comma must be
1197
-                        // escaped.
1198
-                        $value = str_replace(array('\\', ';', ','),
1199
-                                             array('\\\\', '\\;', '\\,'),
1200
-                                             $value);
1201
-                    }
1202
-                    $value = preg_replace('/\r?\n/', "\n", $value);
1203
-                }
1204
-            }
1164
+						$value = str_replace(';', '\\;', $value);
1165
+					}
1166
+					// Text containing newlines or ASCII >= 127 must be BASE64
1167
+					// or QUOTED-PRINTABLE encoded. Currently we use
1168
+					// QUOTED-PRINTABLE as default.
1169
+					if (preg_match('/[^\x20-\x7F]/', $value) &&
1170
+							!isset($params['ENCODING']))  {
1171
+						$params['ENCODING'] = 'QUOTED-PRINTABLE';
1172
+					}
1173
+					if (preg_match('/([\177-\377])/', $value) &&
1174
+							!isset($params['CHARSET'])) {
1175
+						// Add CHARSET as well. At least the synthesis client
1176
+						// gets confused otherwise
1177
+						$params['CHARSET'] = String::upper($charset);
1178
+						$params_str .= ';CHARSET=' . $params['CHARSET'];
1179
+					}
1180
+				} else {
1181
+					if (is_array($attribute['values']) &&
1182
+						count($attribute['values']) > 1) {
1183
+						$values = $attribute['values'];
1184
+						if ($name == 'N' || $name == 'ADR' || $name == 'ORG') {
1185
+							$glue = ';';
1186
+						} else {
1187
+							$glue = ',';
1188
+						}
1189
+						// As of rfc 2426 2.5 semicolon and comma must be
1190
+						// escaped.
1191
+						$values = str_replace(array('\\', ';', ','),
1192
+											  array('\\\\', '\\;', '\\,'),
1193
+											  $values);
1194
+						$value = implode($glue, $values);
1195
+					} else {
1196
+						// As of rfc 2426 2.5 semicolon and comma must be
1197
+						// escaped.
1198
+						$value = str_replace(array('\\', ';', ','),
1199
+											 array('\\\\', '\\;', '\\,'),
1200
+											 $value);
1201
+					}
1202
+					$value = preg_replace('/\r?\n/', "\n", $value);
1203
+				}
1204
+			}
1205 1205
 
1206 1206
 			$encoding = (!empty($params['ENCODING']) && strlen(trim($value)) > 0);
1207 1207
 
1208
-            if ($encoding) {
1209
-	            switch($params['ENCODING']) {
1210
-		            case 'Q':
1211
-		            case 'QUOTED-PRINTABLE':
1212
-		            	if (!$this->isOldFormat())
1213
-		            	{
1214
-		            		$encoding = false;
1215
-		            		break;
1216
-		            	}
1217
-			            $params_str .= ';ENCODING=' . $params['ENCODING'];
1218
-			            $value = str_replace("\r", '', $value);
1219
-			            $result .= $name . $params_str . ':'
1220
-				            . str_replace('=0A', '=0D=0A',
1221
-					            $this->_quotedPrintableEncode($value))
1208
+			if ($encoding) {
1209
+				switch($params['ENCODING']) {
1210
+					case 'Q':
1211
+					case 'QUOTED-PRINTABLE':
1212
+						if (!$this->isOldFormat())
1213
+						{
1214
+							$encoding = false;
1215
+							break;
1216
+						}
1217
+						$params_str .= ';ENCODING=' . $params['ENCODING'];
1218
+						$value = str_replace("\r", '', $value);
1219
+						$result .= $name . $params_str . ':'
1220
+							. str_replace('=0A', '=0D=0A',
1221
+								$this->_quotedPrintableEncode($value))
1222 1222
 								. $this->_newline;
1223
-			            break;
1224
-		            case 'FUNAMBOL-QP':
1225
-		            	// Funambol needs some special quoting
1226
-			            $value = str_replace(array('<', "\r"), array('&lt;', ''), $value);
1227
-			            if (!$this->isOldFormat())
1228
-			            {
1229
-			            	$encoding = false;
1230
-			            	break;
1231
-			            }
1232
-			            $params_str .= ';ENCODING=QUOTED-PRINTABLE';
1233
-			            $result .= $name . $params_str . ':'
1234
-				            . str_replace('=0A', '=0D=0A',
1235
-					            $this->_quotedPrintableEncode($value, false))
1223
+						break;
1224
+					case 'FUNAMBOL-QP':
1225
+						// Funambol needs some special quoting
1226
+						$value = str_replace(array('<', "\r"), array('&lt;', ''), $value);
1227
+						if (!$this->isOldFormat())
1228
+						{
1229
+							$encoding = false;
1230
+							break;
1231
+						}
1232
+						$params_str .= ';ENCODING=QUOTED-PRINTABLE';
1233
+						$result .= $name . $params_str . ':'
1234
+							. str_replace('=0A', '=0D=0A',
1235
+								$this->_quotedPrintableEncode($value, false))
1236 1236
 								. $this->_newline;
1237
-			            break;
1238
-		            case 'B':
1239
-		            case 'BASE64':
1240
-			            $params_str .= ';ENCODING=' . $params['ENCODING'];
1241
-			            // using native php wordwrap to speed up encoding of images
1242
-			            $result .= wordwrap($name . $params_str . ':' . $this->_newline . ' ' .
1243
-			            	$this->_base64Encode($value),75,$this->_newline . ' ',true) . $this->_newline;
1244
-			            /*
1237
+						break;
1238
+					case 'B':
1239
+					case 'BASE64':
1240
+						$params_str .= ';ENCODING=' . $params['ENCODING'];
1241
+						// using native php wordwrap to speed up encoding of images
1242
+						$result .= wordwrap($name . $params_str . ':' . $this->_newline . ' ' .
1243
+							$this->_base64Encode($value),75,$this->_newline . ' ',true) . $this->_newline;
1244
+						/*
1245 1245
 			            $attr_string = $name . $params_str . ':' . $this->_newline . ' ' . $this->_base64Encode($value);
1246 1246
 			            $attr_string = String::wordwrap($attr_string, 75, $this->_newline . ' ',
1247 1247
 				            true, 'utf-8', true); // charset does not matter
1248 1248
 			            $result .= $attr_string . $this->_newline;
1249 1249
 			            */
1250
-			            if ($this->isOldFormat()) {
1251
-				            $result .= $this->_newline; // Append an empty line
1252
-			            }
1253
-	            }
1254
-            }
1255
-
1256
-            if (!$encoding) {
1257
-                $value = str_replace(array("\r", "\n"), array('', '\\n'), $value);
1258
-                $attr_string = $name . $params_str;
1259
-                if (strlen($value) > 0) {
1260
-                	$attr_string .= ':' . $value;
1261
-                } elseif ($name != 'RRULE') {
1262
-                	$attr_string .= ':';
1263
-                }
1264
-                if (!$this->isOldFormat()) {
1265
-                    $attr_string = String::wordwrap($attr_string, 75, $this->_newline . ' ',
1266
-                                                    true, $charset, true);
1267
-                }
1268
-                $result .= $attr_string . $this->_newline;
1269
-            }
1270
-        }
1271
-
1272
-        foreach ($this->_components as $component) {
1273
-            if ($this->isOldFormat() &&  $component->getType() == 'vTimeZone') {
1274
-    			// Not supported
1250
+						if ($this->isOldFormat()) {
1251
+							$result .= $this->_newline; // Append an empty line
1252
+						}
1253
+				}
1254
+			}
1255
+
1256
+			if (!$encoding) {
1257
+				$value = str_replace(array("\r", "\n"), array('', '\\n'), $value);
1258
+				$attr_string = $name . $params_str;
1259
+				if (strlen($value) > 0) {
1260
+					$attr_string .= ':' . $value;
1261
+				} elseif ($name != 'RRULE') {
1262
+					$attr_string .= ':';
1263
+				}
1264
+				if (!$this->isOldFormat()) {
1265
+					$attr_string = String::wordwrap($attr_string, 75, $this->_newline . ' ',
1266
+													true, $charset, true);
1267
+				}
1268
+				$result .= $attr_string . $this->_newline;
1269
+			}
1270
+		}
1271
+
1272
+		foreach ($this->_components as $component) {
1273
+			if ($this->isOldFormat() &&  $component->getType() == 'vTimeZone') {
1274
+				// Not supported
1275 1275
 				continue;
1276
-        	}
1277
-            $result .= $component->exportvCalendar($charset);
1278
-        }
1279
-
1280
-        return $result . 'END:' . $base . $this->_newline;
1281
-    }
1282
-
1283
-    /**
1284
-     * Parse a UTC Offset field.
1285
-     */
1286
-    function _parseUtcOffset($text)
1287
-    {
1288
-        $offset = array();
1289
-        if (preg_match('/(\+|-)([0-9]{2})([0-9]{2})([0-9]{2})?/', $text, $timeParts)) {
1290
-            $offset['ahead']  = (bool)($timeParts[1] == '+');
1291
-            $offset['hour']   = intval($timeParts[2]);
1292
-            $offset['minute'] = intval($timeParts[3]);
1293
-            if (isset($timeParts[4])) {
1294
-                $offset['second'] = intval($timeParts[4]);
1295
-            }
1296
-            return $offset;
1297
-        } else {
1298
-            return false;
1299
-        }
1300
-    }
1301
-
1302
-    /**
1303
-     * Export a UTC Offset field.
1304
-     */
1305
-    function _exportUtcOffset($value)
1306
-    {
1307
-        $offset = $value['ahead'] ? '+' : '-';
1308
-        $offset .= sprintf('%02d%02d',
1309
-                           $value['hour'], $value['minute']);
1310
-        if (isset($value['second'])) {
1311
-            $offset .= sprintf('%02d', $value['second']);
1312
-        }
1313
-
1314
-        return $offset;
1315
-    }
1316
-
1317
-    /**
1318
-     * Parse a Time Period field.
1319
-     */
1320
-    function _parsePeriod($text)
1321
-    {
1322
-        $periodParts = explode('/', $text);
1323
-
1324
-        $start = $this->_parseDateTime($periodParts[0]);
1325
-
1326
-        if ($duration = $this->_parseDuration($periodParts[1])) {
1327
-            return array('start' => $start, 'duration' => $duration);
1328
-        } elseif ($end = $this->_parseDateTime($periodParts[1])) {
1329
-            return array('start' => $start, 'end' => $end);
1330
-        }
1331
-    }
1332
-
1333
-    /**
1334
-     * Export a Time Period field.
1335
-     */
1336
-    function _exportPeriod($value)
1337
-    {
1338
-        $period = $this->_exportDateTime($value['start']);
1339
-        $period .= '/';
1340
-        if (isset($value['duration'])) {
1341
-            $period .= $this->_exportDuration($value['duration']);
1342
-        } else {
1343
-            $period .= $this->_exportDateTime($value['end']);
1344
-        }
1345
-        return $period;
1346
-    }
1347
-
1348
-    /**
1349
-     * Grok the TZID and return an offset in seconds from UTC for this
1350
-     * date and time.
1351
-     */
1352
-    function _parseTZID($date, $time, $tzid)
1353
-    {
1354
-        $vtimezone = $this->_container->findComponentByAttribute('vtimezone', 'TZID', $tzid);
1355
-        if (!$vtimezone) {
1356
-            return false;
1357
-        }
1358
-
1359
-        $change_times = array();
1360
-        foreach ($vtimezone->getComponents() as $o) {
1361
-            $t = $vtimezone->parseChild($o, $date['year']);
1362
-            if ($t !== false) {
1363
-                $change_times[] = $t;
1364
-            }
1365
-        }
1366
-
1367
-        if (!$change_times) {
1368
-            return false;
1369
-        }
1370
-
1371
-        sort($change_times);
1372
-
1373
-        // Time is arbitrarily based on UTC for comparison.
1374
-        $t = @gmmktime($time['hour'], $time['minute'], $time['second'],
1375
-                       $date['month'], $date['mday'], $date['year']);
1376
-
1377
-        if ($t < $change_times[0]['time']) {
1378
-            return $change_times[0]['from'];
1379
-        }
1380
-
1381
-        for ($i = 0, $n = count($change_times); $i < $n - 1; $i++) {
1382
-            if (($t >= $change_times[$i]['time']) &&
1383
-                ($t < $change_times[$i + 1]['time'])) {
1384
-                return $change_times[$i]['to'];
1385
-            }
1386
-        }
1387
-
1388
-        if ($t >= $change_times[$n - 1]['time']) {
1389
-            return $change_times[$n - 1]['to'];
1390
-        }
1391
-
1392
-        return false;
1393
-    }
1394
-
1395
-    /**
1396
-     * Parses a DateTime field and returns a unix timestamp. If the
1397
-     * field cannot be parsed then the original text is returned
1398
-     * unmodified.
1399
-     *
1400
-     * @todo This function should be moved to Horde_Date and made public.
1401
-     */
1402
-    function _parseDateTime($text, $tzid = false)
1403
-    {
1404
-        $dateParts = explode('T', $text);
1405
-        if (count($dateParts) != 2 && !empty($text)) {
1406
-            // Not a datetime field but may be just a date field.
1407
-            if (!preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $text, $match)) {
1408
-                // Or not
1409
-                return $text;
1410
-            }
1411
-            $newtext = $text.'T000000';
1412
-            $dateParts = explode('T', $newtext);
1413
-        }
1414
-
1415
-        if (!$date = Horde_iCalendar::_parseDate($dateParts[0])) {
1416
-            return $text;
1417
-        }
1418
-        if (!$time = Horde_iCalendar::_parseTime($dateParts[1])) {
1419
-            return $text;
1420
-        }
1421
-
1422
-        // Get timezone info for date fields from $tzid and container.
1423
-        $tzoffset = ($time['zone'] == 'Local' && $tzid && is_a($this->_container, 'Horde_iCalendar'))
1424
-            ? $this->_parseTZID($date, $time, $tzid) : false;
1425
-        if ($time['zone'] == 'UTC' || $tzoffset !== false) {
1426
-            $result = @gmmktime($time['hour'], $time['minute'], $time['second'],
1427
-                                $date['month'], $date['mday'], $date['year']);
1428
-            if ($tzoffset) {
1429
-                $result -= $tzoffset;
1430
-            }
1431
-        } else {
1432
-            // We don't know the timezone so assume local timezone.
1433
-            // FIXME: shouldn't this be based on the user's timezone
1434
-            // preference rather than the server's timezone?
1435
-            $result = @mktime($time['hour'], $time['minute'], $time['second'],
1436
-                              $date['month'], $date['mday'], $date['year']);
1437
-        }
1438
-
1439
-        return ($result !== false) ? $result : $text;
1440
-    }
1441
-
1442
-    /**
1443
-     * Export a DateTime field.
1444
-     */
1445
-    function _exportDateTime($value)
1446
-    {
1447
-        if (is_numeric($value)) {
1448
-            $temp = array();
1449
-            $tz = date('O', $value);
1450
-            $TZOffset = (3600 * substr($tz, 0, 3)) + (60 * substr(date('O', $value), 3, 2));
1451
-            $value -= $TZOffset;
1452
-
1453
-            $temp['zone']   = 'UTC';
1454
-            $temp['year']   = date('Y', $value);
1455
-            $temp['month']  = date('n', $value);
1456
-            $temp['mday']   = date('j', $value);
1457
-            $temp['hour']   = date('G', $value);
1458
-            $temp['minute'] = date('i', $value);
1459
-            $temp['second'] = date('s', $value);
1460
-            return Horde_iCalendar::_exportDate($temp) . 'T' . Horde_iCalendar::_exportTime($temp);
1461
-        } else if (is_object($value) || is_array($value)) {
1462
-            $dateOb = new Horde_Date($value);
1463
-            return Horde_iCalendar::_exportDateTime($dateOb->timestamp());
1464
-        }
1465
-        return $value; // nothing to do with us, let's not touch it
1466
-    }
1467
-
1468
-    /**
1469
-     * Parses a Time field.
1470
-     *
1471
-     * @static
1472
-     */
1473
-    function _parseTime($text)
1474
-    {
1475
-        if (preg_match('/([0-9]{2})([0-9]{2})([0-9]{2})(Z)?/', $text, $timeParts)) {
1476
-            $time['hour'] = intval($timeParts[1]);
1477
-            $time['minute'] = intval($timeParts[2]);
1478
-            $time['second'] = intval($timeParts[3]);
1479
-            if (isset($timeParts[4])) {
1480
-                $time['zone'] = 'UTC';
1481
-            } else {
1482
-                $time['zone'] = 'Local';
1483
-            }
1484
-            return $time;
1485
-        } else {
1486
-            return false;
1487
-        }
1488
-    }
1489
-
1490
-    /**
1491
-     * Exports a Time field.
1492
-     */
1493
-    function _exportTime($value)
1494
-    {
1495
-        $time = sprintf('%02d%02d%02d',
1496
-                        $value['hour'], $value['minute'], $value['second']);
1497
-        if ($value['zone'] == 'UTC') {
1498
-            $time .= 'Z';
1499
-        }
1500
-        return $time;
1501
-    }
1502
-
1503
-    /**
1504
-     * Parses a Date field.
1505
-     *
1506
-     * @static
1507
-     */
1508
-    function _parseDate($text)
1509
-    {
1510
-        $parts = explode('T', $text);
1511
-        if (count($parts) == 2) {
1512
-            $text = $parts[0];
1513
-        }
1514
-
1515
-        if (!preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $text, $match)) {
1516
-            return false;
1517
-        }
1518
-
1519
-        return array('year' => $match[1],
1520
-                     'month' => $match[2],
1521
-                     'mday' => $match[3]);
1522
-    }
1523
-
1524
-    /**
1525
-     * Exports a date field.
1526
-     *
1527
-     * @param object|array $value  Date object or hash.
1528
-     * @param string $autoconvert  If set, use this as time part to export the
1529
-     *                             date as datetime when exporting to Vcalendar
1530
-     *                             1.0. Examples: '000000' or '235959'
1531
-     */
1532
-    function _exportDate($value, $autoconvert = false)
1533
-    {
1534
-        if (is_object($value)) {
1535
-            $value = array('year' => $value->year, 'month' => $value->month, 'mday' => $value->mday);
1536
-        }
1537
-        if ($autoconvert !== false && $this->isOldFormat()) {
1538
-            return sprintf('%04d%02d%02dT%s', $value['year'], $value['month'], $value['mday'], $autoconvert);
1539
-        } else {
1540
-            return sprintf('%04d%02d%02d', $value['year'], $value['month'], $value['mday']);
1541
-        }
1542
-    }
1543
-
1544
-    /**
1545
-     * Parse a Duration Value field.
1546
-     */
1547
-    function _parseDuration($text)
1548
-    {
1549
-        if (preg_match('/([+]?|[-])P(([0-9]+W)|([0-9]+D)|)(T(([0-9]+H)|([0-9]+M)|([0-9]+S))+)?/', trim($text), $durvalue)) {
1550
-            // Weeks.
1551
-            $duration = 7 * 86400 * intval($durvalue[3]);
1552
-
1553
-            if (count($durvalue) > 4) {
1554
-                // Days.
1555
-                $duration += 86400 * intval($durvalue[4]);
1556
-            }
1557
-            if (count($durvalue) > 5) {
1558
-                // Hours.
1559
-                $duration += 3600 * intval($durvalue[7]);
1560
-
1561
-                // Mins.
1562
-                if (isset($durvalue[8])) {
1563
-                    $duration += 60 * intval($durvalue[8]);
1564
-                }
1565
-
1566
-                // Secs.
1567
-                if (isset($durvalue[9])) {
1568
-                    $duration += intval($durvalue[9]);
1569
-                }
1570
-            }
1571
-
1572
-            // Sign.
1573
-            if ($durvalue[1] == "-") {
1574
-                $duration *= -1;
1575
-            }
1576
-
1577
-            return $duration;
1578
-        } else {
1579
-            return false;
1580
-        }
1581
-    }
1582
-
1583
-    /**
1584
-     * Export a duration value.
1585
-     */
1586
-    function _exportDuration($value)
1587
-    {
1588
-        $duration = '';
1589
-        if ($value < 0) {
1590
-            $value *= -1;
1591
-            $duration .= '-';
1592
-        }
1593
-        $duration .= 'P';
1594
-
1595
-        $weeks = floor($value / (7 * 86400));
1596
-        $value = $value % (7 * 86400);
1597
-        if ($weeks) {
1598
-            $duration .= $weeks . 'W';
1599
-        }
1600
-
1601
-        $days = floor($value / (86400));
1602
-        $value = $value % (86400);
1603
-        if ($days) {
1604
-            $duration .= $days . 'D';
1605
-        }
1606
-
1607
-        if ($value) {
1608
-            $duration .= 'T';
1609
-
1610
-            $hours = floor($value / 3600);
1611
-            $value = $value % 3600;
1612
-            if ($hours) {
1613
-                $duration .= $hours . 'H';
1614
-            }
1615
-
1616
-            $mins = floor($value / 60);
1617
-            $value = $value % 60;
1618
-            if ($mins) {
1619
-                $duration .= $mins . 'M';
1620
-            }
1621
-
1622
-            if ($value) {
1623
-                $duration .= $value . 'S';
1624
-            }
1625
-        }
1276
+			}
1277
+			$result .= $component->exportvCalendar($charset);
1278
+		}
1279
+
1280
+		return $result . 'END:' . $base . $this->_newline;
1281
+	}
1282
+
1283
+	/**
1284
+	 * Parse a UTC Offset field.
1285
+	 */
1286
+	function _parseUtcOffset($text)
1287
+	{
1288
+		$offset = array();
1289
+		if (preg_match('/(\+|-)([0-9]{2})([0-9]{2})([0-9]{2})?/', $text, $timeParts)) {
1290
+			$offset['ahead']  = (bool)($timeParts[1] == '+');
1291
+			$offset['hour']   = intval($timeParts[2]);
1292
+			$offset['minute'] = intval($timeParts[3]);
1293
+			if (isset($timeParts[4])) {
1294
+				$offset['second'] = intval($timeParts[4]);
1295
+			}
1296
+			return $offset;
1297
+		} else {
1298
+			return false;
1299
+		}
1300
+	}
1301
+
1302
+	/**
1303
+	 * Export a UTC Offset field.
1304
+	 */
1305
+	function _exportUtcOffset($value)
1306
+	{
1307
+		$offset = $value['ahead'] ? '+' : '-';
1308
+		$offset .= sprintf('%02d%02d',
1309
+						   $value['hour'], $value['minute']);
1310
+		if (isset($value['second'])) {
1311
+			$offset .= sprintf('%02d', $value['second']);
1312
+		}
1313
+
1314
+		return $offset;
1315
+	}
1316
+
1317
+	/**
1318
+	 * Parse a Time Period field.
1319
+	 */
1320
+	function _parsePeriod($text)
1321
+	{
1322
+		$periodParts = explode('/', $text);
1323
+
1324
+		$start = $this->_parseDateTime($periodParts[0]);
1325
+
1326
+		if ($duration = $this->_parseDuration($periodParts[1])) {
1327
+			return array('start' => $start, 'duration' => $duration);
1328
+		} elseif ($end = $this->_parseDateTime($periodParts[1])) {
1329
+			return array('start' => $start, 'end' => $end);
1330
+		}
1331
+	}
1332
+
1333
+	/**
1334
+	 * Export a Time Period field.
1335
+	 */
1336
+	function _exportPeriod($value)
1337
+	{
1338
+		$period = $this->_exportDateTime($value['start']);
1339
+		$period .= '/';
1340
+		if (isset($value['duration'])) {
1341
+			$period .= $this->_exportDuration($value['duration']);
1342
+		} else {
1343
+			$period .= $this->_exportDateTime($value['end']);
1344
+		}
1345
+		return $period;
1346
+	}
1347
+
1348
+	/**
1349
+	 * Grok the TZID and return an offset in seconds from UTC for this
1350
+	 * date and time.
1351
+	 */
1352
+	function _parseTZID($date, $time, $tzid)
1353
+	{
1354
+		$vtimezone = $this->_container->findComponentByAttribute('vtimezone', 'TZID', $tzid);
1355
+		if (!$vtimezone) {
1356
+			return false;
1357
+		}
1358
+
1359
+		$change_times = array();
1360
+		foreach ($vtimezone->getComponents() as $o) {
1361
+			$t = $vtimezone->parseChild($o, $date['year']);
1362
+			if ($t !== false) {
1363
+				$change_times[] = $t;
1364
+			}
1365
+		}
1366
+
1367
+		if (!$change_times) {
1368
+			return false;
1369
+		}
1370
+
1371
+		sort($change_times);
1372
+
1373
+		// Time is arbitrarily based on UTC for comparison.
1374
+		$t = @gmmktime($time['hour'], $time['minute'], $time['second'],
1375
+					   $date['month'], $date['mday'], $date['year']);
1376
+
1377
+		if ($t < $change_times[0]['time']) {
1378
+			return $change_times[0]['from'];
1379
+		}
1380
+
1381
+		for ($i = 0, $n = count($change_times); $i < $n - 1; $i++) {
1382
+			if (($t >= $change_times[$i]['time']) &&
1383
+				($t < $change_times[$i + 1]['time'])) {
1384
+				return $change_times[$i]['to'];
1385
+			}
1386
+		}
1387
+
1388
+		if ($t >= $change_times[$n - 1]['time']) {
1389
+			return $change_times[$n - 1]['to'];
1390
+		}
1391
+
1392
+		return false;
1393
+	}
1394
+
1395
+	/**
1396
+	 * Parses a DateTime field and returns a unix timestamp. If the
1397
+	 * field cannot be parsed then the original text is returned
1398
+	 * unmodified.
1399
+	 *
1400
+	 * @todo This function should be moved to Horde_Date and made public.
1401
+	 */
1402
+	function _parseDateTime($text, $tzid = false)
1403
+	{
1404
+		$dateParts = explode('T', $text);
1405
+		if (count($dateParts) != 2 && !empty($text)) {
1406
+			// Not a datetime field but may be just a date field.
1407
+			if (!preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $text, $match)) {
1408
+				// Or not
1409
+				return $text;
1410
+			}
1411
+			$newtext = $text.'T000000';
1412
+			$dateParts = explode('T', $newtext);
1413
+		}
1414
+
1415
+		if (!$date = Horde_iCalendar::_parseDate($dateParts[0])) {
1416
+			return $text;
1417
+		}
1418
+		if (!$time = Horde_iCalendar::_parseTime($dateParts[1])) {
1419
+			return $text;
1420
+		}
1421
+
1422
+		// Get timezone info for date fields from $tzid and container.
1423
+		$tzoffset = ($time['zone'] == 'Local' && $tzid && is_a($this->_container, 'Horde_iCalendar'))
1424
+			? $this->_parseTZID($date, $time, $tzid) : false;
1425
+		if ($time['zone'] == 'UTC' || $tzoffset !== false) {
1426
+			$result = @gmmktime($time['hour'], $time['minute'], $time['second'],
1427
+								$date['month'], $date['mday'], $date['year']);
1428
+			if ($tzoffset) {
1429
+				$result -= $tzoffset;
1430
+			}
1431
+		} else {
1432
+			// We don't know the timezone so assume local timezone.
1433
+			// FIXME: shouldn't this be based on the user's timezone
1434
+			// preference rather than the server's timezone?
1435
+			$result = @mktime($time['hour'], $time['minute'], $time['second'],
1436
+							  $date['month'], $date['mday'], $date['year']);
1437
+		}
1438
+
1439
+		return ($result !== false) ? $result : $text;
1440
+	}
1441
+
1442
+	/**
1443
+	 * Export a DateTime field.
1444
+	 */
1445
+	function _exportDateTime($value)
1446
+	{
1447
+		if (is_numeric($value)) {
1448
+			$temp = array();
1449
+			$tz = date('O', $value);
1450
+			$TZOffset = (3600 * substr($tz, 0, 3)) + (60 * substr(date('O', $value), 3, 2));
1451
+			$value -= $TZOffset;
1452
+
1453
+			$temp['zone']   = 'UTC';
1454
+			$temp['year']   = date('Y', $value);
1455
+			$temp['month']  = date('n', $value);
1456
+			$temp['mday']   = date('j', $value);
1457
+			$temp['hour']   = date('G', $value);
1458
+			$temp['minute'] = date('i', $value);
1459
+			$temp['second'] = date('s', $value);
1460
+			return Horde_iCalendar::_exportDate($temp) . 'T' . Horde_iCalendar::_exportTime($temp);
1461
+		} else if (is_object($value) || is_array($value)) {
1462
+			$dateOb = new Horde_Date($value);
1463
+			return Horde_iCalendar::_exportDateTime($dateOb->timestamp());
1464
+		}
1465
+		return $value; // nothing to do with us, let's not touch it
1466
+	}
1467
+
1468
+	/**
1469
+	 * Parses a Time field.
1470
+	 *
1471
+	 * @static
1472
+	 */
1473
+	function _parseTime($text)
1474
+	{
1475
+		if (preg_match('/([0-9]{2})([0-9]{2})([0-9]{2})(Z)?/', $text, $timeParts)) {
1476
+			$time['hour'] = intval($timeParts[1]);
1477
+			$time['minute'] = intval($timeParts[2]);
1478
+			$time['second'] = intval($timeParts[3]);
1479
+			if (isset($timeParts[4])) {
1480
+				$time['zone'] = 'UTC';
1481
+			} else {
1482
+				$time['zone'] = 'Local';
1483
+			}
1484
+			return $time;
1485
+		} else {
1486
+			return false;
1487
+		}
1488
+	}
1489
+
1490
+	/**
1491
+	 * Exports a Time field.
1492
+	 */
1493
+	function _exportTime($value)
1494
+	{
1495
+		$time = sprintf('%02d%02d%02d',
1496
+						$value['hour'], $value['minute'], $value['second']);
1497
+		if ($value['zone'] == 'UTC') {
1498
+			$time .= 'Z';
1499
+		}
1500
+		return $time;
1501
+	}
1502
+
1503
+	/**
1504
+	 * Parses a Date field.
1505
+	 *
1506
+	 * @static
1507
+	 */
1508
+	function _parseDate($text)
1509
+	{
1510
+		$parts = explode('T', $text);
1511
+		if (count($parts) == 2) {
1512
+			$text = $parts[0];
1513
+		}
1514
+
1515
+		if (!preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $text, $match)) {
1516
+			return false;
1517
+		}
1518
+
1519
+		return array('year' => $match[1],
1520
+					 'month' => $match[2],
1521
+					 'mday' => $match[3]);
1522
+	}
1523
+
1524
+	/**
1525
+	 * Exports a date field.
1526
+	 *
1527
+	 * @param object|array $value  Date object or hash.
1528
+	 * @param string $autoconvert  If set, use this as time part to export the
1529
+	 *                             date as datetime when exporting to Vcalendar
1530
+	 *                             1.0. Examples: '000000' or '235959'
1531
+	 */
1532
+	function _exportDate($value, $autoconvert = false)
1533
+	{
1534
+		if (is_object($value)) {
1535
+			$value = array('year' => $value->year, 'month' => $value->month, 'mday' => $value->mday);
1536
+		}
1537
+		if ($autoconvert !== false && $this->isOldFormat()) {
1538
+			return sprintf('%04d%02d%02dT%s', $value['year'], $value['month'], $value['mday'], $autoconvert);
1539
+		} else {
1540
+			return sprintf('%04d%02d%02d', $value['year'], $value['month'], $value['mday']);
1541
+		}
1542
+	}
1543
+
1544
+	/**
1545
+	 * Parse a Duration Value field.
1546
+	 */
1547
+	function _parseDuration($text)
1548
+	{
1549
+		if (preg_match('/([+]?|[-])P(([0-9]+W)|([0-9]+D)|)(T(([0-9]+H)|([0-9]+M)|([0-9]+S))+)?/', trim($text), $durvalue)) {
1550
+			// Weeks.
1551
+			$duration = 7 * 86400 * intval($durvalue[3]);
1552
+
1553
+			if (count($durvalue) > 4) {
1554
+				// Days.
1555
+				$duration += 86400 * intval($durvalue[4]);
1556
+			}
1557
+			if (count($durvalue) > 5) {
1558
+				// Hours.
1559
+				$duration += 3600 * intval($durvalue[7]);
1560
+
1561
+				// Mins.
1562
+				if (isset($durvalue[8])) {
1563
+					$duration += 60 * intval($durvalue[8]);
1564
+				}
1565
+
1566
+				// Secs.
1567
+				if (isset($durvalue[9])) {
1568
+					$duration += intval($durvalue[9]);
1569
+				}
1570
+			}
1571
+
1572
+			// Sign.
1573
+			if ($durvalue[1] == "-") {
1574
+				$duration *= -1;
1575
+			}
1576
+
1577
+			return $duration;
1578
+		} else {
1579
+			return false;
1580
+		}
1581
+	}
1582
+
1583
+	/**
1584
+	 * Export a duration value.
1585
+	 */
1586
+	function _exportDuration($value)
1587
+	{
1588
+		$duration = '';
1589
+		if ($value < 0) {
1590
+			$value *= -1;
1591
+			$duration .= '-';
1592
+		}
1593
+		$duration .= 'P';
1594
+
1595
+		$weeks = floor($value / (7 * 86400));
1596
+		$value = $value % (7 * 86400);
1597
+		if ($weeks) {
1598
+			$duration .= $weeks . 'W';
1599
+		}
1600
+
1601
+		$days = floor($value / (86400));
1602
+		$value = $value % (86400);
1603
+		if ($days) {
1604
+			$duration .= $days . 'D';
1605
+		}
1606
+
1607
+		if ($value) {
1608
+			$duration .= 'T';
1609
+
1610
+			$hours = floor($value / 3600);
1611
+			$value = $value % 3600;
1612
+			if ($hours) {
1613
+				$duration .= $hours . 'H';
1614
+			}
1615
+
1616
+			$mins = floor($value / 60);
1617
+			$value = $value % 60;
1618
+			if ($mins) {
1619
+				$duration .= $mins . 'M';
1620
+			}
1621
+
1622
+			if ($value) {
1623
+				$duration .= $value . 'S';
1624
+			}
1625
+		}
1626 1626
 		// duration without time ("P") is NOT valid, append 0 minutes ("T0M")
1627 1627
 		elseif ($duration === 'P')
1628 1628
 		{
1629 1629
 			$duration .= 'T0M';
1630 1630
 		}
1631 1631
 
1632
-        return $duration;
1633
-    }
1632
+		return $duration;
1633
+	}
1634 1634
 
1635 1635
 
1636 1636
    /**
1637
-     * Convert an 8bit string to a base64 string
1638
-     * to RFC2045, section 6.7.
1639
-     *
1640
-     * @param  string $input  The string to be encoded.
1641
-     *
1642
-     * @return string         The base64 encoded string.
1643
-     */
1644
-    function _base64Encode($input = '')
1645
-    {
1646
-        return base64_encode($input);
1647
-    }
1648
-
1649
-
1650
-    /**
1651
-     * Converts an 8bit string to a quoted-printable string according to RFC
1652
-     * 2045, section 6.7.
1653
-     *
1654
-     * imap_8bit() does not apply all necessary rules.
1655
-     *
1656
-     * @param string $input  The string to be encoded.
1657
-     *
1658
-     * @return string  The quoted-printable encoded string.
1659
-     */
1660
-    function _quotedPrintableEncode($input = '', $withFolding=true)
1661
-    {
1662
-        $output = $line = '';
1663
-        $len = bytes($input);
1664
-
1665
-        for ($i = 0; $i < $len; ++$i) {
1666
-            $ord = ord($input[$i]);
1667
-            // Encode non-printable characters (rule 2).
1668
-            if ($ord == 9 ||
1669
-                ($ord >= 32 && $ord <= 60) ||
1670
-                ($ord >= 62 && $ord <= 126)) {
1671
-                $chunk = $input[$i];
1672
-            } else {
1673
-                // Quoted printable encoding (rule 1).
1674
-                $chunk = '=' . String::upper(sprintf('%02X', $ord));
1675
-            }
1676
-            $line .= $chunk;
1677
-            // Wrap long lines (rule 5)
1678
-            if ($withFolding && strlen($line) + 1 > 76) {
1679
-                $line = String::wordwrap($line, 75, "=\r\n", true, 'us-ascii', true);
1680
-                $newline = strrchr($line, "\r\n");
1681
-                if ($newline !== false) {
1682
-                    $output .= substr($line, 0, -strlen($newline) + 2);
1683
-                    $line = substr($newline, 2);
1684
-                } else {
1685
-                    $output .= $line;
1686
-                }
1687
-                continue;
1688
-            }
1689
-            // Wrap at line breaks for better readability (rule 4).
1690
-            if ($withFolding && substr($line, -3) == '=0A') {
1691
-                $output .= $line . "=\r\n";
1692
-                $line = '';
1693
-            }
1694
-        }
1695
-        $output .= $line;
1696
-
1697
-        // Trailing whitespace must be encoded (rule 3).
1698
-        $lastpos = strlen($output) - 1;
1699
-        if ($output[$lastpos] == chr(9) ||
1700
-            $output[$lastpos] == chr(32)) {
1701
-            $output[$lastpos] = '=';
1702
-            $output .= String::upper(sprintf('%02X', ord($output[$lastpos])));
1703
-        }
1704
-
1705
-        return $output;
1706
-    }
1637
+    * Convert an 8bit string to a base64 string
1638
+    * to RFC2045, section 6.7.
1639
+    *
1640
+    * @param  string $input  The string to be encoded.
1641
+    *
1642
+    * @return string         The base64 encoded string.
1643
+    */
1644
+	function _base64Encode($input = '')
1645
+	{
1646
+		return base64_encode($input);
1647
+	}
1648
+
1649
+
1650
+	/**
1651
+	 * Converts an 8bit string to a quoted-printable string according to RFC
1652
+	 * 2045, section 6.7.
1653
+	 *
1654
+	 * imap_8bit() does not apply all necessary rules.
1655
+	 *
1656
+	 * @param string $input  The string to be encoded.
1657
+	 *
1658
+	 * @return string  The quoted-printable encoded string.
1659
+	 */
1660
+	function _quotedPrintableEncode($input = '', $withFolding=true)
1661
+	{
1662
+		$output = $line = '';
1663
+		$len = bytes($input);
1664
+
1665
+		for ($i = 0; $i < $len; ++$i) {
1666
+			$ord = ord($input[$i]);
1667
+			// Encode non-printable characters (rule 2).
1668
+			if ($ord == 9 ||
1669
+				($ord >= 32 && $ord <= 60) ||
1670
+				($ord >= 62 && $ord <= 126)) {
1671
+				$chunk = $input[$i];
1672
+			} else {
1673
+				// Quoted printable encoding (rule 1).
1674
+				$chunk = '=' . String::upper(sprintf('%02X', $ord));
1675
+			}
1676
+			$line .= $chunk;
1677
+			// Wrap long lines (rule 5)
1678
+			if ($withFolding && strlen($line) + 1 > 76) {
1679
+				$line = String::wordwrap($line, 75, "=\r\n", true, 'us-ascii', true);
1680
+				$newline = strrchr($line, "\r\n");
1681
+				if ($newline !== false) {
1682
+					$output .= substr($line, 0, -strlen($newline) + 2);
1683
+					$line = substr($newline, 2);
1684
+				} else {
1685
+					$output .= $line;
1686
+				}
1687
+				continue;
1688
+			}
1689
+			// Wrap at line breaks for better readability (rule 4).
1690
+			if ($withFolding && substr($line, -3) == '=0A') {
1691
+				$output .= $line . "=\r\n";
1692
+				$line = '';
1693
+			}
1694
+		}
1695
+		$output .= $line;
1696
+
1697
+		// Trailing whitespace must be encoded (rule 3).
1698
+		$lastpos = strlen($output) - 1;
1699
+		if ($output[$lastpos] == chr(9) ||
1700
+			$output[$lastpos] == chr(32)) {
1701
+			$output[$lastpos] = '=';
1702
+			$output .= String::upper(sprintf('%02X', ord($output[$lastpos])));
1703
+		}
1704
+
1705
+		return $output;
1706
+	}
1707 1707
 
1708 1708
 }
Please login to merge, or discard this patch.
Switch Indentation   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -970,237 +970,237 @@
 block discarded – undo
970 970
 
971 971
             switch ($name) {
972 972
             // Date fields.
973
-            case 'COMPLETED':
974
-            case 'CREATED':
975
-            case 'DCREATED':
976
-            case 'LAST-MODIFIED':
977
-                $value = $this->_exportDateTime($value);
978
-                break;
979
-
980
-			// Support additional fields after date.
973
+            	case 'COMPLETED':
974
+            	case 'CREATED':
975
+            	case 'DCREATED':
976
+            	case 'LAST-MODIFIED':
977
+                	$value = $this->_exportDateTime($value);
978
+                	break;
979
+
980
+				// Support additional fields after date.
981 981
  			case 'AALARM':
982
-            case 'DALARM':
983
-            	if (isset($params['VALUE'])) {
984
-                    if ($params['VALUE'] == 'DATE') {
985
-                        // VCALENDAR 1.0 uses T000000 - T235959 for all day events:
986
-                        if ($this->isOldFormat() && $name == 'DTEND') {
987
-                            $d = new Horde_Date($value);
988
-                            $value = new Horde_Date(array(
989
-                                'year' => $d->year,
990
-                                'month' => $d->month,
991
-                                'mday' => $d->mday - 1));
992
-                            $value->correct();
993
-                            $value = $this->_exportDate($value, '235959');
994
-                        } else {
995
-                            $value = $this->_exportDate($value, '000000');
996
-                        }
997
-                    } else {
998
-                        $value = $this->_exportDateTime($value);
999
-                    }
1000
-                } else {
1001
-                    $value = $this->_exportDateTime($value);
1002
-                }
1003
-
1004
-            	if (is_array($attribute['values']) &&
1005
-		            	count($attribute['values']) > 0) {
1006
-		            $values = $attribute['values'];
1007
-	            	if ($this->isOldFormat()) {
1008
-		            	$values = str_replace(';', '\\;', $values);
1009
-	            	} else {
1010
-                        // As of rfc 2426 2.5 semicolon and comma must be
1011
-                        // escaped.
1012
-                        $values = str_replace(array('\\', ';', ','),
1013
-                                              array('\\\\', '\\;', '\\,'),
1014
-                                              $values);
1015
-	            	}
1016
-	            	$value .= ';' . implode(';', $values);
1017
-		         }
1018
-
1019
-                break;
1020
-
1021
-            case 'DTEND':
1022
-            case 'DTSTART':
1023
-            case 'DTSTAMP':
1024
-            case 'DUE':
1025
-            case 'RECURRENCE-ID':
1026
-            case 'X-RECURRENCE-ID':
1027
-                if (isset($params['VALUE'])) {
1028
-                    if ($params['VALUE'] == 'DATE') {
1029
-                        // VCALENDAR 1.0 uses T000000 - T235959 for all day events:
1030
-                        if ($this->isOldFormat() && $name == 'DTEND') {
1031
-                            $d = new Horde_Date($value);
1032
-                            $value = new Horde_Date(array(
1033
-                                'year' => $d->year,
1034
-                                'month' => $d->month,
1035
-                                'mday' => $d->mday - 1));
1036
-                            $value->correct();
1037
-                            $value = $this->_exportDate($value, '235959');
1038
-                        } else {
1039
-                            $value = $this->_exportDate($value, '000000');
1040
-                        }
1041
-                    } else {
1042
-                        $value = $this->_exportDateTime($value);
1043
-                    }
1044
-                } else {
1045
-                    $value = $this->_exportDateTime($value);
1046
-                }
1047
-                break;
1048
-
1049
-            // Comma or semicolon seperated dates.
1050
-            case 'EXDATE':
1051
-            case 'RDATE':
1052
-	            if (is_array($attribute['values'])) {
1053
-		            $values = $attribute['values'];
1054
-	            } elseif (!empty($value)) {
1055
-	            	if ($this->isOldFormat()) {
1056
-		            	$values = explode(';', $value);
982
+            	case 'DALARM':
983
+            		if (isset($params['VALUE'])) {
984
+                    	if ($params['VALUE'] == 'DATE') {
985
+                        	// VCALENDAR 1.0 uses T000000 - T235959 for all day events:
986
+                        	if ($this->isOldFormat() && $name == 'DTEND') {
987
+                            	$d = new Horde_Date($value);
988
+                            	$value = new Horde_Date(array(
989
+                                	'year' => $d->year,
990
+                                	'month' => $d->month,
991
+                                	'mday' => $d->mday - 1));
992
+                            	$value->correct();
993
+                            	$value = $this->_exportDate($value, '235959');
994
+                        	} else {
995
+                            	$value = $this->_exportDate($value, '000000');
996
+                        	}
997
+                    	} else {
998
+                        	$value = $this->_exportDateTime($value);
999
+                    	}
1000
+                	} else {
1001
+                    	$value = $this->_exportDateTime($value);
1002
+                	}
1003
+
1004
+            		if (is_array($attribute['values']) &&
1005
+		            		count($attribute['values']) > 0) {
1006
+		            	$values = $attribute['values'];
1007
+	            		if ($this->isOldFormat()) {
1008
+		            		$values = str_replace(';', '\\;', $values);
1009
+	            		} else {
1010
+                        	// As of rfc 2426 2.5 semicolon and comma must be
1011
+                        	// escaped.
1012
+                        	$values = str_replace(array('\\', ';', ','),
1013
+                                              	array('\\\\', '\\;', '\\,'),
1014
+                                              	$values);
1015
+	            		}
1016
+	            		$value .= ';' . implode(';', $values);
1017
+		         	}
1018
+
1019
+                	break;
1020
+
1021
+            	case 'DTEND':
1022
+            	case 'DTSTART':
1023
+            	case 'DTSTAMP':
1024
+            	case 'DUE':
1025
+            	case 'RECURRENCE-ID':
1026
+            	case 'X-RECURRENCE-ID':
1027
+                	if (isset($params['VALUE'])) {
1028
+                    	if ($params['VALUE'] == 'DATE') {
1029
+                        	// VCALENDAR 1.0 uses T000000 - T235959 for all day events:
1030
+                        	if ($this->isOldFormat() && $name == 'DTEND') {
1031
+                            	$d = new Horde_Date($value);
1032
+                            	$value = new Horde_Date(array(
1033
+                                	'year' => $d->year,
1034
+                                	'month' => $d->month,
1035
+                                	'mday' => $d->mday - 1));
1036
+                            	$value->correct();
1037
+                            	$value = $this->_exportDate($value, '235959');
1038
+                        	} else {
1039
+                            	$value = $this->_exportDate($value, '000000');
1040
+                        	}
1041
+                    	} else {
1042
+                        	$value = $this->_exportDateTime($value);
1043
+                    	}
1044
+                	} else {
1045
+                    	$value = $this->_exportDateTime($value);
1046
+                	}
1047
+                	break;
1048
+
1049
+            	// Comma or semicolon seperated dates.
1050
+            	case 'EXDATE':
1051
+            	case 'RDATE':
1052
+	            	if (is_array($attribute['values'])) {
1053
+		            	$values = $attribute['values'];
1054
+	            	} elseif (!empty($value)) {
1055
+	            		if ($this->isOldFormat()) {
1056
+		            		$values = explode(';', $value);
1057
+	            		} else {
1058
+	            			$values = explode(',', $value);
1059
+	            		}
1057 1060
 	            	} else {
1058
-	            		$values = explode(',', $value);
1061
+		            	break;
1059 1062
 	            	}
1060
-	            } else {
1061
-		            break;
1062
-	            }
1063
-                $dates = array();
1064
-                foreach ($values as $date) {
1065
-                    if (isset($params['VALUE'])) {
1066
-                        if ($params['VALUE'] == 'DATE') {
1067
-                            $dates[] = $this->_exportDate($date, '000000');
1068
-                        } elseif ($params['VALUE'] == 'PERIOD') {
1069
-                            $dates[] = $this->_exportPeriod($date);
1070
-                        } else {
1071
-                            $dates[] = $this->_exportDateTime($date);
1072
-                        }
1073
-                    } else {
1074
-                        $dates[] = $this->_exportDateTime($date);
1075
-                    }
1076
-                }
1077
-                if ($this->isOldFormat()) {
1078
-	                $value = implode(';', $dates);
1079
-                } else {
1080
-	                $value = implode(',', $dates);
1081
-                }
1082
-                break;
1083
-
1084
-            case 'TRIGGER':
1085
-                if (isset($params['VALUE'])) {
1086
-                    if ($params['VALUE'] == 'DATE-TIME') {
1087
-                        $value = $this->_exportDateTime($value);
1088
-                    } elseif ($params['VALUE'] == 'DURATION') {
1089
-                        $value = $this->_exportDuration($value);
1090
-                    }
1091
-                } else {
1092
-                    $value = $this->_exportDuration($value);
1093
-                }
1094
-                break;
1095
-
1096
-            // Duration fields.
1097
-            case 'DURATION':
1098
-                $value = $this->_exportDuration($value);
1099
-                break;
1100
-
1101
-            // Period of time fields.
1102
-            case 'FREEBUSY':
1103
-                $value_str = '';
1104
-                foreach ($value as $period) {
1105
-                    $value_str .= empty($value_str) ? '' : ',';
1106
-                    $value_str .= $this->_exportPeriod($period);
1107
-                }
1108
-                $value = $value_str;
1109
-                break;
1110
-
1111
-            // UTC offset fields.
1112
-            case 'TZOFFSETFROM':
1113
-            case 'TZOFFSETTO':
1114
-                $value = $this->_exportUtcOffset($value);
1115
-                break;
1116
-
1117
-            // Integer fields.
1118
-            case 'PERCENT-COMPLETE':
1119
-            case 'PRIORITY':
1120
-            case 'REPEAT':
1121
-            case 'SEQUENCE':
1122
-                $value = "$value";
1123
-                break;
1124
-
1125
-            // Geo fields.
1126
-            case 'GEO':
1127
-                if ($this->isOldFormat()) {
1128
-                    $value = $value['longitude'] . ',' . $value['latitude'];
1129
-                } else {
1130
-                    $value = $value['latitude'] . ';' . $value['longitude'];
1131
-                }
1132
-                break;
1133
-
1134
-            // Recurrence fields.
1135
-            case 'EXRULE':
1136
-            	break;
1137
-
1138
-            case 'RRULE':
1139
-                if (!empty($params_str) &&  $params_str[0] == ';')
1140
-                {
1141
-                	// The standard requires a double colon RRULE:...
1142
-                	 $params_str[0] = ':';
1143
-                }
1144
-                break;
1145
-
1146
-            case 'PHOTO':
1147
-                break;
1148
-
1149
-            default:
1150
-                if ($this->isOldFormat()) {
1151
-                    if (is_array($attribute['values']) &&
1152
-                        count($attribute['values']) > 1) {
1153
-                        $values = $attribute['values'];
1154
-                        if ($name == 'N' || $name == 'ADR' || $name == 'ORG') {
1155
-                            $glue = ';';
1156
-                        } else {
1157
-                            $glue = ',';
1158
-                        }
1159
-                        $values = str_replace(';', '\\;', $values);
1160
-                        $value = implode($glue, $values);
1161
-                    } else {
1162
-                        /* vcard 2.1 and vcalendar 1.0 escape only
1063
+                	$dates = array();
1064
+                	foreach ($values as $date) {
1065
+                    	if (isset($params['VALUE'])) {
1066
+                        	if ($params['VALUE'] == 'DATE') {
1067
+                            	$dates[] = $this->_exportDate($date, '000000');
1068
+                        	} elseif ($params['VALUE'] == 'PERIOD') {
1069
+                            	$dates[] = $this->_exportPeriod($date);
1070
+                        	} else {
1071
+                            	$dates[] = $this->_exportDateTime($date);
1072
+                        	}
1073
+                    	} else {
1074
+                        	$dates[] = $this->_exportDateTime($date);
1075
+                    	}
1076
+                	}
1077
+                	if ($this->isOldFormat()) {
1078
+	                	$value = implode(';', $dates);
1079
+                	} else {
1080
+	                	$value = implode(',', $dates);
1081
+                	}
1082
+                	break;
1083
+
1084
+            	case 'TRIGGER':
1085
+                	if (isset($params['VALUE'])) {
1086
+                    	if ($params['VALUE'] == 'DATE-TIME') {
1087
+                        	$value = $this->_exportDateTime($value);
1088
+                    	} elseif ($params['VALUE'] == 'DURATION') {
1089
+                        	$value = $this->_exportDuration($value);
1090
+                    	}
1091
+                	} else {
1092
+                    	$value = $this->_exportDuration($value);
1093
+                	}
1094
+                	break;
1095
+
1096
+            	// Duration fields.
1097
+            	case 'DURATION':
1098
+                	$value = $this->_exportDuration($value);
1099
+                	break;
1100
+
1101
+            	// Period of time fields.
1102
+            	case 'FREEBUSY':
1103
+                	$value_str = '';
1104
+                	foreach ($value as $period) {
1105
+                    	$value_str .= empty($value_str) ? '' : ',';
1106
+                    	$value_str .= $this->_exportPeriod($period);
1107
+                	}
1108
+                	$value = $value_str;
1109
+                	break;
1110
+
1111
+            	// UTC offset fields.
1112
+            	case 'TZOFFSETFROM':
1113
+            	case 'TZOFFSETTO':
1114
+                	$value = $this->_exportUtcOffset($value);
1115
+                	break;
1116
+
1117
+            	// Integer fields.
1118
+            	case 'PERCENT-COMPLETE':
1119
+            	case 'PRIORITY':
1120
+            	case 'REPEAT':
1121
+            	case 'SEQUENCE':
1122
+                	$value = "$value";
1123
+                	break;
1124
+
1125
+            	// Geo fields.
1126
+            	case 'GEO':
1127
+                	if ($this->isOldFormat()) {
1128
+                    	$value = $value['longitude'] . ',' . $value['latitude'];
1129
+                	} else {
1130
+                    	$value = $value['latitude'] . ';' . $value['longitude'];
1131
+                	}
1132
+                	break;
1133
+
1134
+            	// Recurrence fields.
1135
+            	case 'EXRULE':
1136
+            		break;
1137
+
1138
+            	case 'RRULE':
1139
+                	if (!empty($params_str) &&  $params_str[0] == ';')
1140
+                	{
1141
+                		// The standard requires a double colon RRULE:...
1142
+                	 	$params_str[0] = ':';
1143
+                	}
1144
+                	break;
1145
+
1146
+            	case 'PHOTO':
1147
+                	break;
1148
+
1149
+            	default:
1150
+                	if ($this->isOldFormat()) {
1151
+                    	if (is_array($attribute['values']) &&
1152
+                        	count($attribute['values']) > 1) {
1153
+                        	$values = $attribute['values'];
1154
+                        	if ($name == 'N' || $name == 'ADR' || $name == 'ORG') {
1155
+                            	$glue = ';';
1156
+                        	} else {
1157
+                            	$glue = ',';
1158
+                        	}
1159
+                        	$values = str_replace(';', '\\;', $values);
1160
+                        	$value = implode($glue, $values);
1161
+                    	} else {
1162
+                        	/* vcard 2.1 and vcalendar 1.0 escape only
1163 1163
                          * semicolons */
1164
-                        $value = str_replace(';', '\\;', $value);
1165
-                    }
1166
-                    // Text containing newlines or ASCII >= 127 must be BASE64
1167
-                    // or QUOTED-PRINTABLE encoded. Currently we use
1168
-                    // QUOTED-PRINTABLE as default.
1169
-                    if (preg_match('/[^\x20-\x7F]/', $value) &&
1170
-		                    !isset($params['ENCODING']))  {
1171
-	                    $params['ENCODING'] = 'QUOTED-PRINTABLE';
1172
-                    }
1173
-                    if (preg_match('/([\177-\377])/', $value) &&
1174
-		                    !isset($params['CHARSET'])) {
1175
-	                    // Add CHARSET as well. At least the synthesis client
1176
-	                    // gets confused otherwise
1177
-	                    $params['CHARSET'] = String::upper($charset);
1178
-	                    $params_str .= ';CHARSET=' . $params['CHARSET'];
1179
-                    }
1180
-                } else {
1181
-                    if (is_array($attribute['values']) &&
1182
-                        count($attribute['values']) > 1) {
1183
-                        $values = $attribute['values'];
1184
-                        if ($name == 'N' || $name == 'ADR' || $name == 'ORG') {
1185
-                            $glue = ';';
1186
-                        } else {
1187
-                            $glue = ',';
1188
-                        }
1189
-                        // As of rfc 2426 2.5 semicolon and comma must be
1190
-                        // escaped.
1191
-                        $values = str_replace(array('\\', ';', ','),
1192
-                                              array('\\\\', '\\;', '\\,'),
1193
-                                              $values);
1194
-                        $value = implode($glue, $values);
1195
-                    } else {
1196
-                        // As of rfc 2426 2.5 semicolon and comma must be
1197
-                        // escaped.
1198
-                        $value = str_replace(array('\\', ';', ','),
1199
-                                             array('\\\\', '\\;', '\\,'),
1200
-                                             $value);
1201
-                    }
1202
-                    $value = preg_replace('/\r?\n/', "\n", $value);
1203
-                }
1164
+                        	$value = str_replace(';', '\\;', $value);
1165
+                    	}
1166
+                    	// Text containing newlines or ASCII >= 127 must be BASE64
1167
+                    	// or QUOTED-PRINTABLE encoded. Currently we use
1168
+                    	// QUOTED-PRINTABLE as default.
1169
+                    	if (preg_match('/[^\x20-\x7F]/', $value) &&
1170
+		                    	!isset($params['ENCODING']))  {
1171
+	                    	$params['ENCODING'] = 'QUOTED-PRINTABLE';
1172
+                    	}
1173
+                    	if (preg_match('/([\177-\377])/', $value) &&
1174
+		                    	!isset($params['CHARSET'])) {
1175
+	                    	// Add CHARSET as well. At least the synthesis client
1176
+	                    	// gets confused otherwise
1177
+	                    	$params['CHARSET'] = String::upper($charset);
1178
+	                    	$params_str .= ';CHARSET=' . $params['CHARSET'];
1179
+                    	}
1180
+                	} else {
1181
+                    	if (is_array($attribute['values']) &&
1182
+                        	count($attribute['values']) > 1) {
1183
+                        	$values = $attribute['values'];
1184
+                        	if ($name == 'N' || $name == 'ADR' || $name == 'ORG') {
1185
+                            	$glue = ';';
1186
+                        	} else {
1187
+                            	$glue = ',';
1188
+                        	}
1189
+                        	// As of rfc 2426 2.5 semicolon and comma must be
1190
+                        	// escaped.
1191
+                        	$values = str_replace(array('\\', ';', ','),
1192
+                                              	array('\\\\', '\\;', '\\,'),
1193
+                                              	$values);
1194
+                        	$value = implode($glue, $values);
1195
+                    	} else {
1196
+                        	// As of rfc 2426 2.5 semicolon and comma must be
1197
+                        	// escaped.
1198
+                        	$value = str_replace(array('\\', ';', ','),
1199
+                                             	array('\\\\', '\\;', '\\,'),
1200
+                                             	$value);
1201
+                    	}
1202
+                    	$value = preg_replace('/\r?\n/', "\n", $value);
1203
+                	}
1204 1204
             }
1205 1205
 
1206 1206
 			$encoding = (!empty($params['ENCODING']) && strlen(trim($value)) > 0);
Please login to merge, or discard this patch.
Spacing   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -80,10 +80,10 @@  discard block
 block discarded – undo
80 80
     function &newComponent($type, &$container)
81 81
     {
82 82
         $type = String::lower($type);
83
-        $class = 'Horde_iCalendar_' . $type;
83
+        $class = 'Horde_iCalendar_'.$type;
84 84
         if (!class_exists($class)) {
85 85
 			// include relative from current dir, as we no longer set (old) Horde dir in include path
86
-            include 'iCalendar/' . $type . '.php';
86
+            include 'iCalendar/'.$type.'.php';
87 87
         }
88 88
         if (class_exists($class)) {
89 89
             $component = new $class();
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
         }
202 202
         if (!count($result)) {
203 203
             require_once 'PEAR.php';
204
-            return PEAR::raiseError('Attribute "' . $name . '" Not Found');
204
+            return PEAR::raiseError('Attribute "'.$name.'" Not Found');
205 205
         } if (count($result) == 1 && !$params) {
206 206
             return $result[0];
207 207
         } else {
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
             }
233 233
         }
234 234
         if (!count($result)) {
235
-            return PEAR::raiseError('Attribute "' . $name . '" Not Found');
235
+            return PEAR::raiseError('Attribute "'.$name.'" Not Found');
236 236
         }
237 237
         return $result;
238 238
     }
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
      */
380 380
     function &findComponent($childclass)
381 381
     {
382
-        $childclass = 'Horde_iCalendar_' . String::lower($childclass);
382
+        $childclass = 'Horde_iCalendar_'.String::lower($childclass);
383 383
         $keys = array_keys($this->_components);
384 384
         foreach ($keys as $key) {
385 385
             if (is_a($this->_components[$key], $childclass)) {
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
      */
407 407
     function &findComponentByAttribute($childclass, $attribute, $value = null)
408 408
     {
409
-        $childclass = 'Horde_iCalendar_' . String::lower($childclass);
409
+        $childclass = 'Horde_iCalendar_'.String::lower($childclass);
410 410
         $keys = array_keys($this->_components);
411 411
         foreach ($keys as $key) {
412 412
             if (is_a($this->_components[$key], $childclass)) {
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
     function exportvCalendar($charset = null)
471 471
     {
472 472
         // Default values.
473
-        $requiredAttributes['PRODID'] = '-//The Horde Project//Horde_iCalendar Library' . (defined('HORDE_VERSION') ? ', Horde ' . constant('HORDE_VERSION') : '') . '//EN';
473
+        $requiredAttributes['PRODID'] = '-//The Horde Project//Horde_iCalendar Library'.(defined('HORDE_VERSION') ? ', Horde '.constant('HORDE_VERSION') : '').'//EN';
474 474
         // METHOD is only required for iTip, but not for CalDAV, therefore removing it here calendar_ical sets it anyway by default
475 475
         //$requiredAttributes['METHOD'] = 'PUBLISH';
476 476
 
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
     function toHash($paramsInKeys = false)
500 500
     {
501 501
         $hash = array();
502
-        foreach ($this->_attributes as $a)  {
502
+        foreach ($this->_attributes as $a) {
503 503
             $k = $a['name'];
504 504
             if ($paramsInKeys && is_array($a['params'])) {
505 505
                 foreach ($a['params'] as $p => $v) {
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
         		__FILE__, __LINE__, PEAR_LOG_WARNING);
539 539
             $container = true;
540 540
             $vCal = $matches[1];
541
-        } elseif (preg_match('/^BEGIN:' . $base . '(.*)^END:' . $base . '/ism', $text, $matches)) {
541
+        } elseif (preg_match('/^BEGIN:'.$base.'(.*)^END:'.$base.'/ism', $text, $matches)) {
542 542
             $container = true;
543 543
             $vCal = $matches[1];
544 544
         } else {
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
         }
556 556
 
557 557
 		// Preserve a trailing CR
558
-        $vCal = trim($vCal) . "\n";
558
+        $vCal = trim($vCal)."\n";
559 559
 
560 560
         // All subcomponents.
561 561
         $matches = null;
@@ -748,7 +748,7 @@  discard block
 block discarded – undo
748 748
 	                case 'EXDATE':
749 749
 	                case 'RDATE':
750 750
 		                $dates = array();
751
-		                preg_match_all('/[;,]([^;,]*)/', ';' . $value, $values);
751
+		                preg_match_all('/[;,]([^;,]*)/', ';'.$value, $values);
752 752
 
753 753
 		                foreach ($values[1] as $value) {
754 754
 			                if ((isset($params['VALUE'])
@@ -769,7 +769,7 @@  discard block
 block discarded – undo
769 769
 		                // Period of time fields.
770 770
 	                case 'FREEBUSY':
771 771
 		                $periods = array();
772
-		                preg_match_all('/,([^,]*)/', ',' . $value, $values);
772
+		                preg_match_all('/,([^,]*)/', ','.$value, $values);
773 773
 		                foreach ($values[1] as $value) {
774 774
 			                $periods[] = $this->_parsePeriod($value);
775 775
 		                }
@@ -903,7 +903,7 @@  discard block
 block discarded – undo
903 903
     {
904 904
     	$base = String::upper($base);
905 905
 
906
-        $result = 'BEGIN:' . $base . $this->_newline;
906
+        $result = 'BEGIN:'.$base.$this->_newline;
907 907
 
908 908
         // VERSION is not allowed for entries enclosed in VCALENDAR/ICALENDAR,
909 909
         // as it is part of the enclosing VCALENDAR/ICALENDAR. See rfc2445
@@ -911,7 +911,7 @@  discard block
 block discarded – undo
911 911
             $base !== 'VJOURNAL' && $base !== 'VFREEBUSY' &&
912 912
             $base !== 'VTIMEZONE' && $base !== 'STANDARD' && $base != 'DAYLIGHT') {
913 913
             // Ensure that version is the first attribute.
914
-            $result .= 'VERSION:' . $this->_version . $this->_newline;
914
+            $result .= 'VERSION:'.$this->_version.$this->_newline;
915 915
         }
916 916
 
917 917
         if (empty($charset)) {
@@ -1013,7 +1013,7 @@  discard block
 block discarded – undo
1013 1013
                                               array('\\\\', '\\;', '\\,'),
1014 1014
                                               $values);
1015 1015
 	            	}
1016
-	            	$value .= ';' . implode(';', $values);
1016
+	            	$value .= ';'.implode(';', $values);
1017 1017
 		         }
1018 1018
 
1019 1019
                 break;
@@ -1125,9 +1125,9 @@  discard block
 block discarded – undo
1125 1125
             // Geo fields.
1126 1126
             case 'GEO':
1127 1127
                 if ($this->isOldFormat()) {
1128
-                    $value = $value['longitude'] . ',' . $value['latitude'];
1128
+                    $value = $value['longitude'].','.$value['latitude'];
1129 1129
                 } else {
1130
-                    $value = $value['latitude'] . ';' . $value['longitude'];
1130
+                    $value = $value['latitude'].';'.$value['longitude'];
1131 1131
                 }
1132 1132
                 break;
1133 1133
 
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
             	break;
1137 1137
 
1138 1138
             case 'RRULE':
1139
-                if (!empty($params_str) &&  $params_str[0] == ';')
1139
+                if (!empty($params_str) && $params_str[0] == ';')
1140 1140
                 {
1141 1141
                 	// The standard requires a double colon RRULE:...
1142 1142
                 	 $params_str[0] = ':';
@@ -1167,7 +1167,7 @@  discard block
 block discarded – undo
1167 1167
                     // or QUOTED-PRINTABLE encoded. Currently we use
1168 1168
                     // QUOTED-PRINTABLE as default.
1169 1169
                     if (preg_match('/[^\x20-\x7F]/', $value) &&
1170
-		                    !isset($params['ENCODING']))  {
1170
+		                    !isset($params['ENCODING'])) {
1171 1171
 	                    $params['ENCODING'] = 'QUOTED-PRINTABLE';
1172 1172
                     }
1173 1173
                     if (preg_match('/([\177-\377])/', $value) &&
@@ -1175,7 +1175,7 @@  discard block
 block discarded – undo
1175 1175
 	                    // Add CHARSET as well. At least the synthesis client
1176 1176
 	                    // gets confused otherwise
1177 1177
 	                    $params['CHARSET'] = String::upper($charset);
1178
-	                    $params_str .= ';CHARSET=' . $params['CHARSET'];
1178
+	                    $params_str .= ';CHARSET='.$params['CHARSET'];
1179 1179
                     }
1180 1180
                 } else {
1181 1181
                     if (is_array($attribute['values']) &&
@@ -1206,7 +1206,7 @@  discard block
 block discarded – undo
1206 1206
 			$encoding = (!empty($params['ENCODING']) && strlen(trim($value)) > 0);
1207 1207
 
1208 1208
             if ($encoding) {
1209
-	            switch($params['ENCODING']) {
1209
+	            switch ($params['ENCODING']) {
1210 1210
 		            case 'Q':
1211 1211
 		            case 'QUOTED-PRINTABLE':
1212 1212
 		            	if (!$this->isOldFormat())
@@ -1214,9 +1214,9 @@  discard block
 block discarded – undo
1214 1214
 		            		$encoding = false;
1215 1215
 		            		break;
1216 1216
 		            	}
1217
-			            $params_str .= ';ENCODING=' . $params['ENCODING'];
1217
+			            $params_str .= ';ENCODING='.$params['ENCODING'];
1218 1218
 			            $value = str_replace("\r", '', $value);
1219
-			            $result .= $name . $params_str . ':'
1219
+			            $result .= $name.$params_str.':'
1220 1220
 				            . str_replace('=0A', '=0D=0A',
1221 1221
 					            $this->_quotedPrintableEncode($value))
1222 1222
 								. $this->_newline;
@@ -1230,17 +1230,17 @@  discard block
 block discarded – undo
1230 1230
 			            	break;
1231 1231
 			            }
1232 1232
 			            $params_str .= ';ENCODING=QUOTED-PRINTABLE';
1233
-			            $result .= $name . $params_str . ':'
1233
+			            $result .= $name.$params_str.':'
1234 1234
 				            . str_replace('=0A', '=0D=0A',
1235 1235
 					            $this->_quotedPrintableEncode($value, false))
1236 1236
 								. $this->_newline;
1237 1237
 			            break;
1238 1238
 		            case 'B':
1239 1239
 		            case 'BASE64':
1240
-			            $params_str .= ';ENCODING=' . $params['ENCODING'];
1240
+			            $params_str .= ';ENCODING='.$params['ENCODING'];
1241 1241
 			            // using native php wordwrap to speed up encoding of images
1242
-			            $result .= wordwrap($name . $params_str . ':' . $this->_newline . ' ' .
1243
-			            	$this->_base64Encode($value),75,$this->_newline . ' ',true) . $this->_newline;
1242
+			            $result .= wordwrap($name.$params_str.':'.$this->_newline.' '.
1243
+			            	$this->_base64Encode($value), 75, $this->_newline.' ', true).$this->_newline;
1244 1244
 			            /*
1245 1245
 			            $attr_string = $name . $params_str . ':' . $this->_newline . ' ' . $this->_base64Encode($value);
1246 1246
 			            $attr_string = String::wordwrap($attr_string, 75, $this->_newline . ' ',
@@ -1255,29 +1255,29 @@  discard block
 block discarded – undo
1255 1255
 
1256 1256
             if (!$encoding) {
1257 1257
                 $value = str_replace(array("\r", "\n"), array('', '\\n'), $value);
1258
-                $attr_string = $name . $params_str;
1258
+                $attr_string = $name.$params_str;
1259 1259
                 if (strlen($value) > 0) {
1260
-                	$attr_string .= ':' . $value;
1260
+                	$attr_string .= ':'.$value;
1261 1261
                 } elseif ($name != 'RRULE') {
1262 1262
                 	$attr_string .= ':';
1263 1263
                 }
1264 1264
                 if (!$this->isOldFormat()) {
1265
-                    $attr_string = String::wordwrap($attr_string, 75, $this->_newline . ' ',
1265
+                    $attr_string = String::wordwrap($attr_string, 75, $this->_newline.' ',
1266 1266
                                                     true, $charset, true);
1267 1267
                 }
1268
-                $result .= $attr_string . $this->_newline;
1268
+                $result .= $attr_string.$this->_newline;
1269 1269
             }
1270 1270
         }
1271 1271
 
1272 1272
         foreach ($this->_components as $component) {
1273
-            if ($this->isOldFormat() &&  $component->getType() == 'vTimeZone') {
1273
+            if ($this->isOldFormat() && $component->getType() == 'vTimeZone') {
1274 1274
     			// Not supported
1275 1275
 				continue;
1276 1276
         	}
1277 1277
             $result .= $component->exportvCalendar($charset);
1278 1278
         }
1279 1279
 
1280
-        return $result . 'END:' . $base . $this->_newline;
1280
+        return $result.'END:'.$base.$this->_newline;
1281 1281
     }
1282 1282
 
1283 1283
     /**
@@ -1457,7 +1457,7 @@  discard block
 block discarded – undo
1457 1457
             $temp['hour']   = date('G', $value);
1458 1458
             $temp['minute'] = date('i', $value);
1459 1459
             $temp['second'] = date('s', $value);
1460
-            return Horde_iCalendar::_exportDate($temp) . 'T' . Horde_iCalendar::_exportTime($temp);
1460
+            return Horde_iCalendar::_exportDate($temp).'T'.Horde_iCalendar::_exportTime($temp);
1461 1461
         } else if (is_object($value) || is_array($value)) {
1462 1462
             $dateOb = new Horde_Date($value);
1463 1463
             return Horde_iCalendar::_exportDateTime($dateOb->timestamp());
@@ -1595,13 +1595,13 @@  discard block
 block discarded – undo
1595 1595
         $weeks = floor($value / (7 * 86400));
1596 1596
         $value = $value % (7 * 86400);
1597 1597
         if ($weeks) {
1598
-            $duration .= $weeks . 'W';
1598
+            $duration .= $weeks.'W';
1599 1599
         }
1600 1600
 
1601 1601
         $days = floor($value / (86400));
1602 1602
         $value = $value % (86400);
1603 1603
         if ($days) {
1604
-            $duration .= $days . 'D';
1604
+            $duration .= $days.'D';
1605 1605
         }
1606 1606
 
1607 1607
         if ($value) {
@@ -1610,17 +1610,17 @@  discard block
 block discarded – undo
1610 1610
             $hours = floor($value / 3600);
1611 1611
             $value = $value % 3600;
1612 1612
             if ($hours) {
1613
-                $duration .= $hours . 'H';
1613
+                $duration .= $hours.'H';
1614 1614
             }
1615 1615
 
1616 1616
             $mins = floor($value / 60);
1617 1617
             $value = $value % 60;
1618 1618
             if ($mins) {
1619
-                $duration .= $mins . 'M';
1619
+                $duration .= $mins.'M';
1620 1620
             }
1621 1621
 
1622 1622
             if ($value) {
1623
-                $duration .= $value . 'S';
1623
+                $duration .= $value.'S';
1624 1624
             }
1625 1625
         }
1626 1626
 		// duration without time ("P") is NOT valid, append 0 minutes ("T0M")
@@ -1657,7 +1657,7 @@  discard block
 block discarded – undo
1657 1657
      *
1658 1658
      * @return string  The quoted-printable encoded string.
1659 1659
      */
1660
-    function _quotedPrintableEncode($input = '', $withFolding=true)
1660
+    function _quotedPrintableEncode($input = '', $withFolding = true)
1661 1661
     {
1662 1662
         $output = $line = '';
1663 1663
         $len = bytes($input);
@@ -1671,7 +1671,7 @@  discard block
 block discarded – undo
1671 1671
                 $chunk = $input[$i];
1672 1672
             } else {
1673 1673
                 // Quoted printable encoding (rule 1).
1674
-                $chunk = '=' . String::upper(sprintf('%02X', $ord));
1674
+                $chunk = '='.String::upper(sprintf('%02X', $ord));
1675 1675
             }
1676 1676
             $line .= $chunk;
1677 1677
             // Wrap long lines (rule 5)
@@ -1688,7 +1688,7 @@  discard block
 block discarded – undo
1688 1688
             }
1689 1689
             // Wrap at line breaks for better readability (rule 4).
1690 1690
             if ($withFolding && substr($line, -3) == '=0A') {
1691
-                $output .= $line . "=\r\n";
1691
+                $output .= $line."=\r\n";
1692 1692
                 $line = '';
1693 1693
             }
1694 1694
         }
Please login to merge, or discard this patch.
Braces   +518 added lines, -230 removed lines patch added patch discarded remove patch
@@ -20,7 +20,8 @@  discard block
 block discarded – undo
20 20
 /**
21 21
  * Class representing iCalendar files.
22 22
  */
23
-class Horde_iCalendar {
23
+class Horde_iCalendar
24
+{
24 25
 
25 26
     /**
26 27
      * The parent (containing) iCalendar object.
@@ -81,19 +82,24 @@  discard block
 block discarded – undo
81 82
     {
82 83
         $type = String::lower($type);
83 84
         $class = 'Horde_iCalendar_' . $type;
84
-        if (!class_exists($class)) {
85
+        if (!class_exists($class))
86
+        {
85 87
 			// include relative from current dir, as we no longer set (old) Horde dir in include path
86 88
             include 'iCalendar/' . $type . '.php';
87 89
         }
88
-        if (class_exists($class)) {
90
+        if (class_exists($class))
91
+        {
89 92
             $component = new $class();
90
-            if ($container !== false) {
93
+            if ($container !== false)
94
+            {
91 95
                 $component->_container = &$container;
92 96
                 // Use version of container, not default set by component
93 97
                 // constructor.
94 98
                 $component->_version = $container->_version;
95 99
             }
96
-        } else {
100
+        }
101
+        else
102
+        {
97 103
             // Should return an dummy x-unknown type class here.
98 104
             $component = false;
99 105
         }
@@ -119,20 +125,26 @@  discard block
 block discarded – undo
119 125
     {
120 126
         // Make sure we update the internal format version if
121 127
         // setAttribute('VERSION', ...) is called.
122
-        if ($name == 'VERSION') {
128
+        if ($name == 'VERSION')
129
+        {
123 130
             $this->_version = $value;
124
-            if ($this->_container !== false) {
131
+            if ($this->_container !== false)
132
+            {
125 133
                 $this->_container->_version = $value;
126 134
             }
127 135
         }
128 136
 
129
-        if (!$values) {
137
+        if (!$values)
138
+        {
130 139
             $values = array($value);
131 140
         }
132 141
         $found = false;
133
-        if (!$append) {
134
-            foreach (array_keys($this->_attributes) as $key) {
135
-                if ($this->_attributes[$key]['name'] == String::upper($name)) {
142
+        if (!$append)
143
+        {
144
+            foreach (array_keys($this->_attributes) as $key)
145
+            {
146
+                if ($this->_attributes[$key]['name'] == String::upper($name))
147
+                {
136 148
                     $this->_attributes[$key]['params'] = $params;
137 149
                     $this->_attributes[$key]['value'] = $value;
138 150
                     $this->_attributes[$key]['values'] = $values;
@@ -142,7 +154,8 @@  discard block
 block discarded – undo
142 154
             }
143 155
         }
144 156
 
145
-        if ($append || !$found) {
157
+        if ($append || !$found)
158
+        {
146 159
             $this->_attributes[] = array(
147 160
                 'name'      => String::upper($name),
148 161
                 'params'    => $params,
@@ -164,8 +177,10 @@  discard block
 block discarded – undo
164 177
     function setParameter($name, $params = array())
165 178
     {
166 179
         $keys = array_keys($this->_attributes);
167
-        foreach ($keys as $key) {
168
-            if ($this->_attributes[$key]['name'] == $name) {
180
+        foreach ($keys as $key)
181
+        {
182
+            if ($this->_attributes[$key]['name'] == $name)
183
+            {
169 184
                 $this->_attributes[$key]['params'] =
170 185
                     array_merge($this->_attributes[$key]['params'], $params);
171 186
                 return true;
@@ -190,21 +205,30 @@  discard block
 block discarded – undo
190 205
     function getAttribute($name, $params = false)
191 206
     {
192 207
         $result = array();
193
-        foreach ($this->_attributes as $attribute) {
194
-            if ($attribute['name'] == $name) {
195
-                if ($params) {
208
+        foreach ($this->_attributes as $attribute)
209
+        {
210
+            if ($attribute['name'] == $name)
211
+            {
212
+                if ($params)
213
+                {
196 214
                     $result[] = $attribute['params'];
197
-                } else {
215
+                }
216
+                else
217
+                {
198 218
                     $result[] = $attribute['value'];
199 219
                 }
200 220
             }
201 221
         }
202
-        if (!count($result)) {
222
+        if (!count($result))
223
+        {
203 224
             require_once 'PEAR.php';
204 225
             return PEAR::raiseError('Attribute "' . $name . '" Not Found');
205
-        } if (count($result) == 1 && !$params) {
226
+        } if (count($result) == 1 && !$params)
227
+        {
206 228
             return $result[0];
207
-        } else {
229
+        }
230
+        else
231
+        {
208 232
             return $result;
209 233
         }
210 234
     }
@@ -226,12 +250,15 @@  discard block
 block discarded – undo
226 250
     function getAttributeValues($name)
227 251
     {
228 252
         $result = array();
229
-        foreach ($this->_attributes as $attribute) {
230
-            if ($attribute['name'] == $name) {
253
+        foreach ($this->_attributes as $attribute)
254
+        {
255
+            if ($attribute['name'] == $name)
256
+            {
231 257
                 $result = array_merge($attribute['values'], $result);
232 258
             }
233 259
         }
234
-        if (!count($result)) {
260
+        if (!count($result))
261
+        {
235 262
             return PEAR::raiseError('Attribute "' . $name . '" Not Found');
236 263
         }
237 264
         return $result;
@@ -262,8 +289,10 @@  discard block
 block discarded – undo
262 289
     function removeAttribute($name)
263 290
     {
264 291
         $keys = array_keys($this->_attributes);
265
-        foreach ($keys as $key) {
266
-            if ($this->_attributes[$key]['name'] == $name) {
292
+        foreach ($keys as $key)
293
+        {
294
+            if ($this->_attributes[$key]['name'] == $name)
295
+            {
267 296
                 unset($this->_attributes[$key]);
268 297
             }
269 298
         }
@@ -279,12 +308,15 @@  discard block
 block discarded – undo
279 308
      */
280 309
     function getAllAttributes($tag = false)
281 310
     {
282
-        if ($tag === false) {
311
+        if ($tag === false)
312
+        {
283 313
             return $this->_attributes;
284 314
         }
285 315
         $result = array();
286
-        foreach ($this->_attributes as $attribute) {
287
-            if ($attribute['name'] == $tag) {
316
+        foreach ($this->_attributes as $attribute)
317
+        {
318
+            if ($attribute['name'] == $tag)
319
+            {
288 320
                 $result[] = $attribute;
289 321
             }
290 322
         }
@@ -298,7 +330,8 @@  discard block
 block discarded – undo
298 330
      */
299 331
     function addComponent($component)
300 332
     {
301
-        if (is_a($component, 'Horde_iCalendar')) {
333
+        if (is_a($component, 'Horde_iCalendar'))
334
+        {
302 335
             $component->_container = &$this;
303 336
             $this->_components[] = &$component;
304 337
         }
@@ -328,11 +361,15 @@  discard block
 block discarded – undo
328 361
     function getComponentClasses()
329 362
     {
330 363
         $r = array();
331
-        foreach ($this->_components as $c) {
364
+        foreach ($this->_components as $c)
365
+        {
332 366
             $cn = strtolower(get_class($c));
333
-            if (empty($r[$cn])) {
367
+            if (empty($r[$cn]))
368
+            {
334 369
                 $r[$cn] = 1;
335
-            } else {
370
+            }
371
+            else
372
+            {
336 373
                 $r[$cn]++;
337 374
             }
338 375
         }
@@ -360,9 +397,12 @@  discard block
 block discarded – undo
360 397
      */
361 398
     function getComponent($idx)
362 399
     {
363
-        if (isset($this->_components[$idx])) {
400
+        if (isset($this->_components[$idx]))
401
+        {
364 402
             return $this->_components[$idx];
365
-        } else {
403
+        }
404
+        else
405
+        {
366 406
             return false;
367 407
         }
368 408
     }
@@ -381,8 +421,10 @@  discard block
 block discarded – undo
381 421
     {
382 422
         $childclass = 'Horde_iCalendar_' . String::lower($childclass);
383 423
         $keys = array_keys($this->_components);
384
-        foreach ($keys as $key) {
385
-            if (is_a($this->_components[$key], $childclass)) {
424
+        foreach ($keys as $key)
425
+        {
426
+            if (is_a($this->_components[$key], $childclass))
427
+            {
386 428
                 return $this->_components[$key];
387 429
             }
388 430
         }
@@ -408,13 +450,17 @@  discard block
 block discarded – undo
408 450
     {
409 451
         $childclass = 'Horde_iCalendar_' . String::lower($childclass);
410 452
         $keys = array_keys($this->_components);
411
-        foreach ($keys as $key) {
412
-            if (is_a($this->_components[$key], $childclass)) {
453
+        foreach ($keys as $key)
454
+        {
455
+            if (is_a($this->_components[$key], $childclass))
456
+            {
413 457
                 $attr = $this->_components[$key]->getAttribute($attribute);
414
-                if (is_a($attr, 'PEAR_Error')) {
458
+                if (is_a($attr, 'PEAR_Error'))
459
+                {
415 460
                     continue;
416 461
                 }
417
-                if ($value !== null && $value != $attr) {
462
+                if ($value !== null && $value != $attr)
463
+                {
418 464
                     continue;
419 465
                 }
420 466
                 return $this->_components[$key];
@@ -447,7 +493,8 @@  discard block
 block discarded – undo
447 493
     function isOldFormat()
448 494
     {
449 495
 	$retval = true;
450
-	switch ($this->getType()) {
496
+	switch ($this->getType())
497
+	{
451 498
 		case 'vcard':
452 499
             		$retval = ($this->_version < 3);
453 500
 			break;
@@ -474,8 +521,10 @@  discard block
 block discarded – undo
474 521
         // METHOD is only required for iTip, but not for CalDAV, therefore removing it here calendar_ical sets it anyway by default
475 522
         //$requiredAttributes['METHOD'] = 'PUBLISH';
476 523
 
477
-        foreach ($requiredAttributes as $name => $default_value) {
478
-            if (is_a($this->getattribute($name), 'PEAR_Error')) {
524
+        foreach ($requiredAttributes as $name => $default_value)
525
+        {
526
+            if (is_a($this->getattribute($name), 'PEAR_Error'))
527
+            {
479 528
                 $this->setAttribute($name, $default_value);
480 529
             }
481 530
         }
@@ -499,10 +548,13 @@  discard block
 block discarded – undo
499 548
     function toHash($paramsInKeys = false)
500 549
     {
501 550
         $hash = array();
502
-        foreach ($this->_attributes as $a)  {
551
+        foreach ($this->_attributes as $a)
552
+        {
503 553
             $k = $a['name'];
504
-            if ($paramsInKeys && is_array($a['params'])) {
505
-                foreach ($a['params'] as $p => $v) {
554
+            if ($paramsInKeys && is_array($a['params']))
555
+            {
556
+                foreach ($a['params'] as $p => $v)
557
+                {
506 558
                     $k .= ";$p=$v";
507 559
                 }
508 560
             }
@@ -527,28 +579,35 @@  discard block
 block discarded – undo
527 579
      */
528 580
     function parsevCalendar($text, $base = 'VCALENDAR', $charset = null, $clear = true)
529 581
     {
530
-        if ($clear) {
582
+        if ($clear)
583
+        {
531 584
             $this->clear();
532 585
         }
533 586
 
534 587
         if ($base == 'VTODO' &&
535
-        	preg_match('/^BEGIN:VTODO(.*)^END:VEVENT/ism', $text, $matches)) {
588
+        	preg_match('/^BEGIN:VTODO(.*)^END:VEVENT/ism', $text, $matches))
589
+        {
536 590
         	// Workaround for Funambol VTODO bug in Mozilla Sync Plugins
537 591
         	Horde::logMessage('iCalendar: Funambol VTODO-bug detected, workaround activated...',
538 592
         		__FILE__, __LINE__, PEAR_LOG_WARNING);
539 593
             $container = true;
540 594
             $vCal = $matches[1];
541
-        } elseif (preg_match('/^BEGIN:' . $base . '(.*)^END:' . $base . '/ism', $text, $matches)) {
595
+        }
596
+        elseif (preg_match('/^BEGIN:' . $base . '(.*)^END:' . $base . '/ism', $text, $matches))
597
+        {
542 598
             $container = true;
543 599
             $vCal = $matches[1];
544
-        } else {
600
+        }
601
+        else
602
+        {
545 603
             // Text isn't enclosed in BEGIN:VCALENDAR
546 604
             // .. END:VCALENDAR. We'll try to parse it anyway.
547 605
             $container = false;
548 606
             $vCal = $text;
549 607
         }
550 608
 
551
-        if (preg_match('/^VERSION:(\d\.\d)\s*$/ism', $vCal, $matches)) {
609
+        if (preg_match('/^VERSION:(\d\.\d)\s*$/ism', $vCal, $matches))
610
+        {
552 611
             // define the version asap
553 612
             #Horde::logMessage("iCalendar VERSION:" . $matches[1], __FILE__, __LINE__, PEAR_LOG_DEBUG);
554 613
             $this->setAttribute('VERSION', $matches[1]);
@@ -561,16 +620,20 @@  discard block
 block discarded – undo
561 620
         $matches = null;
562 621
         // Workaround for Funambol VTODO bug in Mozilla Sync Plugins
563 622
         if (preg_match_all('/^BEGIN:(VTODO)(\r\n|\r|\n)(.*)^END:VEVENT/Uims', $vCal, $matches) ||
564
-        	preg_match_all('/^BEGIN:(.*)(\r\n|\r|\n)(.*)^END:\1/Uims', $vCal, $matches)) {
623
+        	preg_match_all('/^BEGIN:(.*)(\r\n|\r|\n)(.*)^END:\1/Uims', $vCal, $matches))
624
+        {
565 625
             // vTimezone components are processed first. They are
566 626
             // needed to process vEvents that may use a TZID.
567
-            foreach ($matches[0] as $key => $data) {
627
+            foreach ($matches[0] as $key => $data)
628
+            {
568 629
                 $type = trim($matches[1][$key]);
569
-                if ($type != 'VTIMEZONE') {
630
+                if ($type != 'VTIMEZONE')
631
+                {
570 632
                     continue;
571 633
                 }
572 634
                 $component = &Horde_iCalendar::newComponent($type, $this);
573
-                if ($component === false) {
635
+                if ($component === false)
636
+                {
574 637
                     return PEAR::raiseError("Unable to create object for type $type");
575 638
                 }
576 639
                 $component->parsevCalendar($data, $type, $charset);
@@ -582,13 +645,16 @@  discard block
 block discarded – undo
582 645
             }
583 646
 
584 647
             // Now process the non-vTimezone components.
585
-            foreach ($matches[0] as $key => $data) {
648
+            foreach ($matches[0] as $key => $data)
649
+            {
586 650
                 $type = trim($matches[1][$key]);
587
-                if ($type == 'VTIMEZONE') {
651
+                if ($type == 'VTIMEZONE')
652
+                {
588 653
                     continue;
589 654
                 }
590 655
                 $component = &Horde_iCalendar::newComponent($type, $this);
591
-                if ($component === false) {
656
+                if ($component === false)
657
+                {
592 658
                     return PEAR::raiseError("Unable to create object for type $type");
593 659
                 }
594 660
                 $component->parsevCalendar($data, $type, $charset);
@@ -598,7 +664,9 @@  discard block
 block discarded – undo
598 664
                 // Remove from the vCalendar data.
599 665
                 $vCal = str_replace($data, '', $vCal);
600 666
             }
601
-        } elseif (!$container) {
667
+        }
668
+        elseif (!$container)
669
+        {
602 670
             return false;
603 671
         }
604 672
 
@@ -606,11 +674,16 @@  discard block
 block discarded – undo
606 674
         //  BODY;ENCODING=QUOTED-PRINTABLE:=
607 675
         //  another=20line=
608 676
         //  last=20line
609
-        while (preg_match_all('/^([^:]+;\s*((ENCODING=)?QUOTED-PRINTABLE|ENCODING=[Q|q])(.*=\r?\n)+(.*[^=])?\r?\n)/mU', $vCal, $matches)) {
610
-            foreach ($matches[1] as $s) {
611
-            	if ($this->isOldFormat()) {
677
+        while (preg_match_all('/^([^:]+;\s*((ENCODING=)?QUOTED-PRINTABLE|ENCODING=[Q|q])(.*=\r?\n)+(.*[^=])?\r?\n)/mU', $vCal, $matches))
678
+        {
679
+            foreach ($matches[1] as $s)
680
+            {
681
+            	if ($this->isOldFormat())
682
+            	{
612 683
                 	$r = preg_replace('/=\r?\n([ \t])?/', '\1', $s);
613
-            	} else {
684
+            	}
685
+            	else
686
+            	{
614 687
             		$r = preg_replace('/=\r?\n[ \t]*/', '', $s);
615 688
             	}
616 689
                 $vCal = str_replace($s, $r, $vCal);
@@ -618,63 +691,85 @@  discard block
 block discarded – undo
618 691
         }
619 692
 
620 693
         // Unfold any folded lines.
621
-        if ($this->isOldFormat()) {
694
+        if ($this->isOldFormat())
695
+        {
622 696
         	// old formats force folding at whitespace which must therefore be preserved
623 697
         	$vCal = preg_replace('/[\r\n]+([ \t])/', '\1', $vCal);
624
-        } else {
698
+        }
699
+        else
700
+        {
625 701
         	$vCal = preg_replace('/[\r\n]+[ \t]/', '', $vCal);
626 702
         }
627 703
 
628 704
 		$isDate = false;
629 705
 
630 706
         // Parse the remaining attributes.
631
-        if (preg_match_all('/^((?:[^":]+|(?:"[^"]*")+)*):([^\r\n]*)\r?$/m', $vCal, $matches)) {
632
-            foreach ($matches[0] as $attribute) {
707
+        if (preg_match_all('/^((?:[^":]+|(?:"[^"]*")+)*):([^\r\n]*)\r?$/m', $vCal, $matches))
708
+        {
709
+            foreach ($matches[0] as $attribute)
710
+            {
633 711
                 preg_match('/([^:;]*)((;(?:(?:[^":\\\]*(?:\\\.)?)+|(?:"[^"]*")+)*)?):([^\r\n]*)[\r\n]*/', $attribute, $parts);
634 712
                 $tag = trim(String::upper($parts[1]));
635 713
                 $value = $parts[4];
636 714
                 $params = array();
637 715
 
638 716
                 // Parse parameters.
639
-                if (!empty($parts[2])) {
717
+                if (!empty($parts[2]))
718
+                {
640 719
                     preg_match_all('/;(([^;=]*)(=("[^"]*"|(?:[^;\\\]*(?:\\\.)?)*))?)/', $parts[2], $param_parts);
641
-                    foreach ($param_parts[2] as $key => $paramName) {
720
+                    foreach ($param_parts[2] as $key => $paramName)
721
+                    {
642 722
                         $paramName = String::upper($paramName);
643 723
                         $paramValue = $param_parts[4][$key];
644
-                        if ($paramName == 'TYPE') {
724
+                        if ($paramName == 'TYPE')
725
+                        {
645 726
                             $paramValue = preg_split('/(?<!\\\\),/', $paramValue);
646
-                            if (isset($params[$paramName])) {
647
-                        		if (!is_array($params[$paramName])) {
727
+                            if (isset($params[$paramName]))
728
+                            {
729
+                        		if (!is_array($params[$paramName]))
730
+                        		{
648 731
                         			$params[$paramName] = array($params[$paramName]);
649 732
                         		}
650 733
                         		$params[$paramName] = array_merge($params[$paramName], $paramValue);
651
-                        	} else {
652
-                        		if (count($paramValue) == 1) {
734
+                        	}
735
+                        	else
736
+                        	{
737
+                        		if (count($paramValue) == 1)
738
+                        		{
653 739
                                 	$paramValue = $paramValue[0];
654 740
                             	}
655 741
                             	$params[$paramName] = $paramValue;
656 742
                         	}
657
-                        } else {
743
+                        }
744
+                        else
745
+                        {
658 746
                         	$params[$paramName] = $paramValue;
659 747
                         }
660 748
                     }
661 749
                 }
662 750
 
663 751
                 // Charset and encoding handling.
664
-                if (isset($params['QUOTED-PRINTABLE'])) {
752
+                if (isset($params['QUOTED-PRINTABLE']))
753
+                {
665 754
 	                $params['ENCODING'] = 'QUOTED-PRINTABLE';
666 755
                 }
667
-                if (isset($params['BASE64'])) {
756
+                if (isset($params['BASE64']))
757
+                {
668 758
 	                $params['ENCODING'] = 'BASE64';
669 759
                 }
670
-                if (isset($params['ENCODING'])) {
671
-	                switch (String::upper($params['ENCODING'])) {
760
+                if (isset($params['ENCODING']))
761
+                {
762
+	                switch (String::upper($params['ENCODING']))
763
+	                {
672 764
 		                case 'Q':
673 765
 		                case 'QUOTED-PRINTABLE':
674 766
 			                $value = quoted_printable_decode($value);
675
-			                if (isset($params['CHARSET'])) {
767
+			                if (isset($params['CHARSET']))
768
+			                {
676 769
 				                $value = $GLOBALS['egw']->translation->convert($value, $params['CHARSET']);
677
-			                } else {
770
+			                }
771
+			                else
772
+			                {
678 773
 				                $value = $GLOBALS['egw']->translation->convert($value,
679 774
 					                empty($charset) ? ($this->isOldFormat() ? 'iso-8859-1' : 'utf-8') : $charset);
680 775
 			                }
@@ -686,9 +781,13 @@  discard block
 block discarded – undo
686 781
 			                $value = base64_decode($value);
687 782
 			                break;
688 783
 	                }
689
-                } elseif (isset($params['CHARSET'])) {
784
+                }
785
+                elseif (isset($params['CHARSET']))
786
+                {
690 787
 	                $value = $GLOBALS['egw']->translation->convert($value, $params['CHARSET']);
691
-                } else {
788
+                }
789
+                else
790
+                {
692 791
 	                // As per RFC 2279, assume UTF8 if we don't have an
693 792
 	                // explicit charset parameter.
694 793
 	                $value = $GLOBALS['egw']->translation->convert($value,
@@ -698,7 +797,8 @@  discard block
 block discarded – undo
698 797
                 // Get timezone info for date fields from $params.
699 798
                 $tzid = isset($params['TZID']) ? trim($params['TZID'], '\"') : false;
700 799
 
701
-                switch ($tag) {
800
+                switch ($tag)
801
+                {
702 802
 	                case 'VERSION': // already processed
703 803
 		                break;
704 804
 		                // Date fields.
@@ -724,22 +824,31 @@  discard block
 block discarded – undo
724 824
 		                // types like AALARM may contain additional data after a ;
725 825
 		                // ignore these.
726 826
 		                $ts = explode(';', $value);
727
-		                if (isset($params['VALUE']) && $params['VALUE'] == 'DATE') {
827
+		                if (isset($params['VALUE']) && $params['VALUE'] == 'DATE')
828
+		                {
728 829
 			                $isDate = true;
729 830
 			                $this->setAttribute($tag, $this->_parseDateTime($ts[0], $tzid), $params, true, $this->_parseDate($ts[0]));
730
-		                } else {
831
+		                }
832
+		                else
833
+		                {
731 834
 			                $this->setAttribute($tag, $this->_parseDateTime($ts[0], $tzid), $params);
732 835
 		                }
733 836
 		                break;
734 837
 
735 838
 	                case 'TRIGGER':
736
-		                if (isset($params['VALUE'])) {
737
-			                if ($params['VALUE'] == 'DATE-TIME') {
839
+		                if (isset($params['VALUE']))
840
+		                {
841
+			                if ($params['VALUE'] == 'DATE-TIME')
842
+			                {
738 843
 				                $this->setAttribute($tag, $this->_parseDateTime($value, $tzid), $params);
739
-			                } else {
844
+			                }
845
+			                else
846
+			                {
740 847
 				                $this->setAttribute($tag, $this->_parseDuration($value), $params);
741 848
 			                }
742
-		                } else {
849
+		                }
850
+		                else
851
+		                {
743 852
 			                $this->setAttribute($tag, $this->_parseDuration($value), $params);
744 853
 		                }
745 854
 		                break;
@@ -750,11 +859,15 @@  discard block
 block discarded – undo
750 859
 		                $dates = array();
751 860
 		                preg_match_all('/[;,]([^;,]*)/', ';' . $value, $values);
752 861
 
753
-		                foreach ($values[1] as $value) {
862
+		                foreach ($values[1] as $value)
863
+		                {
754 864
 			                if ((isset($params['VALUE'])
755
-					                && $params['VALUE'] == 'DATE') || (!isset($params['VALUE']) && $isDate)) {
865
+					                && $params['VALUE'] == 'DATE') || (!isset($params['VALUE']) && $isDate))
866
+			                {
756 867
 				                $dates[] = $this->_parseDate(trim($value));
757
-			                } else {
868
+			                }
869
+			                else
870
+			                {
758 871
 				                $dates[] = $this->_parseDateTime(trim($value), $tzid);
759 872
 			                }
760 873
 		                }
@@ -770,7 +883,8 @@  discard block
 block discarded – undo
770 883
 	                case 'FREEBUSY':
771 884
 		                $periods = array();
772 885
 		                preg_match_all('/,([^,]*)/', ',' . $value, $values);
773
-		                foreach ($values[1] as $value) {
886
+		                foreach ($values[1] as $value)
887
+		                {
774 888
 			                $periods[] = $this->_parsePeriod($value);
775 889
 		                }
776 890
 
@@ -793,11 +907,14 @@  discard block
 block discarded – undo
793 907
 
794 908
 		                // Geo fields.
795 909
 	                case 'GEO':
796
-		                if ($this->isOldFormat()) {
910
+		                if ($this->isOldFormat())
911
+		                {
797 912
 			                $floats = explode(',', $value);
798 913
 			                $value = array('latitude' => floatval($floats[1]),
799 914
 				                'longitude' => floatval($floats[0]));
800
-		                } else {
915
+		                }
916
+		                else
917
+		                {
801 918
 			                $floats = explode(';', $value);
802 919
 			                $value = array('latitude' => floatval($floats[0]),
803 920
 				                'longitude' => floatval($floats[1]));
@@ -854,7 +971,8 @@  discard block
 block discarded – undo
854 971
 
855 972
 		                // String fields.
856 973
 	                default:
857
-		                if ($this->isOldFormat()) {
974
+		                if ($this->isOldFormat())
975
+		                {
858 976
 			                $value = trim($value);
859 977
 			                // vCalendar 1.0 and vCard 2.1 only escape semicolons
860 978
 			                // and use unescaped semicolons to create lists.
@@ -867,7 +985,9 @@  discard block
 block discarded – undo
867 985
 			                $value = str_replace('\\;', ';', $value);
868 986
 			                $values = str_replace('\\;', ';', $values);
869 987
 			                $this->setAttribute($tag, trim($value), $params, true, $values);
870
-		                } else {
988
+		                }
989
+		                else
990
+		                {
871 991
 			                $value = trim($value);
872 992
 			                // As of rfc 2426 2.4.2 semicolon, comma, and colon
873 993
 			                // must be escaped (comma is unescaped after splitting
@@ -909,58 +1029,78 @@  discard block
 block discarded – undo
909 1029
         // as it is part of the enclosing VCALENDAR/ICALENDAR. See rfc2445
910 1030
         if ($base !== 'VEVENT' && $base !== 'VTODO' && $base !== 'VALARM' &&
911 1031
             $base !== 'VJOURNAL' && $base !== 'VFREEBUSY' &&
912
-            $base !== 'VTIMEZONE' && $base !== 'STANDARD' && $base != 'DAYLIGHT') {
1032
+            $base !== 'VTIMEZONE' && $base !== 'STANDARD' && $base != 'DAYLIGHT')
1033
+        {
913 1034
             // Ensure that version is the first attribute.
914 1035
             $result .= 'VERSION:' . $this->_version . $this->_newline;
915 1036
         }
916 1037
 
917
-        if (empty($charset)) {
918
-        	if ($this->isOldFormat()) {
1038
+        if (empty($charset))
1039
+        {
1040
+        	if ($this->isOldFormat())
1041
+        	{
919 1042
         		$charset = NLS::getCharset();
920
-        	} else {
1043
+        	}
1044
+        	else
1045
+        	{
921 1046
         		$charset = 'utf-8';
922 1047
         	}
923 1048
         }
924 1049
 
925
-        foreach ($this->_attributes as $attribute) {
1050
+        foreach ($this->_attributes as $attribute)
1051
+        {
926 1052
             $name = $attribute['name'];
927
-            if ($name == 'VERSION') {
1053
+            if ($name == 'VERSION')
1054
+            {
928 1055
                 // Already done.
929 1056
                 continue;
930 1057
             }
931 1058
 
932 1059
             $params_str = '';
933 1060
             $params = $attribute['params'];
934
-            if ($params) {
935
-                foreach ($params as $param_name => $param_value) {
1061
+            if ($params)
1062
+            {
1063
+                foreach ($params as $param_name => $param_value)
1064
+                {
936 1065
                     /* Skip CHARSET for iCalendar 2.0 data, not allowed. */
937
-                    if ($param_name == 'CHARSET') {
938
-                    	if (!$this->isOldFormat() || empty($param_value)) {
1066
+                    if ($param_name == 'CHARSET')
1067
+                    {
1068
+                    	if (!$this->isOldFormat() || empty($param_value))
1069
+                    	{
939 1070
                         	continue;
940
-                    	} else {
1071
+                    	}
1072
+                    	else
1073
+                    	{
941 1074
                     		$param_value = String::Upper($param_value);
942 1075
                     	}
943 1076
                     }
944
-                    if ($param_name == 'ENCODING') {
1077
+                    if ($param_name == 'ENCODING')
1078
+                    {
945 1079
                     	continue;
946 1080
                     }
947 1081
                     /* Skip VALUE=DATE for vCalendar 1.0 data, not allowed. */
948 1082
                     if ($this->isOldFormat() &&
949
-                        $param_name == 'VALUE' && $param_value == 'DATE') {
1083
+                        $param_name == 'VALUE' && $param_value == 'DATE')
1084
+                    {
950 1085
                         continue;
951 1086
                     }
952 1087
                     /* Skip TZID for iCalendar 1.0 data, not supported. */
953
-					if ($this->isOldFormat() && $param_name == 'TZID') {
1088
+					if ($this->isOldFormat() && $param_name == 'TZID')
1089
+					{
954 1090
                         continue;
955 1091
                     }
956 1092
                     // Skip CN in ATTENDEE adn ORGANIZER for vCalendar 1.0
957 1093
                     if ($this->isOldFormat() && $param_name == 'CN' &&
958
-                    	($name == 'ATTENDEE' || $name == 'ORGANIZER')) {
1094
+                    	($name == 'ATTENDEE' || $name == 'ORGANIZER'))
1095
+                    {
959 1096
                     	continue;
960 1097
                     }
961
-                    if ($param_value === null) {
1098
+                    if ($param_value === null)
1099
+                    {
962 1100
                         $params_str .= ";$param_name";
963
-                    } else {
1101
+                    }
1102
+                    else
1103
+                    {
964 1104
                         $params_str .= ";$param_name=$param_value";
965 1105
                     }
966 1106
                 }
@@ -968,7 +1108,8 @@  discard block
 block discarded – undo
968 1108
 
969 1109
             $value = $attribute['value'];
970 1110
 
971
-            switch ($name) {
1111
+            switch ($name)
1112
+            {
972 1113
             // Date fields.
973 1114
             case 'COMPLETED':
974 1115
             case 'CREATED':
@@ -980,10 +1121,13 @@  discard block
 block discarded – undo
980 1121
 			// Support additional fields after date.
981 1122
  			case 'AALARM':
982 1123
             case 'DALARM':
983
-            	if (isset($params['VALUE'])) {
984
-                    if ($params['VALUE'] == 'DATE') {
1124
+            	if (isset($params['VALUE']))
1125
+            	{
1126
+                    if ($params['VALUE'] == 'DATE')
1127
+                    {
985 1128
                         // VCALENDAR 1.0 uses T000000 - T235959 for all day events:
986
-                        if ($this->isOldFormat() && $name == 'DTEND') {
1129
+                        if ($this->isOldFormat() && $name == 'DTEND')
1130
+                        {
987 1131
                             $d = new Horde_Date($value);
988 1132
                             $value = new Horde_Date(array(
989 1133
                                 'year' => $d->year,
@@ -991,22 +1135,32 @@  discard block
 block discarded – undo
991 1135
                                 'mday' => $d->mday - 1));
992 1136
                             $value->correct();
993 1137
                             $value = $this->_exportDate($value, '235959');
994
-                        } else {
1138
+                        }
1139
+                        else
1140
+                        {
995 1141
                             $value = $this->_exportDate($value, '000000');
996 1142
                         }
997
-                    } else {
1143
+                    }
1144
+                    else
1145
+                    {
998 1146
                         $value = $this->_exportDateTime($value);
999 1147
                     }
1000
-                } else {
1148
+                }
1149
+                else
1150
+                {
1001 1151
                     $value = $this->_exportDateTime($value);
1002 1152
                 }
1003 1153
 
1004 1154
             	if (is_array($attribute['values']) &&
1005
-		            	count($attribute['values']) > 0) {
1155
+		            	count($attribute['values']) > 0)
1156
+            	{
1006 1157
 		            $values = $attribute['values'];
1007
-	            	if ($this->isOldFormat()) {
1158
+	            	if ($this->isOldFormat())
1159
+	            	{
1008 1160
 		            	$values = str_replace(';', '\\;', $values);
1009
-	            	} else {
1161
+	            	}
1162
+	            	else
1163
+	            	{
1010 1164
                         // As of rfc 2426 2.5 semicolon and comma must be
1011 1165
                         // escaped.
1012 1166
                         $values = str_replace(array('\\', ';', ','),
@@ -1024,10 +1178,13 @@  discard block
 block discarded – undo
1024 1178
             case 'DUE':
1025 1179
             case 'RECURRENCE-ID':
1026 1180
             case 'X-RECURRENCE-ID':
1027
-                if (isset($params['VALUE'])) {
1028
-                    if ($params['VALUE'] == 'DATE') {
1181
+                if (isset($params['VALUE']))
1182
+                {
1183
+                    if ($params['VALUE'] == 'DATE')
1184
+                    {
1029 1185
                         // VCALENDAR 1.0 uses T000000 - T235959 for all day events:
1030
-                        if ($this->isOldFormat() && $name == 'DTEND') {
1186
+                        if ($this->isOldFormat() && $name == 'DTEND')
1187
+                        {
1031 1188
                             $d = new Horde_Date($value);
1032 1189
                             $value = new Horde_Date(array(
1033 1190
                                 'year' => $d->year,
@@ -1035,13 +1192,19 @@  discard block
 block discarded – undo
1035 1192
                                 'mday' => $d->mday - 1));
1036 1193
                             $value->correct();
1037 1194
                             $value = $this->_exportDate($value, '235959');
1038
-                        } else {
1195
+                        }
1196
+                        else
1197
+                        {
1039 1198
                             $value = $this->_exportDate($value, '000000');
1040 1199
                         }
1041
-                    } else {
1200
+                    }
1201
+                    else
1202
+                    {
1042 1203
                         $value = $this->_exportDateTime($value);
1043 1204
                     }
1044
-                } else {
1205
+                }
1206
+                else
1207
+                {
1045 1208
                     $value = $this->_exportDateTime($value);
1046 1209
                 }
1047 1210
                 break;
@@ -1049,46 +1212,72 @@  discard block
 block discarded – undo
1049 1212
             // Comma or semicolon seperated dates.
1050 1213
             case 'EXDATE':
1051 1214
             case 'RDATE':
1052
-	            if (is_array($attribute['values'])) {
1215
+	            if (is_array($attribute['values']))
1216
+	            {
1053 1217
 		            $values = $attribute['values'];
1054
-	            } elseif (!empty($value)) {
1055
-	            	if ($this->isOldFormat()) {
1218
+	            }
1219
+	            elseif (!empty($value))
1220
+	            {
1221
+	            	if ($this->isOldFormat())
1222
+	            	{
1056 1223
 		            	$values = explode(';', $value);
1057
-	            	} else {
1224
+	            	}
1225
+	            	else
1226
+	            	{
1058 1227
 	            		$values = explode(',', $value);
1059 1228
 	            	}
1060
-	            } else {
1229
+	            }
1230
+	            else
1231
+	            {
1061 1232
 		            break;
1062 1233
 	            }
1063 1234
                 $dates = array();
1064
-                foreach ($values as $date) {
1065
-                    if (isset($params['VALUE'])) {
1066
-                        if ($params['VALUE'] == 'DATE') {
1235
+                foreach ($values as $date)
1236
+                {
1237
+                    if (isset($params['VALUE']))
1238
+                    {
1239
+                        if ($params['VALUE'] == 'DATE')
1240
+                        {
1067 1241
                             $dates[] = $this->_exportDate($date, '000000');
1068
-                        } elseif ($params['VALUE'] == 'PERIOD') {
1242
+                        }
1243
+                        elseif ($params['VALUE'] == 'PERIOD')
1244
+                        {
1069 1245
                             $dates[] = $this->_exportPeriod($date);
1070
-                        } else {
1246
+                        }
1247
+                        else
1248
+                        {
1071 1249
                             $dates[] = $this->_exportDateTime($date);
1072 1250
                         }
1073
-                    } else {
1251
+                    }
1252
+                    else
1253
+                    {
1074 1254
                         $dates[] = $this->_exportDateTime($date);
1075 1255
                     }
1076 1256
                 }
1077
-                if ($this->isOldFormat()) {
1257
+                if ($this->isOldFormat())
1258
+                {
1078 1259
 	                $value = implode(';', $dates);
1079
-                } else {
1260
+                }
1261
+                else
1262
+                {
1080 1263
 	                $value = implode(',', $dates);
1081 1264
                 }
1082 1265
                 break;
1083 1266
 
1084 1267
             case 'TRIGGER':
1085
-                if (isset($params['VALUE'])) {
1086
-                    if ($params['VALUE'] == 'DATE-TIME') {
1268
+                if (isset($params['VALUE']))
1269
+                {
1270
+                    if ($params['VALUE'] == 'DATE-TIME')
1271
+                    {
1087 1272
                         $value = $this->_exportDateTime($value);
1088
-                    } elseif ($params['VALUE'] == 'DURATION') {
1273
+                    }
1274
+                    elseif ($params['VALUE'] == 'DURATION')
1275
+                    {
1089 1276
                         $value = $this->_exportDuration($value);
1090 1277
                     }
1091
-                } else {
1278
+                }
1279
+                else
1280
+                {
1092 1281
                     $value = $this->_exportDuration($value);
1093 1282
                 }
1094 1283
                 break;
@@ -1101,7 +1290,8 @@  discard block
 block discarded – undo
1101 1290
             // Period of time fields.
1102 1291
             case 'FREEBUSY':
1103 1292
                 $value_str = '';
1104
-                foreach ($value as $period) {
1293
+                foreach ($value as $period)
1294
+                {
1105 1295
                     $value_str .= empty($value_str) ? '' : ',';
1106 1296
                     $value_str .= $this->_exportPeriod($period);
1107 1297
                 }
@@ -1124,9 +1314,12 @@  discard block
 block discarded – undo
1124 1314
 
1125 1315
             // Geo fields.
1126 1316
             case 'GEO':
1127
-                if ($this->isOldFormat()) {
1317
+                if ($this->isOldFormat())
1318
+                {
1128 1319
                     $value = $value['longitude'] . ',' . $value['latitude'];
1129
-                } else {
1320
+                }
1321
+                else
1322
+                {
1130 1323
                     $value = $value['latitude'] . ';' . $value['longitude'];
1131 1324
                 }
1132 1325
                 break;
@@ -1147,18 +1340,25 @@  discard block
 block discarded – undo
1147 1340
                 break;
1148 1341
 
1149 1342
             default:
1150
-                if ($this->isOldFormat()) {
1343
+                if ($this->isOldFormat())
1344
+                {
1151 1345
                     if (is_array($attribute['values']) &&
1152
-                        count($attribute['values']) > 1) {
1346
+                        count($attribute['values']) > 1)
1347
+                    {
1153 1348
                         $values = $attribute['values'];
1154
-                        if ($name == 'N' || $name == 'ADR' || $name == 'ORG') {
1349
+                        if ($name == 'N' || $name == 'ADR' || $name == 'ORG')
1350
+                        {
1155 1351
                             $glue = ';';
1156
-                        } else {
1352
+                        }
1353
+                        else
1354
+                        {
1157 1355
                             $glue = ',';
1158 1356
                         }
1159 1357
                         $values = str_replace(';', '\\;', $values);
1160 1358
                         $value = implode($glue, $values);
1161
-                    } else {
1359
+                    }
1360
+                    else
1361
+                    {
1162 1362
                         /* vcard 2.1 and vcalendar 1.0 escape only
1163 1363
                          * semicolons */
1164 1364
                         $value = str_replace(';', '\\;', $value);
@@ -1167,23 +1367,31 @@  discard block
 block discarded – undo
1167 1367
                     // or QUOTED-PRINTABLE encoded. Currently we use
1168 1368
                     // QUOTED-PRINTABLE as default.
1169 1369
                     if (preg_match('/[^\x20-\x7F]/', $value) &&
1170
-		                    !isset($params['ENCODING']))  {
1370
+		                    !isset($params['ENCODING']))
1371
+                    {
1171 1372
 	                    $params['ENCODING'] = 'QUOTED-PRINTABLE';
1172 1373
                     }
1173 1374
                     if (preg_match('/([\177-\377])/', $value) &&
1174
-		                    !isset($params['CHARSET'])) {
1375
+		                    !isset($params['CHARSET']))
1376
+                    {
1175 1377
 	                    // Add CHARSET as well. At least the synthesis client
1176 1378
 	                    // gets confused otherwise
1177 1379
 	                    $params['CHARSET'] = String::upper($charset);
1178 1380
 	                    $params_str .= ';CHARSET=' . $params['CHARSET'];
1179 1381
                     }
1180
-                } else {
1382
+                }
1383
+                else
1384
+                {
1181 1385
                     if (is_array($attribute['values']) &&
1182
-                        count($attribute['values']) > 1) {
1386
+                        count($attribute['values']) > 1)
1387
+                    {
1183 1388
                         $values = $attribute['values'];
1184
-                        if ($name == 'N' || $name == 'ADR' || $name == 'ORG') {
1389
+                        if ($name == 'N' || $name == 'ADR' || $name == 'ORG')
1390
+                        {
1185 1391
                             $glue = ';';
1186
-                        } else {
1392
+                        }
1393
+                        else
1394
+                        {
1187 1395
                             $glue = ',';
1188 1396
                         }
1189 1397
                         // As of rfc 2426 2.5 semicolon and comma must be
@@ -1192,7 +1400,9 @@  discard block
 block discarded – undo
1192 1400
                                               array('\\\\', '\\;', '\\,'),
1193 1401
                                               $values);
1194 1402
                         $value = implode($glue, $values);
1195
-                    } else {
1403
+                    }
1404
+                    else
1405
+                    {
1196 1406
                         // As of rfc 2426 2.5 semicolon and comma must be
1197 1407
                         // escaped.
1198 1408
                         $value = str_replace(array('\\', ';', ','),
@@ -1205,8 +1415,10 @@  discard block
 block discarded – undo
1205 1415
 
1206 1416
 			$encoding = (!empty($params['ENCODING']) && strlen(trim($value)) > 0);
1207 1417
 
1208
-            if ($encoding) {
1209
-	            switch($params['ENCODING']) {
1418
+            if ($encoding)
1419
+            {
1420
+	            switch($params['ENCODING'])
1421
+	            {
1210 1422
 		            case 'Q':
1211 1423
 		            case 'QUOTED-PRINTABLE':
1212 1424
 		            	if (!$this->isOldFormat())
@@ -1247,21 +1459,27 @@  discard block
 block discarded – undo
1247 1459
 				            true, 'utf-8', true); // charset does not matter
1248 1460
 			            $result .= $attr_string . $this->_newline;
1249 1461
 			            */
1250
-			            if ($this->isOldFormat()) {
1462
+			            if ($this->isOldFormat())
1463
+			            {
1251 1464
 				            $result .= $this->_newline; // Append an empty line
1252 1465
 			            }
1253 1466
 	            }
1254 1467
             }
1255 1468
 
1256
-            if (!$encoding) {
1469
+            if (!$encoding)
1470
+            {
1257 1471
                 $value = str_replace(array("\r", "\n"), array('', '\\n'), $value);
1258 1472
                 $attr_string = $name . $params_str;
1259
-                if (strlen($value) > 0) {
1473
+                if (strlen($value) > 0)
1474
+                {
1260 1475
                 	$attr_string .= ':' . $value;
1261
-                } elseif ($name != 'RRULE') {
1476
+                }
1477
+                elseif ($name != 'RRULE')
1478
+                {
1262 1479
                 	$attr_string .= ':';
1263 1480
                 }
1264
-                if (!$this->isOldFormat()) {
1481
+                if (!$this->isOldFormat())
1482
+                {
1265 1483
                     $attr_string = String::wordwrap($attr_string, 75, $this->_newline . ' ',
1266 1484
                                                     true, $charset, true);
1267 1485
                 }
@@ -1269,8 +1487,10 @@  discard block
 block discarded – undo
1269 1487
             }
1270 1488
         }
1271 1489
 
1272
-        foreach ($this->_components as $component) {
1273
-            if ($this->isOldFormat() &&  $component->getType() == 'vTimeZone') {
1490
+        foreach ($this->_components as $component)
1491
+        {
1492
+            if ($this->isOldFormat() &&  $component->getType() == 'vTimeZone')
1493
+            {
1274 1494
     			// Not supported
1275 1495
 				continue;
1276 1496
         	}
@@ -1286,15 +1506,19 @@  discard block
 block discarded – undo
1286 1506
     function _parseUtcOffset($text)
1287 1507
     {
1288 1508
         $offset = array();
1289
-        if (preg_match('/(\+|-)([0-9]{2})([0-9]{2})([0-9]{2})?/', $text, $timeParts)) {
1509
+        if (preg_match('/(\+|-)([0-9]{2})([0-9]{2})([0-9]{2})?/', $text, $timeParts))
1510
+        {
1290 1511
             $offset['ahead']  = (bool)($timeParts[1] == '+');
1291 1512
             $offset['hour']   = intval($timeParts[2]);
1292 1513
             $offset['minute'] = intval($timeParts[3]);
1293
-            if (isset($timeParts[4])) {
1514
+            if (isset($timeParts[4]))
1515
+            {
1294 1516
                 $offset['second'] = intval($timeParts[4]);
1295 1517
             }
1296 1518
             return $offset;
1297
-        } else {
1519
+        }
1520
+        else
1521
+        {
1298 1522
             return false;
1299 1523
         }
1300 1524
     }
@@ -1307,7 +1531,8 @@  discard block
 block discarded – undo
1307 1531
         $offset = $value['ahead'] ? '+' : '-';
1308 1532
         $offset .= sprintf('%02d%02d',
1309 1533
                            $value['hour'], $value['minute']);
1310
-        if (isset($value['second'])) {
1534
+        if (isset($value['second']))
1535
+        {
1311 1536
             $offset .= sprintf('%02d', $value['second']);
1312 1537
         }
1313 1538
 
@@ -1323,9 +1548,12 @@  discard block
 block discarded – undo
1323 1548
 
1324 1549
         $start = $this->_parseDateTime($periodParts[0]);
1325 1550
 
1326
-        if ($duration = $this->_parseDuration($periodParts[1])) {
1551
+        if ($duration = $this->_parseDuration($periodParts[1]))
1552
+        {
1327 1553
             return array('start' => $start, 'duration' => $duration);
1328
-        } elseif ($end = $this->_parseDateTime($periodParts[1])) {
1554
+        }
1555
+        elseif ($end = $this->_parseDateTime($periodParts[1]))
1556
+        {
1329 1557
             return array('start' => $start, 'end' => $end);
1330 1558
         }
1331 1559
     }
@@ -1337,9 +1565,12 @@  discard block
 block discarded – undo
1337 1565
     {
1338 1566
         $period = $this->_exportDateTime($value['start']);
1339 1567
         $period .= '/';
1340
-        if (isset($value['duration'])) {
1568
+        if (isset($value['duration']))
1569
+        {
1341 1570
             $period .= $this->_exportDuration($value['duration']);
1342
-        } else {
1571
+        }
1572
+        else
1573
+        {
1343 1574
             $period .= $this->_exportDateTime($value['end']);
1344 1575
         }
1345 1576
         return $period;
@@ -1352,19 +1583,23 @@  discard block
 block discarded – undo
1352 1583
     function _parseTZID($date, $time, $tzid)
1353 1584
     {
1354 1585
         $vtimezone = $this->_container->findComponentByAttribute('vtimezone', 'TZID', $tzid);
1355
-        if (!$vtimezone) {
1586
+        if (!$vtimezone)
1587
+        {
1356 1588
             return false;
1357 1589
         }
1358 1590
 
1359 1591
         $change_times = array();
1360
-        foreach ($vtimezone->getComponents() as $o) {
1592
+        foreach ($vtimezone->getComponents() as $o)
1593
+        {
1361 1594
             $t = $vtimezone->parseChild($o, $date['year']);
1362
-            if ($t !== false) {
1595
+            if ($t !== false)
1596
+            {
1363 1597
                 $change_times[] = $t;
1364 1598
             }
1365 1599
         }
1366 1600
 
1367
-        if (!$change_times) {
1601
+        if (!$change_times)
1602
+        {
1368 1603
             return false;
1369 1604
         }
1370 1605
 
@@ -1374,18 +1609,22 @@  discard block
 block discarded – undo
1374 1609
         $t = @gmmktime($time['hour'], $time['minute'], $time['second'],
1375 1610
                        $date['month'], $date['mday'], $date['year']);
1376 1611
 
1377
-        if ($t < $change_times[0]['time']) {
1612
+        if ($t < $change_times[0]['time'])
1613
+        {
1378 1614
             return $change_times[0]['from'];
1379 1615
         }
1380 1616
 
1381
-        for ($i = 0, $n = count($change_times); $i < $n - 1; $i++) {
1617
+        for ($i = 0, $n = count($change_times); $i < $n - 1; $i++)
1618
+        {
1382 1619
             if (($t >= $change_times[$i]['time']) &&
1383
-                ($t < $change_times[$i + 1]['time'])) {
1620
+                ($t < $change_times[$i + 1]['time']))
1621
+            {
1384 1622
                 return $change_times[$i]['to'];
1385 1623
             }
1386 1624
         }
1387 1625
 
1388
-        if ($t >= $change_times[$n - 1]['time']) {
1626
+        if ($t >= $change_times[$n - 1]['time'])
1627
+        {
1389 1628
             return $change_times[$n - 1]['to'];
1390 1629
         }
1391 1630
 
@@ -1402,9 +1641,11 @@  discard block
 block discarded – undo
1402 1641
     function _parseDateTime($text, $tzid = false)
1403 1642
     {
1404 1643
         $dateParts = explode('T', $text);
1405
-        if (count($dateParts) != 2 && !empty($text)) {
1644
+        if (count($dateParts) != 2 && !empty($text))
1645
+        {
1406 1646
             // Not a datetime field but may be just a date field.
1407
-            if (!preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $text, $match)) {
1647
+            if (!preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $text, $match))
1648
+            {
1408 1649
                 // Or not
1409 1650
                 return $text;
1410 1651
             }
@@ -1412,23 +1653,29 @@  discard block
 block discarded – undo
1412 1653
             $dateParts = explode('T', $newtext);
1413 1654
         }
1414 1655
 
1415
-        if (!$date = Horde_iCalendar::_parseDate($dateParts[0])) {
1656
+        if (!$date = Horde_iCalendar::_parseDate($dateParts[0]))
1657
+        {
1416 1658
             return $text;
1417 1659
         }
1418
-        if (!$time = Horde_iCalendar::_parseTime($dateParts[1])) {
1660
+        if (!$time = Horde_iCalendar::_parseTime($dateParts[1]))
1661
+        {
1419 1662
             return $text;
1420 1663
         }
1421 1664
 
1422 1665
         // Get timezone info for date fields from $tzid and container.
1423 1666
         $tzoffset = ($time['zone'] == 'Local' && $tzid && is_a($this->_container, 'Horde_iCalendar'))
1424 1667
             ? $this->_parseTZID($date, $time, $tzid) : false;
1425
-        if ($time['zone'] == 'UTC' || $tzoffset !== false) {
1668
+        if ($time['zone'] == 'UTC' || $tzoffset !== false)
1669
+        {
1426 1670
             $result = @gmmktime($time['hour'], $time['minute'], $time['second'],
1427 1671
                                 $date['month'], $date['mday'], $date['year']);
1428
-            if ($tzoffset) {
1672
+            if ($tzoffset)
1673
+            {
1429 1674
                 $result -= $tzoffset;
1430 1675
             }
1431
-        } else {
1676
+        }
1677
+        else
1678
+        {
1432 1679
             // We don't know the timezone so assume local timezone.
1433 1680
             // FIXME: shouldn't this be based on the user's timezone
1434 1681
             // preference rather than the server's timezone?
@@ -1444,7 +1691,8 @@  discard block
 block discarded – undo
1444 1691
      */
1445 1692
     function _exportDateTime($value)
1446 1693
     {
1447
-        if (is_numeric($value)) {
1694
+        if (is_numeric($value))
1695
+        {
1448 1696
             $temp = array();
1449 1697
             $tz = date('O', $value);
1450 1698
             $TZOffset = (3600 * substr($tz, 0, 3)) + (60 * substr(date('O', $value), 3, 2));
@@ -1458,7 +1706,9 @@  discard block
 block discarded – undo
1458 1706
             $temp['minute'] = date('i', $value);
1459 1707
             $temp['second'] = date('s', $value);
1460 1708
             return Horde_iCalendar::_exportDate($temp) . 'T' . Horde_iCalendar::_exportTime($temp);
1461
-        } else if (is_object($value) || is_array($value)) {
1709
+        }
1710
+        else if (is_object($value) || is_array($value))
1711
+        {
1462 1712
             $dateOb = new Horde_Date($value);
1463 1713
             return Horde_iCalendar::_exportDateTime($dateOb->timestamp());
1464 1714
         }
@@ -1472,17 +1722,23 @@  discard block
 block discarded – undo
1472 1722
      */
1473 1723
     function _parseTime($text)
1474 1724
     {
1475
-        if (preg_match('/([0-9]{2})([0-9]{2})([0-9]{2})(Z)?/', $text, $timeParts)) {
1725
+        if (preg_match('/([0-9]{2})([0-9]{2})([0-9]{2})(Z)?/', $text, $timeParts))
1726
+        {
1476 1727
             $time['hour'] = intval($timeParts[1]);
1477 1728
             $time['minute'] = intval($timeParts[2]);
1478 1729
             $time['second'] = intval($timeParts[3]);
1479
-            if (isset($timeParts[4])) {
1730
+            if (isset($timeParts[4]))
1731
+            {
1480 1732
                 $time['zone'] = 'UTC';
1481
-            } else {
1733
+            }
1734
+            else
1735
+            {
1482 1736
                 $time['zone'] = 'Local';
1483 1737
             }
1484 1738
             return $time;
1485
-        } else {
1739
+        }
1740
+        else
1741
+        {
1486 1742
             return false;
1487 1743
         }
1488 1744
     }
@@ -1494,7 +1750,8 @@  discard block
 block discarded – undo
1494 1750
     {
1495 1751
         $time = sprintf('%02d%02d%02d',
1496 1752
                         $value['hour'], $value['minute'], $value['second']);
1497
-        if ($value['zone'] == 'UTC') {
1753
+        if ($value['zone'] == 'UTC')
1754
+        {
1498 1755
             $time .= 'Z';
1499 1756
         }
1500 1757
         return $time;
@@ -1508,11 +1765,13 @@  discard block
 block discarded – undo
1508 1765
     function _parseDate($text)
1509 1766
     {
1510 1767
         $parts = explode('T', $text);
1511
-        if (count($parts) == 2) {
1768
+        if (count($parts) == 2)
1769
+        {
1512 1770
             $text = $parts[0];
1513 1771
         }
1514 1772
 
1515
-        if (!preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $text, $match)) {
1773
+        if (!preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $text, $match))
1774
+        {
1516 1775
             return false;
1517 1776
         }
1518 1777
 
@@ -1531,12 +1790,16 @@  discard block
 block discarded – undo
1531 1790
      */
1532 1791
     function _exportDate($value, $autoconvert = false)
1533 1792
     {
1534
-        if (is_object($value)) {
1793
+        if (is_object($value))
1794
+        {
1535 1795
             $value = array('year' => $value->year, 'month' => $value->month, 'mday' => $value->mday);
1536 1796
         }
1537
-        if ($autoconvert !== false && $this->isOldFormat()) {
1797
+        if ($autoconvert !== false && $this->isOldFormat())
1798
+        {
1538 1799
             return sprintf('%04d%02d%02dT%s', $value['year'], $value['month'], $value['mday'], $autoconvert);
1539
-        } else {
1800
+        }
1801
+        else
1802
+        {
1540 1803
             return sprintf('%04d%02d%02d', $value['year'], $value['month'], $value['mday']);
1541 1804
         }
1542 1805
     }
@@ -1546,36 +1809,44 @@  discard block
 block discarded – undo
1546 1809
      */
1547 1810
     function _parseDuration($text)
1548 1811
     {
1549
-        if (preg_match('/([+]?|[-])P(([0-9]+W)|([0-9]+D)|)(T(([0-9]+H)|([0-9]+M)|([0-9]+S))+)?/', trim($text), $durvalue)) {
1812
+        if (preg_match('/([+]?|[-])P(([0-9]+W)|([0-9]+D)|)(T(([0-9]+H)|([0-9]+M)|([0-9]+S))+)?/', trim($text), $durvalue))
1813
+        {
1550 1814
             // Weeks.
1551 1815
             $duration = 7 * 86400 * intval($durvalue[3]);
1552 1816
 
1553
-            if (count($durvalue) > 4) {
1817
+            if (count($durvalue) > 4)
1818
+            {
1554 1819
                 // Days.
1555 1820
                 $duration += 86400 * intval($durvalue[4]);
1556 1821
             }
1557
-            if (count($durvalue) > 5) {
1822
+            if (count($durvalue) > 5)
1823
+            {
1558 1824
                 // Hours.
1559 1825
                 $duration += 3600 * intval($durvalue[7]);
1560 1826
 
1561 1827
                 // Mins.
1562
-                if (isset($durvalue[8])) {
1828
+                if (isset($durvalue[8]))
1829
+                {
1563 1830
                     $duration += 60 * intval($durvalue[8]);
1564 1831
                 }
1565 1832
 
1566 1833
                 // Secs.
1567
-                if (isset($durvalue[9])) {
1834
+                if (isset($durvalue[9]))
1835
+                {
1568 1836
                     $duration += intval($durvalue[9]);
1569 1837
                 }
1570 1838
             }
1571 1839
 
1572 1840
             // Sign.
1573
-            if ($durvalue[1] == "-") {
1841
+            if ($durvalue[1] == "-")
1842
+            {
1574 1843
                 $duration *= -1;
1575 1844
             }
1576 1845
 
1577 1846
             return $duration;
1578
-        } else {
1847
+        }
1848
+        else
1849
+        {
1579 1850
             return false;
1580 1851
         }
1581 1852
     }
@@ -1586,7 +1857,8 @@  discard block
 block discarded – undo
1586 1857
     function _exportDuration($value)
1587 1858
     {
1588 1859
         $duration = '';
1589
-        if ($value < 0) {
1860
+        if ($value < 0)
1861
+        {
1590 1862
             $value *= -1;
1591 1863
             $duration .= '-';
1592 1864
         }
@@ -1594,32 +1866,38 @@  discard block
 block discarded – undo
1594 1866
 
1595 1867
         $weeks = floor($value / (7 * 86400));
1596 1868
         $value = $value % (7 * 86400);
1597
-        if ($weeks) {
1869
+        if ($weeks)
1870
+        {
1598 1871
             $duration .= $weeks . 'W';
1599 1872
         }
1600 1873
 
1601 1874
         $days = floor($value / (86400));
1602 1875
         $value = $value % (86400);
1603
-        if ($days) {
1876
+        if ($days)
1877
+        {
1604 1878
             $duration .= $days . 'D';
1605 1879
         }
1606 1880
 
1607
-        if ($value) {
1881
+        if ($value)
1882
+        {
1608 1883
             $duration .= 'T';
1609 1884
 
1610 1885
             $hours = floor($value / 3600);
1611 1886
             $value = $value % 3600;
1612
-            if ($hours) {
1887
+            if ($hours)
1888
+            {
1613 1889
                 $duration .= $hours . 'H';
1614 1890
             }
1615 1891
 
1616 1892
             $mins = floor($value / 60);
1617 1893
             $value = $value % 60;
1618
-            if ($mins) {
1894
+            if ($mins)
1895
+            {
1619 1896
                 $duration .= $mins . 'M';
1620 1897
             }
1621 1898
 
1622
-            if ($value) {
1899
+            if ($value)
1900
+            {
1623 1901
                 $duration .= $value . 'S';
1624 1902
             }
1625 1903
         }
@@ -1662,32 +1940,41 @@  discard block
 block discarded – undo
1662 1940
         $output = $line = '';
1663 1941
         $len = bytes($input);
1664 1942
 
1665
-        for ($i = 0; $i < $len; ++$i) {
1943
+        for ($i = 0; $i < $len; ++$i)
1944
+        {
1666 1945
             $ord = ord($input[$i]);
1667 1946
             // Encode non-printable characters (rule 2).
1668 1947
             if ($ord == 9 ||
1669 1948
                 ($ord >= 32 && $ord <= 60) ||
1670
-                ($ord >= 62 && $ord <= 126)) {
1949
+                ($ord >= 62 && $ord <= 126))
1950
+            {
1671 1951
                 $chunk = $input[$i];
1672
-            } else {
1952
+            }
1953
+            else
1954
+            {
1673 1955
                 // Quoted printable encoding (rule 1).
1674 1956
                 $chunk = '=' . String::upper(sprintf('%02X', $ord));
1675 1957
             }
1676 1958
             $line .= $chunk;
1677 1959
             // Wrap long lines (rule 5)
1678
-            if ($withFolding && strlen($line) + 1 > 76) {
1960
+            if ($withFolding && strlen($line) + 1 > 76)
1961
+            {
1679 1962
                 $line = String::wordwrap($line, 75, "=\r\n", true, 'us-ascii', true);
1680 1963
                 $newline = strrchr($line, "\r\n");
1681
-                if ($newline !== false) {
1964
+                if ($newline !== false)
1965
+                {
1682 1966
                     $output .= substr($line, 0, -strlen($newline) + 2);
1683 1967
                     $line = substr($newline, 2);
1684
-                } else {
1968
+                }
1969
+                else
1970
+                {
1685 1971
                     $output .= $line;
1686 1972
                 }
1687 1973
                 continue;
1688 1974
             }
1689 1975
             // Wrap at line breaks for better readability (rule 4).
1690
-            if ($withFolding && substr($line, -3) == '=0A') {
1976
+            if ($withFolding && substr($line, -3) == '=0A')
1977
+            {
1691 1978
                 $output .= $line . "=\r\n";
1692 1979
                 $line = '';
1693 1980
             }
@@ -1697,7 +1984,8 @@  discard block
 block discarded – undo
1697 1984
         // Trailing whitespace must be encoded (rule 3).
1698 1985
         $lastpos = strlen($output) - 1;
1699 1986
         if ($output[$lastpos] == chr(9) ||
1700
-            $output[$lastpos] == chr(32)) {
1987
+            $output[$lastpos] == chr(32))
1988
+        {
1701 1989
             $output[$lastpos] = '=';
1702 1990
             $output .= String::upper(sprintf('%02X', ord($output[$lastpos])));
1703 1991
         }
Please login to merge, or discard this patch.
phpgwapi/inc/horde/Horde/iCalendar/vfreebusy.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@
 block discarded – undo
156 156
     /**
157 157
      * Returns any additional freebusy parameters.
158 158
      *
159
-     * @return array  Additional parameters of the freebusy periods.
159
+     * @return integer|null  Additional parameters of the freebusy periods.
160 160
      */
161 161
     function getExtraParams()
162 162
     {
Please login to merge, or discard this patch.
Indentation   +438 added lines, -438 removed lines patch added patch discarded remove patch
@@ -17,443 +17,443 @@
 block discarded – undo
17 17
  */
18 18
 class Horde_iCalendar_vfreebusy extends Horde_iCalendar {
19 19
 
20
-    var $_busyPeriods = array();
21
-    var $_extraParams = array();
22
-
23
-    /**
24
-     * Returns the type of this calendar component.
25
-     *
26
-     * @return string  The type of this component.
27
-     */
28
-    function getType()
29
-    {
30
-        return 'vFreebusy';
31
-    }
32
-
33
-    /**
34
-     * Parses a string containing vFreebusy data.
35
-     *
36
-     * @param string $data     The data to parse.
37
-     */
38
-    function parsevCalendar($data, $type = null, $charset = null)
39
-    {
40
-        parent::parsevCalendar($data, 'VFREEBUSY', $charset);
41
-
42
-        // Do something with all the busy periods.
43
-        foreach ($this->_attributes as $key => $attribute) {
44
-            if ($attribute['name'] != 'FREEBUSY') {
45
-                continue;
46
-            }
47
-            foreach ($attribute['values'] as $value) {
48
-                $params = isset($attribute['params'])
49
-                    ? $attribute['params']
50
-                    : array();
51
-                if (isset($value['duration'])) {
52
-                    $this->addBusyPeriod('BUSY', $value['start'], null,
53
-                                         $value['duration'], $params);
54
-                } else {
55
-                    $this->addBusyPeriod('BUSY', $value['start'],
56
-                                         $value['end'], null, $params);
57
-                }
58
-            }
59
-            unset($this->_attributes[$key]);
60
-        }
61
-    }
62
-
63
-    /**
64
-     * Returns the component exported as string.
65
-     *
66
-     * @return string  The exported vFreeBusy information according to the
67
-     *                 iCalender format specification.
68
-     */
69
-    function exportvCalendar()
70
-    {
71
-        foreach ($this->_busyPeriods as $start => $end) {
72
-            $periods = array(array('start' => $start, 'end' => $end));
73
-            $this->setAttribute('FREEBUSY', $periods,
74
-                                isset($this->_extraParams[$start])
75
-                                ? $this->_extraParams[$start] : array());
76
-        }
77
-
78
-        $res = parent::_exportvData('VFREEBUSY');
79
-
80
-        foreach ($this->_attributes as $key => $attribute) {
81
-            if ($attribute['name'] == 'FREEBUSY') {
82
-                unset($this->_attributes[$key]);
83
-            }
84
-        }
85
-
86
-        return $res;
87
-    }
88
-
89
-    /**
90
-     * Returns a display name for this object.
91
-     *
92
-     * @return string  A clear text name for displaying this object.
93
-     */
94
-    function getName()
95
-    {
96
-        $name = '';
97
-        $method = !empty($this->_container) ?
98
-            $this->_container->getAttribute('METHOD') : 'PUBLISH';
99
-
100
-        if (is_a($method, 'PEAR_Error') || $method == 'PUBLISH') {
101
-            $attr = 'ORGANIZER';
102
-        } elseif ($method == 'REPLY') {
103
-            $attr = 'ATTENDEE';
104
-        }
105
-
106
-        $name = $this->getAttribute($attr, true);
107
-        if (!is_a($name, 'PEAR_Error') && isset($name[0]['CN'])) {
108
-            return $name[0]['CN'];
109
-        }
110
-
111
-        $name = $this->getAttribute($attr);
112
-        if (is_a($name, 'PEAR_Error')) {
113
-            return '';
114
-        } else {
115
-            $name = parse_url($name);
116
-            return $name['path'];
117
-        }
118
-    }
119
-
120
-    /**
121
-     * Returns the email address for this object.
122
-     *
123
-     * @return string  The email address of this object's owner.
124
-     */
125
-    function getEmail()
126
-    {
127
-        $name = '';
128
-        $method = !empty($this->_container)
129
-                  ? $this->_container->getAttribute('METHOD') : 'PUBLISH';
130
-
131
-        if (is_a($method, 'PEAR_Error') || $method == 'PUBLISH') {
132
-            $attr = 'ORGANIZER';
133
-        } elseif ($method == 'REPLY') {
134
-            $attr = 'ATTENDEE';
135
-        }
136
-
137
-        $name = $this->getAttribute($attr);
138
-        if (is_a($name, 'PEAR_Error')) {
139
-            return '';
140
-        } else {
141
-            $name = parse_url($name);
142
-            return $name['path'];
143
-        }
144
-    }
145
-
146
-    /**
147
-     * Returns the busy periods.
148
-     *
149
-     * @return array  All busy periods.
150
-     */
151
-    function getBusyPeriods()
152
-    {
153
-        return $this->_busyPeriods;
154
-    }
155
-
156
-    /**
157
-     * Returns any additional freebusy parameters.
158
-     *
159
-     * @return array  Additional parameters of the freebusy periods.
160
-     */
161
-    function getExtraParams()
162
-    {
163
-        return $this->_extraParams;
164
-    }
165
-
166
-    /**
167
-     * Returns all the free periods of time in a given period.
168
-     *
169
-     * @param integer $startStamp  The start timestamp.
170
-     * @param integer $endStamp    The end timestamp.
171
-     *
172
-     * @return array  A hash with free time periods, the start times as the
173
-     *                keys and the end times as the values.
174
-     */
175
-    function getFreePeriods($startStamp, $endStamp)
176
-    {
177
-        $this->simplify();
178
-        $periods = array();
179
-
180
-        // Check that we have data for some part of this period.
181
-        if ($this->getEnd() < $startStamp || $this->getStart() > $endStamp) {
182
-            return $periods;
183
-        }
184
-
185
-        // Locate the first time in the requested period we have data for.
186
-        $nextstart = max($startStamp, $this->getStart());
187
-
188
-        // Check each busy period and add free periods in between.
189
-        foreach ($this->_busyPeriods as $start => $end) {
190
-            if ($start <= $endStamp && $end >= $nextstart) {
191
-                if ($nextstart <= $start) {
192
-                    $periods[$nextstart] = min($start, $endStamp);
193
-                }
194
-                $nextstart = min($end, $endStamp);
195
-            }
196
-        }
197
-
198
-        // If we didn't read the end of the requested period but still have
199
-        // data then mark as free to the end of the period or available data.
200
-        if ($nextstart < $endStamp && $nextstart < $this->getEnd()) {
201
-            $periods[$nextstart] = min($this->getEnd(), $endStamp);
202
-        }
203
-
204
-        return $periods;
205
-    }
206
-
207
-    /**
208
-     * Adds a busy period to the info.
209
-     *
210
-     * This function may throw away data in case you add a period with a start
211
-     * date that already exists. The longer of the two periods will be chosen
212
-     * (and all information associated with the shorter one will be removed).
213
-     *
214
-     * @param string $type       The type of the period. Either 'FREE' or
215
-     *                           'BUSY'; only 'BUSY' supported at the moment.
216
-     * @param integer $start     The start timestamp of the period.
217
-     * @param integer $end       The end timestamp of the period.
218
-     * @param integer $duration  The duration of the period. If specified, the
219
-     *                           $end parameter will be ignored.
220
-     * @param array   $extra     Additional parameters for this busy period.
221
-     */
222
-    function addBusyPeriod($type, $start, $end = null, $duration = null,
223
-                           $extra = array())
224
-    {
225
-        if ($type == 'FREE') {
226
-            // Make sure this period is not marked as busy.
227
-            return false;
228
-        }
229
-
230
-        // Calculate the end time if duration was specified.
231
-        $tempEnd = is_null($duration) ? $end : $start + $duration;
232
-
233
-        // Make sure the period length is always positive.
234
-        $end = max($start, $tempEnd);
235
-        $start = min($start, $tempEnd);
236
-
237
-        if (isset($this->_busyPeriods[$start])) {
238
-            // Already a period starting at this time. Change the current
239
-            // period only if the new one is longer. This might be a problem
240
-            // if the callee assumes that there is no simplification going
241
-            // on. But since the periods are stored using the start time of
242
-            // the busy periods we have to throw away data here.
243
-            if ($end > $this->_busyPeriods[$start]) {
244
-                $this->_busyPeriods[$start] = $end;
245
-                $this->_extraParams[$start] = $extra;
246
-            }
247
-        } else {
248
-            // Add a new busy period.
249
-            $this->_busyPeriods[$start] = $end;
250
-            $this->_extraParams[$start] = $extra;
251
-        }
252
-
253
-        return true;
254
-    }
255
-
256
-    /**
257
-     * Returns the timestamp of the start of the time period this free busy
258
-     * information covers.
259
-     *
260
-     * @return integer  A timestamp.
261
-     */
262
-    function getStart()
263
-    {
264
-        if (!is_a($this->getAttribute('DTSTART'), 'PEAR_Error')) {
265
-            return $this->getAttribute('DTSTART');
266
-        } elseif (count($this->_busyPeriods)) {
267
-            return min(array_keys($this->_busyPeriods));
268
-        } else {
269
-            return false;
270
-        }
271
-    }
272
-
273
-    /**
274
-     * Returns the timestamp of the end of the time period this free busy
275
-     * information covers.
276
-     *
277
-     * @return integer  A timestamp.
278
-     */
279
-    function getEnd()
280
-    {
281
-        if (!is_a($this->getAttribute('DTEND'), 'PEAR_Error')) {
282
-            return $this->getAttribute('DTEND');
283
-        } elseif (count($this->_busyPeriods)) {
284
-            return max(array_values($this->_busyPeriods));
285
-        } else {
286
-            return false;
287
-        }
288
-    }
289
-
290
-    /**
291
-     * Merges the busy periods of another Horde_iCalendar_vfreebusy object
292
-     * into this one.
293
-     *
294
-     * This might lead to simplification no matter what you specify for the
295
-     * "simplify" flag since periods with the same start date will lead to the
296
-     * shorter period being removed (see addBusyPeriod).
297
-     *
298
-     * @param Horde_iCalendar_vfreebusy $freebusy  A freebusy object.
299
-     * @param boolean $simplify                    If true, simplify() will
300
-     *                                             called after the merge.
301
-     */
302
-    function merge($freebusy, $simplify = true)
303
-    {
304
-        if (!is_a($freebusy, 'Horde_iCalendar_vfreebusy')) {
305
-            return false;
306
-        }
307
-
308
-        $extra = $freebusy->getExtraParams();
309
-        foreach ($freebusy->getBusyPeriods() as $start => $end) {
310
-            // This might simplify the busy periods without taking the
311
-            // "simplify" flag into account.
312
-            $this->addBusyPeriod('BUSY', $start, $end, null,
313
-                                 isset($extra[$start])
314
-                                 ? $extra[$start] : array());
315
-        }
316
-
317
-        $thisattr = $this->getAttribute('DTSTART');
318
-        $thatattr = $freebusy->getAttribute('DTSTART');
319
-        if (is_a($thisattr, 'PEAR_Error') && !is_a($thatattr, 'PEAR_Error')) {
320
-            $this->setAttribute('DTSTART', $thatattr, array(), false);
321
-        } elseif (!is_a($thatattr, 'PEAR_Error')) {
322
-            if ($thatattr < $thisattr) {
323
-                $this->setAttribute('DTSTART', $thatattr, array(), false);
324
-            }
325
-        }
326
-
327
-        $thisattr = $this->getAttribute('DTEND');
328
-        $thatattr = $freebusy->getAttribute('DTEND');
329
-        if (is_a($thisattr, 'PEAR_Error') && !is_a($thatattr, 'PEAR_Error')) {
330
-            $this->setAttribute('DTEND', $thatattr, array(), false);
331
-        } elseif (!is_a($thatattr, 'PEAR_Error')) {
332
-            if ($thatattr > $thisattr) {
333
-                $this->setAttribute('DTEND', $thatattr, array(), false);
334
-            }
335
-        }
336
-
337
-        if ($simplify) {
338
-            $this->simplify();
339
-        }
340
-
341
-        return true;
342
-    }
343
-
344
-    /**
345
-     * Removes all overlaps and simplifies the busy periods array as much as
346
-     * possible.
347
-     */
348
-    function simplify()
349
-    {
350
-        $clean = false;
351
-        $busy  = array($this->_busyPeriods, $this->_extraParams);
352
-        while (!$clean) {
353
-            $result = $this->_simplify($busy[0], $busy[1]);
354
-            $clean = $result === $busy;
355
-            $busy = $result;
356
-        }
357
-
358
-        ksort($result[1], SORT_NUMERIC);
359
-        $this->_extraParams = $result[1];
360
-
361
-        ksort($result[0], SORT_NUMERIC);
362
-        $this->_busyPeriods = $result[0];
363
-    }
364
-
365
-    function _simplify($busyPeriods, $extraParams = array())
366
-    {
367
-        $checked = array();
368
-        $checkedExtra = array();
369
-        $checkedEmpty = true;
370
-
371
-        foreach ($busyPeriods as $start => $end) {
372
-            if ($checkedEmpty) {
373
-                $checked[$start] = $end;
374
-                $checkedExtra[$start] = isset($extraParams[$start])
375
-                    ? $extraParams[$start] : array();
376
-                $checkedEmpty = false;
377
-            } else {
378
-                $added = false;
379
-                foreach ($checked as $testStart => $testEnd) {
380
-                    // Replace old period if the new period lies around the
381
-                    // old period.
382
-                    if ($start <= $testStart && $end >= $testEnd) {
383
-                        // Remove old period entry.
384
-                        unset($checked[$testStart]);
385
-                        unset($checkedExtra[$testStart]);
386
-                        // Add replacing entry.
387
-                        $checked[$start] = $end;
388
-                        $checkedExtra[$start] = isset($extraParams[$start])
389
-                            ? $extraParams[$start] : array();
390
-                        $added = true;
391
-                    } elseif ($start >= $testStart && $end <= $testEnd) {
392
-                        // The new period lies fully within the old
393
-                        // period. Just forget about it.
394
-                        $added = true;
395
-                    } elseif (($end <= $testEnd && $end >= $testStart) ||
396
-                              ($start >= $testStart && $start <= $testEnd)) {
397
-                        // Now we are in trouble: Overlapping time periods. If
398
-                        // we allow for additional parameters we cannot simply
399
-                        // choose one of the two parameter sets. It's better
400
-                        // to leave two separated time periods.
401
-                        $extra = isset($extraParams[$start])
402
-                            ? $extraParams[$start] : array();
403
-                        $testExtra = isset($checkedExtra[$testStart])
404
-                            ? $checkedExtra[$testStart] : array();
405
-                        // Remove old period entry.
406
-                        unset($checked[$testStart]);
407
-                        unset($checkedExtra[$testStart]);
408
-                        // We have two periods overlapping. Are their
409
-                        // additional parameters the same or different?
410
-                        $newStart = min($start, $testStart);
411
-                        $newEnd = max($end, $testEnd);
412
-                        if ($extra === $testExtra) {
413
-                            // Both periods have the same information. So we
414
-                            // can just merge.
415
-                            $checked[$newStart] = $newEnd;
416
-                            $checkedExtra[$newStart] = $extra;
417
-                        } else {
418
-                            // Extra parameters are different. Create one
419
-                            // period at the beginning with the params of the
420
-                            // first period and create a trailing period with
421
-                            // the params of the second period. The break
422
-                            // point will be the end of the first period.
423
-                            $break = min($end, $testEnd);
424
-                            $checked[$newStart] = $break;
425
-                            $checkedExtra[$newStart] =
426
-                                isset($extraParams[$newStart])
427
-                                ? $extraParams[$newStart] : array();
428
-                            $checked[$break] = $newEnd;
429
-                            $highStart = max($start, $testStart);
430
-                            $checkedExtra[$break] =
431
-                                isset($extraParams[$highStart])
432
-                                ? $extraParams[$highStart] : array();
433
-
434
-                            // Ensure we also have the extra data in the
435
-                            // extraParams.
436
-                            $extraParams[$break] =
437
-                                isset($extraParams[$highStart])
438
-                                ? $extraParams[$highStart] : array();
439
-                        }
440
-                        $added = true;
441
-                    }
442
-
443
-                    if ($added) {
444
-                        break;
445
-                    }
446
-                }
447
-
448
-                if (!$added) {
449
-                    $checked[$start] = $end;
450
-                    $checkedExtra[$start] = isset($extraParams[$start])
451
-                        ? $extraParams[$start] : array();
452
-                }
453
-            }
454
-        }
455
-
456
-        return array($checked, $checkedExtra);
457
-    }
20
+	var $_busyPeriods = array();
21
+	var $_extraParams = array();
22
+
23
+	/**
24
+	 * Returns the type of this calendar component.
25
+	 *
26
+	 * @return string  The type of this component.
27
+	 */
28
+	function getType()
29
+	{
30
+		return 'vFreebusy';
31
+	}
32
+
33
+	/**
34
+	 * Parses a string containing vFreebusy data.
35
+	 *
36
+	 * @param string $data     The data to parse.
37
+	 */
38
+	function parsevCalendar($data, $type = null, $charset = null)
39
+	{
40
+		parent::parsevCalendar($data, 'VFREEBUSY', $charset);
41
+
42
+		// Do something with all the busy periods.
43
+		foreach ($this->_attributes as $key => $attribute) {
44
+			if ($attribute['name'] != 'FREEBUSY') {
45
+				continue;
46
+			}
47
+			foreach ($attribute['values'] as $value) {
48
+				$params = isset($attribute['params'])
49
+					? $attribute['params']
50
+					: array();
51
+				if (isset($value['duration'])) {
52
+					$this->addBusyPeriod('BUSY', $value['start'], null,
53
+										 $value['duration'], $params);
54
+				} else {
55
+					$this->addBusyPeriod('BUSY', $value['start'],
56
+										 $value['end'], null, $params);
57
+				}
58
+			}
59
+			unset($this->_attributes[$key]);
60
+		}
61
+	}
62
+
63
+	/**
64
+	 * Returns the component exported as string.
65
+	 *
66
+	 * @return string  The exported vFreeBusy information according to the
67
+	 *                 iCalender format specification.
68
+	 */
69
+	function exportvCalendar()
70
+	{
71
+		foreach ($this->_busyPeriods as $start => $end) {
72
+			$periods = array(array('start' => $start, 'end' => $end));
73
+			$this->setAttribute('FREEBUSY', $periods,
74
+								isset($this->_extraParams[$start])
75
+								? $this->_extraParams[$start] : array());
76
+		}
77
+
78
+		$res = parent::_exportvData('VFREEBUSY');
79
+
80
+		foreach ($this->_attributes as $key => $attribute) {
81
+			if ($attribute['name'] == 'FREEBUSY') {
82
+				unset($this->_attributes[$key]);
83
+			}
84
+		}
85
+
86
+		return $res;
87
+	}
88
+
89
+	/**
90
+	 * Returns a display name for this object.
91
+	 *
92
+	 * @return string  A clear text name for displaying this object.
93
+	 */
94
+	function getName()
95
+	{
96
+		$name = '';
97
+		$method = !empty($this->_container) ?
98
+			$this->_container->getAttribute('METHOD') : 'PUBLISH';
99
+
100
+		if (is_a($method, 'PEAR_Error') || $method == 'PUBLISH') {
101
+			$attr = 'ORGANIZER';
102
+		} elseif ($method == 'REPLY') {
103
+			$attr = 'ATTENDEE';
104
+		}
105
+
106
+		$name = $this->getAttribute($attr, true);
107
+		if (!is_a($name, 'PEAR_Error') && isset($name[0]['CN'])) {
108
+			return $name[0]['CN'];
109
+		}
110
+
111
+		$name = $this->getAttribute($attr);
112
+		if (is_a($name, 'PEAR_Error')) {
113
+			return '';
114
+		} else {
115
+			$name = parse_url($name);
116
+			return $name['path'];
117
+		}
118
+	}
119
+
120
+	/**
121
+	 * Returns the email address for this object.
122
+	 *
123
+	 * @return string  The email address of this object's owner.
124
+	 */
125
+	function getEmail()
126
+	{
127
+		$name = '';
128
+		$method = !empty($this->_container)
129
+				  ? $this->_container->getAttribute('METHOD') : 'PUBLISH';
130
+
131
+		if (is_a($method, 'PEAR_Error') || $method == 'PUBLISH') {
132
+			$attr = 'ORGANIZER';
133
+		} elseif ($method == 'REPLY') {
134
+			$attr = 'ATTENDEE';
135
+		}
136
+
137
+		$name = $this->getAttribute($attr);
138
+		if (is_a($name, 'PEAR_Error')) {
139
+			return '';
140
+		} else {
141
+			$name = parse_url($name);
142
+			return $name['path'];
143
+		}
144
+	}
145
+
146
+	/**
147
+	 * Returns the busy periods.
148
+	 *
149
+	 * @return array  All busy periods.
150
+	 */
151
+	function getBusyPeriods()
152
+	{
153
+		return $this->_busyPeriods;
154
+	}
155
+
156
+	/**
157
+	 * Returns any additional freebusy parameters.
158
+	 *
159
+	 * @return array  Additional parameters of the freebusy periods.
160
+	 */
161
+	function getExtraParams()
162
+	{
163
+		return $this->_extraParams;
164
+	}
165
+
166
+	/**
167
+	 * Returns all the free periods of time in a given period.
168
+	 *
169
+	 * @param integer $startStamp  The start timestamp.
170
+	 * @param integer $endStamp    The end timestamp.
171
+	 *
172
+	 * @return array  A hash with free time periods, the start times as the
173
+	 *                keys and the end times as the values.
174
+	 */
175
+	function getFreePeriods($startStamp, $endStamp)
176
+	{
177
+		$this->simplify();
178
+		$periods = array();
179
+
180
+		// Check that we have data for some part of this period.
181
+		if ($this->getEnd() < $startStamp || $this->getStart() > $endStamp) {
182
+			return $periods;
183
+		}
184
+
185
+		// Locate the first time in the requested period we have data for.
186
+		$nextstart = max($startStamp, $this->getStart());
187
+
188
+		// Check each busy period and add free periods in between.
189
+		foreach ($this->_busyPeriods as $start => $end) {
190
+			if ($start <= $endStamp && $end >= $nextstart) {
191
+				if ($nextstart <= $start) {
192
+					$periods[$nextstart] = min($start, $endStamp);
193
+				}
194
+				$nextstart = min($end, $endStamp);
195
+			}
196
+		}
197
+
198
+		// If we didn't read the end of the requested period but still have
199
+		// data then mark as free to the end of the period or available data.
200
+		if ($nextstart < $endStamp && $nextstart < $this->getEnd()) {
201
+			$periods[$nextstart] = min($this->getEnd(), $endStamp);
202
+		}
203
+
204
+		return $periods;
205
+	}
206
+
207
+	/**
208
+	 * Adds a busy period to the info.
209
+	 *
210
+	 * This function may throw away data in case you add a period with a start
211
+	 * date that already exists. The longer of the two periods will be chosen
212
+	 * (and all information associated with the shorter one will be removed).
213
+	 *
214
+	 * @param string $type       The type of the period. Either 'FREE' or
215
+	 *                           'BUSY'; only 'BUSY' supported at the moment.
216
+	 * @param integer $start     The start timestamp of the period.
217
+	 * @param integer $end       The end timestamp of the period.
218
+	 * @param integer $duration  The duration of the period. If specified, the
219
+	 *                           $end parameter will be ignored.
220
+	 * @param array   $extra     Additional parameters for this busy period.
221
+	 */
222
+	function addBusyPeriod($type, $start, $end = null, $duration = null,
223
+						   $extra = array())
224
+	{
225
+		if ($type == 'FREE') {
226
+			// Make sure this period is not marked as busy.
227
+			return false;
228
+		}
229
+
230
+		// Calculate the end time if duration was specified.
231
+		$tempEnd = is_null($duration) ? $end : $start + $duration;
232
+
233
+		// Make sure the period length is always positive.
234
+		$end = max($start, $tempEnd);
235
+		$start = min($start, $tempEnd);
236
+
237
+		if (isset($this->_busyPeriods[$start])) {
238
+			// Already a period starting at this time. Change the current
239
+			// period only if the new one is longer. This might be a problem
240
+			// if the callee assumes that there is no simplification going
241
+			// on. But since the periods are stored using the start time of
242
+			// the busy periods we have to throw away data here.
243
+			if ($end > $this->_busyPeriods[$start]) {
244
+				$this->_busyPeriods[$start] = $end;
245
+				$this->_extraParams[$start] = $extra;
246
+			}
247
+		} else {
248
+			// Add a new busy period.
249
+			$this->_busyPeriods[$start] = $end;
250
+			$this->_extraParams[$start] = $extra;
251
+		}
252
+
253
+		return true;
254
+	}
255
+
256
+	/**
257
+	 * Returns the timestamp of the start of the time period this free busy
258
+	 * information covers.
259
+	 *
260
+	 * @return integer  A timestamp.
261
+	 */
262
+	function getStart()
263
+	{
264
+		if (!is_a($this->getAttribute('DTSTART'), 'PEAR_Error')) {
265
+			return $this->getAttribute('DTSTART');
266
+		} elseif (count($this->_busyPeriods)) {
267
+			return min(array_keys($this->_busyPeriods));
268
+		} else {
269
+			return false;
270
+		}
271
+	}
272
+
273
+	/**
274
+	 * Returns the timestamp of the end of the time period this free busy
275
+	 * information covers.
276
+	 *
277
+	 * @return integer  A timestamp.
278
+	 */
279
+	function getEnd()
280
+	{
281
+		if (!is_a($this->getAttribute('DTEND'), 'PEAR_Error')) {
282
+			return $this->getAttribute('DTEND');
283
+		} elseif (count($this->_busyPeriods)) {
284
+			return max(array_values($this->_busyPeriods));
285
+		} else {
286
+			return false;
287
+		}
288
+	}
289
+
290
+	/**
291
+	 * Merges the busy periods of another Horde_iCalendar_vfreebusy object
292
+	 * into this one.
293
+	 *
294
+	 * This might lead to simplification no matter what you specify for the
295
+	 * "simplify" flag since periods with the same start date will lead to the
296
+	 * shorter period being removed (see addBusyPeriod).
297
+	 *
298
+	 * @param Horde_iCalendar_vfreebusy $freebusy  A freebusy object.
299
+	 * @param boolean $simplify                    If true, simplify() will
300
+	 *                                             called after the merge.
301
+	 */
302
+	function merge($freebusy, $simplify = true)
303
+	{
304
+		if (!is_a($freebusy, 'Horde_iCalendar_vfreebusy')) {
305
+			return false;
306
+		}
307
+
308
+		$extra = $freebusy->getExtraParams();
309
+		foreach ($freebusy->getBusyPeriods() as $start => $end) {
310
+			// This might simplify the busy periods without taking the
311
+			// "simplify" flag into account.
312
+			$this->addBusyPeriod('BUSY', $start, $end, null,
313
+								 isset($extra[$start])
314
+								 ? $extra[$start] : array());
315
+		}
316
+
317
+		$thisattr = $this->getAttribute('DTSTART');
318
+		$thatattr = $freebusy->getAttribute('DTSTART');
319
+		if (is_a($thisattr, 'PEAR_Error') && !is_a($thatattr, 'PEAR_Error')) {
320
+			$this->setAttribute('DTSTART', $thatattr, array(), false);
321
+		} elseif (!is_a($thatattr, 'PEAR_Error')) {
322
+			if ($thatattr < $thisattr) {
323
+				$this->setAttribute('DTSTART', $thatattr, array(), false);
324
+			}
325
+		}
326
+
327
+		$thisattr = $this->getAttribute('DTEND');
328
+		$thatattr = $freebusy->getAttribute('DTEND');
329
+		if (is_a($thisattr, 'PEAR_Error') && !is_a($thatattr, 'PEAR_Error')) {
330
+			$this->setAttribute('DTEND', $thatattr, array(), false);
331
+		} elseif (!is_a($thatattr, 'PEAR_Error')) {
332
+			if ($thatattr > $thisattr) {
333
+				$this->setAttribute('DTEND', $thatattr, array(), false);
334
+			}
335
+		}
336
+
337
+		if ($simplify) {
338
+			$this->simplify();
339
+		}
340
+
341
+		return true;
342
+	}
343
+
344
+	/**
345
+	 * Removes all overlaps and simplifies the busy periods array as much as
346
+	 * possible.
347
+	 */
348
+	function simplify()
349
+	{
350
+		$clean = false;
351
+		$busy  = array($this->_busyPeriods, $this->_extraParams);
352
+		while (!$clean) {
353
+			$result = $this->_simplify($busy[0], $busy[1]);
354
+			$clean = $result === $busy;
355
+			$busy = $result;
356
+		}
357
+
358
+		ksort($result[1], SORT_NUMERIC);
359
+		$this->_extraParams = $result[1];
360
+
361
+		ksort($result[0], SORT_NUMERIC);
362
+		$this->_busyPeriods = $result[0];
363
+	}
364
+
365
+	function _simplify($busyPeriods, $extraParams = array())
366
+	{
367
+		$checked = array();
368
+		$checkedExtra = array();
369
+		$checkedEmpty = true;
370
+
371
+		foreach ($busyPeriods as $start => $end) {
372
+			if ($checkedEmpty) {
373
+				$checked[$start] = $end;
374
+				$checkedExtra[$start] = isset($extraParams[$start])
375
+					? $extraParams[$start] : array();
376
+				$checkedEmpty = false;
377
+			} else {
378
+				$added = false;
379
+				foreach ($checked as $testStart => $testEnd) {
380
+					// Replace old period if the new period lies around the
381
+					// old period.
382
+					if ($start <= $testStart && $end >= $testEnd) {
383
+						// Remove old period entry.
384
+						unset($checked[$testStart]);
385
+						unset($checkedExtra[$testStart]);
386
+						// Add replacing entry.
387
+						$checked[$start] = $end;
388
+						$checkedExtra[$start] = isset($extraParams[$start])
389
+							? $extraParams[$start] : array();
390
+						$added = true;
391
+					} elseif ($start >= $testStart && $end <= $testEnd) {
392
+						// The new period lies fully within the old
393
+						// period. Just forget about it.
394
+						$added = true;
395
+					} elseif (($end <= $testEnd && $end >= $testStart) ||
396
+							  ($start >= $testStart && $start <= $testEnd)) {
397
+						// Now we are in trouble: Overlapping time periods. If
398
+						// we allow for additional parameters we cannot simply
399
+						// choose one of the two parameter sets. It's better
400
+						// to leave two separated time periods.
401
+						$extra = isset($extraParams[$start])
402
+							? $extraParams[$start] : array();
403
+						$testExtra = isset($checkedExtra[$testStart])
404
+							? $checkedExtra[$testStart] : array();
405
+						// Remove old period entry.
406
+						unset($checked[$testStart]);
407
+						unset($checkedExtra[$testStart]);
408
+						// We have two periods overlapping. Are their
409
+						// additional parameters the same or different?
410
+						$newStart = min($start, $testStart);
411
+						$newEnd = max($end, $testEnd);
412
+						if ($extra === $testExtra) {
413
+							// Both periods have the same information. So we
414
+							// can just merge.
415
+							$checked[$newStart] = $newEnd;
416
+							$checkedExtra[$newStart] = $extra;
417
+						} else {
418
+							// Extra parameters are different. Create one
419
+							// period at the beginning with the params of the
420
+							// first period and create a trailing period with
421
+							// the params of the second period. The break
422
+							// point will be the end of the first period.
423
+							$break = min($end, $testEnd);
424
+							$checked[$newStart] = $break;
425
+							$checkedExtra[$newStart] =
426
+								isset($extraParams[$newStart])
427
+								? $extraParams[$newStart] : array();
428
+							$checked[$break] = $newEnd;
429
+							$highStart = max($start, $testStart);
430
+							$checkedExtra[$break] =
431
+								isset($extraParams[$highStart])
432
+								? $extraParams[$highStart] : array();
433
+
434
+							// Ensure we also have the extra data in the
435
+							// extraParams.
436
+							$extraParams[$break] =
437
+								isset($extraParams[$highStart])
438
+								? $extraParams[$highStart] : array();
439
+						}
440
+						$added = true;
441
+					}
442
+
443
+					if ($added) {
444
+						break;
445
+					}
446
+				}
447
+
448
+				if (!$added) {
449
+					$checked[$start] = $end;
450
+					$checkedExtra[$start] = isset($extraParams[$start])
451
+						? $extraParams[$start] : array();
452
+				}
453
+			}
454
+		}
455
+
456
+		return array($checked, $checkedExtra);
457
+	}
458 458
 
459 459
 }
Please login to merge, or discard this patch.
Braces   +125 added lines, -55 removed lines patch added patch discarded remove patch
@@ -15,7 +15,8 @@  discard block
 block discarded – undo
15 15
  * @since   Horde 3.0
16 16
  * @package Horde_iCalendar
17 17
  */
18
-class Horde_iCalendar_vfreebusy extends Horde_iCalendar {
18
+class Horde_iCalendar_vfreebusy extends Horde_iCalendar
19
+{
19 20
 
20 21
     var $_busyPeriods = array();
21 22
     var $_extraParams = array();
@@ -40,18 +41,24 @@  discard block
 block discarded – undo
40 41
         parent::parsevCalendar($data, 'VFREEBUSY', $charset);
41 42
 
42 43
         // Do something with all the busy periods.
43
-        foreach ($this->_attributes as $key => $attribute) {
44
-            if ($attribute['name'] != 'FREEBUSY') {
44
+        foreach ($this->_attributes as $key => $attribute)
45
+        {
46
+            if ($attribute['name'] != 'FREEBUSY')
47
+            {
45 48
                 continue;
46 49
             }
47
-            foreach ($attribute['values'] as $value) {
50
+            foreach ($attribute['values'] as $value)
51
+            {
48 52
                 $params = isset($attribute['params'])
49 53
                     ? $attribute['params']
50 54
                     : array();
51
-                if (isset($value['duration'])) {
55
+                if (isset($value['duration']))
56
+                {
52 57
                     $this->addBusyPeriod('BUSY', $value['start'], null,
53 58
                                          $value['duration'], $params);
54
-                } else {
59
+                }
60
+                else
61
+                {
55 62
                     $this->addBusyPeriod('BUSY', $value['start'],
56 63
                                          $value['end'], null, $params);
57 64
                 }
@@ -68,7 +75,8 @@  discard block
 block discarded – undo
68 75
      */
69 76
     function exportvCalendar()
70 77
     {
71
-        foreach ($this->_busyPeriods as $start => $end) {
78
+        foreach ($this->_busyPeriods as $start => $end)
79
+        {
72 80
             $periods = array(array('start' => $start, 'end' => $end));
73 81
             $this->setAttribute('FREEBUSY', $periods,
74 82
                                 isset($this->_extraParams[$start])
@@ -77,8 +85,10 @@  discard block
 block discarded – undo
77 85
 
78 86
         $res = parent::_exportvData('VFREEBUSY');
79 87
 
80
-        foreach ($this->_attributes as $key => $attribute) {
81
-            if ($attribute['name'] == 'FREEBUSY') {
88
+        foreach ($this->_attributes as $key => $attribute)
89
+        {
90
+            if ($attribute['name'] == 'FREEBUSY')
91
+            {
82 92
                 unset($this->_attributes[$key]);
83 93
             }
84 94
         }
@@ -97,21 +107,28 @@  discard block
 block discarded – undo
97 107
         $method = !empty($this->_container) ?
98 108
             $this->_container->getAttribute('METHOD') : 'PUBLISH';
99 109
 
100
-        if (is_a($method, 'PEAR_Error') || $method == 'PUBLISH') {
110
+        if (is_a($method, 'PEAR_Error') || $method == 'PUBLISH')
111
+        {
101 112
             $attr = 'ORGANIZER';
102
-        } elseif ($method == 'REPLY') {
113
+        }
114
+        elseif ($method == 'REPLY')
115
+        {
103 116
             $attr = 'ATTENDEE';
104 117
         }
105 118
 
106 119
         $name = $this->getAttribute($attr, true);
107
-        if (!is_a($name, 'PEAR_Error') && isset($name[0]['CN'])) {
120
+        if (!is_a($name, 'PEAR_Error') && isset($name[0]['CN']))
121
+        {
108 122
             return $name[0]['CN'];
109 123
         }
110 124
 
111 125
         $name = $this->getAttribute($attr);
112
-        if (is_a($name, 'PEAR_Error')) {
126
+        if (is_a($name, 'PEAR_Error'))
127
+        {
113 128
             return '';
114
-        } else {
129
+        }
130
+        else
131
+        {
115 132
             $name = parse_url($name);
116 133
             return $name['path'];
117 134
         }
@@ -128,16 +145,22 @@  discard block
 block discarded – undo
128 145
         $method = !empty($this->_container)
129 146
                   ? $this->_container->getAttribute('METHOD') : 'PUBLISH';
130 147
 
131
-        if (is_a($method, 'PEAR_Error') || $method == 'PUBLISH') {
148
+        if (is_a($method, 'PEAR_Error') || $method == 'PUBLISH')
149
+        {
132 150
             $attr = 'ORGANIZER';
133
-        } elseif ($method == 'REPLY') {
151
+        }
152
+        elseif ($method == 'REPLY')
153
+        {
134 154
             $attr = 'ATTENDEE';
135 155
         }
136 156
 
137 157
         $name = $this->getAttribute($attr);
138
-        if (is_a($name, 'PEAR_Error')) {
158
+        if (is_a($name, 'PEAR_Error'))
159
+        {
139 160
             return '';
140
-        } else {
161
+        }
162
+        else
163
+        {
141 164
             $name = parse_url($name);
142 165
             return $name['path'];
143 166
         }
@@ -178,7 +201,8 @@  discard block
 block discarded – undo
178 201
         $periods = array();
179 202
 
180 203
         // Check that we have data for some part of this period.
181
-        if ($this->getEnd() < $startStamp || $this->getStart() > $endStamp) {
204
+        if ($this->getEnd() < $startStamp || $this->getStart() > $endStamp)
205
+        {
182 206
             return $periods;
183 207
         }
184 208
 
@@ -186,9 +210,12 @@  discard block
 block discarded – undo
186 210
         $nextstart = max($startStamp, $this->getStart());
187 211
 
188 212
         // Check each busy period and add free periods in between.
189
-        foreach ($this->_busyPeriods as $start => $end) {
190
-            if ($start <= $endStamp && $end >= $nextstart) {
191
-                if ($nextstart <= $start) {
213
+        foreach ($this->_busyPeriods as $start => $end)
214
+        {
215
+            if ($start <= $endStamp && $end >= $nextstart)
216
+            {
217
+                if ($nextstart <= $start)
218
+                {
192 219
                     $periods[$nextstart] = min($start, $endStamp);
193 220
                 }
194 221
                 $nextstart = min($end, $endStamp);
@@ -197,7 +224,8 @@  discard block
 block discarded – undo
197 224
 
198 225
         // If we didn't read the end of the requested period but still have
199 226
         // data then mark as free to the end of the period or available data.
200
-        if ($nextstart < $endStamp && $nextstart < $this->getEnd()) {
227
+        if ($nextstart < $endStamp && $nextstart < $this->getEnd())
228
+        {
201 229
             $periods[$nextstart] = min($this->getEnd(), $endStamp);
202 230
         }
203 231
 
@@ -222,7 +250,8 @@  discard block
 block discarded – undo
222 250
     function addBusyPeriod($type, $start, $end = null, $duration = null,
223 251
                            $extra = array())
224 252
     {
225
-        if ($type == 'FREE') {
253
+        if ($type == 'FREE')
254
+        {
226 255
             // Make sure this period is not marked as busy.
227 256
             return false;
228 257
         }
@@ -234,17 +263,21 @@  discard block
 block discarded – undo
234 263
         $end = max($start, $tempEnd);
235 264
         $start = min($start, $tempEnd);
236 265
 
237
-        if (isset($this->_busyPeriods[$start])) {
266
+        if (isset($this->_busyPeriods[$start]))
267
+        {
238 268
             // Already a period starting at this time. Change the current
239 269
             // period only if the new one is longer. This might be a problem
240 270
             // if the callee assumes that there is no simplification going
241 271
             // on. But since the periods are stored using the start time of
242 272
             // the busy periods we have to throw away data here.
243
-            if ($end > $this->_busyPeriods[$start]) {
273
+            if ($end > $this->_busyPeriods[$start])
274
+            {
244 275
                 $this->_busyPeriods[$start] = $end;
245 276
                 $this->_extraParams[$start] = $extra;
246 277
             }
247
-        } else {
278
+        }
279
+        else
280
+        {
248 281
             // Add a new busy period.
249 282
             $this->_busyPeriods[$start] = $end;
250 283
             $this->_extraParams[$start] = $extra;
@@ -261,11 +294,16 @@  discard block
 block discarded – undo
261 294
      */
262 295
     function getStart()
263 296
     {
264
-        if (!is_a($this->getAttribute('DTSTART'), 'PEAR_Error')) {
297
+        if (!is_a($this->getAttribute('DTSTART'), 'PEAR_Error'))
298
+        {
265 299
             return $this->getAttribute('DTSTART');
266
-        } elseif (count($this->_busyPeriods)) {
300
+        }
301
+        elseif (count($this->_busyPeriods))
302
+        {
267 303
             return min(array_keys($this->_busyPeriods));
268
-        } else {
304
+        }
305
+        else
306
+        {
269 307
             return false;
270 308
         }
271 309
     }
@@ -278,11 +316,16 @@  discard block
 block discarded – undo
278 316
      */
279 317
     function getEnd()
280 318
     {
281
-        if (!is_a($this->getAttribute('DTEND'), 'PEAR_Error')) {
319
+        if (!is_a($this->getAttribute('DTEND'), 'PEAR_Error'))
320
+        {
282 321
             return $this->getAttribute('DTEND');
283
-        } elseif (count($this->_busyPeriods)) {
322
+        }
323
+        elseif (count($this->_busyPeriods))
324
+        {
284 325
             return max(array_values($this->_busyPeriods));
285
-        } else {
326
+        }
327
+        else
328
+        {
286 329
             return false;
287 330
         }
288 331
     }
@@ -301,12 +344,14 @@  discard block
 block discarded – undo
301 344
      */
302 345
     function merge($freebusy, $simplify = true)
303 346
     {
304
-        if (!is_a($freebusy, 'Horde_iCalendar_vfreebusy')) {
347
+        if (!is_a($freebusy, 'Horde_iCalendar_vfreebusy'))
348
+        {
305 349
             return false;
306 350
         }
307 351
 
308 352
         $extra = $freebusy->getExtraParams();
309
-        foreach ($freebusy->getBusyPeriods() as $start => $end) {
353
+        foreach ($freebusy->getBusyPeriods() as $start => $end)
354
+        {
310 355
             // This might simplify the busy periods without taking the
311 356
             // "simplify" flag into account.
312 357
             $this->addBusyPeriod('BUSY', $start, $end, null,
@@ -316,25 +361,34 @@  discard block
 block discarded – undo
316 361
 
317 362
         $thisattr = $this->getAttribute('DTSTART');
318 363
         $thatattr = $freebusy->getAttribute('DTSTART');
319
-        if (is_a($thisattr, 'PEAR_Error') && !is_a($thatattr, 'PEAR_Error')) {
364
+        if (is_a($thisattr, 'PEAR_Error') && !is_a($thatattr, 'PEAR_Error'))
365
+        {
320 366
             $this->setAttribute('DTSTART', $thatattr, array(), false);
321
-        } elseif (!is_a($thatattr, 'PEAR_Error')) {
322
-            if ($thatattr < $thisattr) {
367
+        }
368
+        elseif (!is_a($thatattr, 'PEAR_Error'))
369
+        {
370
+            if ($thatattr < $thisattr)
371
+            {
323 372
                 $this->setAttribute('DTSTART', $thatattr, array(), false);
324 373
             }
325 374
         }
326 375
 
327 376
         $thisattr = $this->getAttribute('DTEND');
328 377
         $thatattr = $freebusy->getAttribute('DTEND');
329
-        if (is_a($thisattr, 'PEAR_Error') && !is_a($thatattr, 'PEAR_Error')) {
378
+        if (is_a($thisattr, 'PEAR_Error') && !is_a($thatattr, 'PEAR_Error'))
379
+        {
330 380
             $this->setAttribute('DTEND', $thatattr, array(), false);
331
-        } elseif (!is_a($thatattr, 'PEAR_Error')) {
332
-            if ($thatattr > $thisattr) {
381
+        }
382
+        elseif (!is_a($thatattr, 'PEAR_Error'))
383
+        {
384
+            if ($thatattr > $thisattr)
385
+            {
333 386
                 $this->setAttribute('DTEND', $thatattr, array(), false);
334 387
             }
335 388
         }
336 389
 
337
-        if ($simplify) {
390
+        if ($simplify)
391
+        {
338 392
             $this->simplify();
339 393
         }
340 394
 
@@ -349,7 +403,8 @@  discard block
 block discarded – undo
349 403
     {
350 404
         $clean = false;
351 405
         $busy  = array($this->_busyPeriods, $this->_extraParams);
352
-        while (!$clean) {
406
+        while (!$clean)
407
+        {
353 408
             $result = $this->_simplify($busy[0], $busy[1]);
354 409
             $clean = $result === $busy;
355 410
             $busy = $result;
@@ -368,18 +423,24 @@  discard block
 block discarded – undo
368 423
         $checkedExtra = array();
369 424
         $checkedEmpty = true;
370 425
 
371
-        foreach ($busyPeriods as $start => $end) {
372
-            if ($checkedEmpty) {
426
+        foreach ($busyPeriods as $start => $end)
427
+        {
428
+            if ($checkedEmpty)
429
+            {
373 430
                 $checked[$start] = $end;
374 431
                 $checkedExtra[$start] = isset($extraParams[$start])
375 432
                     ? $extraParams[$start] : array();
376 433
                 $checkedEmpty = false;
377
-            } else {
434
+            }
435
+            else
436
+            {
378 437
                 $added = false;
379
-                foreach ($checked as $testStart => $testEnd) {
438
+                foreach ($checked as $testStart => $testEnd)
439
+                {
380 440
                     // Replace old period if the new period lies around the
381 441
                     // old period.
382
-                    if ($start <= $testStart && $end >= $testEnd) {
442
+                    if ($start <= $testStart && $end >= $testEnd)
443
+                    {
383 444
                         // Remove old period entry.
384 445
                         unset($checked[$testStart]);
385 446
                         unset($checkedExtra[$testStart]);
@@ -388,12 +449,16 @@  discard block
 block discarded – undo
388 449
                         $checkedExtra[$start] = isset($extraParams[$start])
389 450
                             ? $extraParams[$start] : array();
390 451
                         $added = true;
391
-                    } elseif ($start >= $testStart && $end <= $testEnd) {
452
+                    }
453
+                    elseif ($start >= $testStart && $end <= $testEnd)
454
+                    {
392 455
                         // The new period lies fully within the old
393 456
                         // period. Just forget about it.
394 457
                         $added = true;
395
-                    } elseif (($end <= $testEnd && $end >= $testStart) ||
396
-                              ($start >= $testStart && $start <= $testEnd)) {
458
+                    }
459
+                    elseif (($end <= $testEnd && $end >= $testStart) ||
460
+                              ($start >= $testStart && $start <= $testEnd))
461
+                    {
397 462
                         // Now we are in trouble: Overlapping time periods. If
398 463
                         // we allow for additional parameters we cannot simply
399 464
                         // choose one of the two parameter sets. It's better
@@ -409,12 +474,15 @@  discard block
 block discarded – undo
409 474
                         // additional parameters the same or different?
410 475
                         $newStart = min($start, $testStart);
411 476
                         $newEnd = max($end, $testEnd);
412
-                        if ($extra === $testExtra) {
477
+                        if ($extra === $testExtra)
478
+                        {
413 479
                             // Both periods have the same information. So we
414 480
                             // can just merge.
415 481
                             $checked[$newStart] = $newEnd;
416 482
                             $checkedExtra[$newStart] = $extra;
417
-                        } else {
483
+                        }
484
+                        else
485
+                        {
418 486
                             // Extra parameters are different. Create one
419 487
                             // period at the beginning with the params of the
420 488
                             // first period and create a trailing period with
@@ -440,12 +508,14 @@  discard block
 block discarded – undo
440 508
                         $added = true;
441 509
                     }
442 510
 
443
-                    if ($added) {
511
+                    if ($added)
512
+                    {
444 513
                         break;
445 514
                     }
446 515
                 }
447 516
 
448
-                if (!$added) {
517
+                if (!$added)
518
+                {
449 519
                     $checked[$start] = $end;
450 520
                     $checkedExtra[$start] = isset($extraParams[$start])
451 521
                         ? $extraParams[$start] : array();
Please login to merge, or discard this patch.
phpgwapi/inc/horde/Horde/NLS.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -420,7 +420,7 @@
 block discarded – undo
420 420
      *
421 421
      * @param string $host  The hostname or IP address.
422 422
      *
423
-     * @return mixed  On success, return an array with the following entries:
423
+     * @return string  On success, return an array with the following entries:
424 424
      *                'code'  =>  Country Code
425 425
      *                'name'  =>  Country Name
426 426
      *                On failure, return false.
Please login to merge, or discard this patch.
Indentation   +493 added lines, -493 removed lines patch added patch discarded remove patch
@@ -24,500 +24,500 @@
 block discarded – undo
24 24
  */
25 25
 class NLS {
26 26
 
27
-    /**
28
-     * Selects the most preferred language for the current client session.
29
-     *
30
-     * @access public
31
-     *
32
-     * @return string  The selected language abbreviation.
33
-     */
34
-    function select()
35
-    {
36
-        global $nls, $prefs;
37
-
38
-        $lang = Util::getFormData('new_lang');
39
-
40
-        /* First, check if language pref is locked and, if so, set it to its
27
+	/**
28
+	 * Selects the most preferred language for the current client session.
29
+	 *
30
+	 * @access public
31
+	 *
32
+	 * @return string  The selected language abbreviation.
33
+	 */
34
+	function select()
35
+	{
36
+		global $nls, $prefs;
37
+
38
+		$lang = Util::getFormData('new_lang');
39
+
40
+		/* First, check if language pref is locked and, if so, set it to its
41 41
            value */
42
-        if (isset($prefs) && $prefs->isLocked('language')) {
43
-            $language = $prefs->getValue('language');
44
-        /* Check if the user selected a language from the login screen */
45
-        } elseif (!empty($lang)) {
46
-            $language = $lang;
47
-        /* Check if we have a language set in a cookie */
48
-        } elseif (isset($_SESSION['horde_language'])) {
49
-            $language = $_SESSION['horde_language'];
50
-        /* Use site-wide default, if one is defined */
51
-        } elseif (!empty($nls['defaults']['language'])) {
52
-            $language = $nls['defaults']['language'];
53
-        /* Try browser-accepted languages. */
54
-        } elseif (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
55
-            /* The browser supplies a list, so return the first valid one. */
56
-            $browser_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
57
-            foreach ($browser_langs as $lang) {
58
-                /* Strip quality value for language */
59
-                if (($pos = strpos($lang, ';')) !== false) {
60
-                    $lang = substr($lang, 0, $pos);
61
-                }
62
-                $lang = NLS::_map(trim($lang));
63
-                if (NLS::isValid($lang)) {
64
-                    $language = $lang;
65
-                    break;
66
-                }
67
-                /* In case no full match, save best guess based on prefix */
68
-                if (!isset($partial_lang) &&
69
-                    NLS::isValid(NLS::_map(substr($lang, 0, 2)))) {
70
-                    $partial_lang = NLS::_map(substr($lang, 0, 2));
71
-                }
72
-            }
73
-        }
74
-
75
-        if (!isset($language)) {
76
-            if (isset($partial_lang)) {
77
-                $language = $partial_lang;
78
-            } else {
79
-                /* No dice auto-detecting, default to US English. */
80
-                $language = 'en_US';
81
-            }
82
-        }
83
-
84
-        return basename($language);
85
-    }
86
-
87
-    /**
88
-     * Sets the language.
89
-     *
90
-     * @access public
91
-     *
92
-     * @param optional string $lang     The language abbriviation.
93
-     */
94
-    function setLang($lang = null)
95
-    {
96
-        include_once HORDE_BASE . '/config/nls.php';
97
-
98
-        if (empty($lang) || !NLS::isValid($lang)) {
99
-            $lang = NLS::select();
100
-        }
101
-
102
-        if (isset($GLOBALS['language']) && $GLOBALS['language'] == $lang) {
103
-            return;
104
-        }
105
-
106
-        $GLOBALS['language'] = $lang;
107
-
108
-        /* First try language with the current charset. */
109
-        $lang_charset = $lang . '.' . NLS::getCharset();
110
-        if ($lang_charset != setlocale(LC_ALL, $lang_charset)) {
111
-            /* Next try language with its default charset. */
112
-            global $nls;
113
-            $charset = !empty($nls['charsets'][$lang]) ? $nls['charsets'][$lang] : $nls['defaults']['charset'];
114
-            $lang_charset = $lang . '.' . $charset;
115
-            NLS::_cachedCharset(0, $charset);
116
-            if ($lang_charset != setlocale(LC_ALL, $lang_charset)) {
117
-                /* At last try language solely. */
118
-                $lang_charset = $lang;
119
-                setlocale(LC_ALL, $lang_charset);
120
-            }
121
-        }
122
-        @putenv('LANG=' . $lang_charset);
123
-        @putenv('LANGUAGE=' . $lang_charset);
124
-    }
125
-
126
-    /**
127
-     * Sets the gettext domain.
128
-     *
129
-     * @access public
130
-     *
131
-     * @param string $app        The application name.
132
-     * @param string $directory  The directory where the application's
133
-     *                           LC_MESSAGES directory resides.
134
-     * @param string $charset    The charset.
135
-     */
136
-    function setTextdomain($app, $directory, $charset)
137
-    {
138
-        bindtextdomain($app, $directory);
139
-        textdomain($app);
140
-
141
-        /* The existence of this function depends on the platform. */
142
-        if (function_exists('bind_textdomain_codeset')) {
143
-            NLS::_cachedCharset(0, bind_textdomain_codeset($app, $charset));
144
-        }
145
-
146
-        if (!headers_sent()) {
147
-            header('Content-Type: text/html; charset=' . $charset);
148
-        }
149
-    }
150
-
151
-    /**
152
-     * Determines whether the supplied language is valid.
153
-     *
154
-     * @access public
155
-     *
156
-     * @param string $language  The abbreviated name of the language.
157
-     *
158
-     * @return boolean  True if the language is valid, false if it's not
159
-     *                  valid or unknown.
160
-     */
161
-    function isValid($language)
162
-    {
163
-        return !empty($GLOBALS['nls']['languages'][$language]);
164
-    }
165
-
166
-    /**
167
-     * Maps languages with common two-letter codes (such as nl) to the
168
-     * full gettext code (in this case, nl_NL). Returns the language
169
-     * unmodified if it isn't an alias.
170
-     *
171
-     * @access private
172
-     *
173
-     * @param string $language  The language code to map.
174
-     *
175
-     * @return string  The mapped language code.
176
-     */
177
-
178
-    function _map($language)
179
-    {
180
-        require_once 'Horde/String.php';
181
-
182
-        $aliases = &$GLOBALS['nls']['aliases'];
183
-
184
-        // Translate the $language to get broader matches.
185
-        // (eg. de-DE should match de_DE)
186
-        $trans_lang = str_replace('-', '_', $language);
187
-        $lang_parts = explode('_', $trans_lang);
188
-        $trans_lang = String::lower($lang_parts[0]);
189
-        if (isset($lang_parts[1])) {
190
-            $trans_lang .= '_' . String::upper($lang_parts[1]);
191
-        }
192
-
193
-        // See if we get a match for this
194
-        if (!empty($aliases[$trans_lang])) {
195
-            return $aliases[$trans_lang];
196
-        }
197
-
198
-        // If we get that far down, the language cannot be found.
199
-        // Return $trans_lang.
200
-        return $trans_lang;
201
-    }
202
-
203
-    /**
204
-     * Returns the charset for the current language.
205
-     *
206
-     * @access public
207
-     *
208
-     * @param boolean $original  If true returns the original charset of the
209
-     *                           translation, the actually used one otherwise.
210
-     *
211
-     * @return string  The character set that should be used with the current
212
-     *                 locale settings.
213
-     */
214
-    function getCharset($original = false)
215
-    {
216
-        global $language, $nls;
217
-
218
-        /* Get cached results. */
219
-        $cacheKey = intval($original);
220
-        $charset = NLS::_cachedCharset($cacheKey);
221
-        if (!is_null($charset)) {
222
-            return $charset;
223
-        }
224
-
225
-        if ($original) {
226
-            $charset = empty($nls['charsets'][$language]) ? $nls['defaults']['charset'] : $nls['charsets'][$language];
227
-        } else {
228
-            require_once 'Horde/Browser.php';
229
-            $browser = &Browser::singleton();
230
-
231
-            if ($browser->hasFeature('utf') &&
232
-                (Util::extensionExists('iconv') ||
233
-                 Util::extensionExists('mbstring'))) {
234
-                $charset = 'UTF-8';
235
-            }
236
-        }
237
-
238
-        if (is_null($charset)) {
239
-            $charset = NLS::getExternalCharset();
240
-        }
241
-
242
-        NLS::_cachedCharset($cacheKey, $charset);
243
-        return $charset;
244
-    }
245
-
246
-
247
-    /**
248
-     * Returns the current charset of the environment
249
-     *
250
-     * @access public
251
-     *
252
-     * @return string  The character set that should be used with the current
253
-     *                 locale settings.
254
-     */
255
-    function getExternalCharset()
256
-    {
257
-        global $language, $nls;
258
-
259
-        /* Get cached results. */
260
-        $charset = NLS::_cachedCharset(2);
261
-        if (!is_null($charset)) {
262
-            return $charset;
263
-        }
264
-
265
-        $lang_charset = setlocale(LC_ALL, 0);
266
-        if (strpos($lang_charset, ';') === false &&
267
-            strpos($lang_charset, '/') === false) {
268
-            $lang_charset = explode('.', $lang_charset);
269
-            if ((count($lang_charset) == 2) && !empty($lang_charset[1])) {
270
-                NLS::_cachedCharset(2, $lang_charset[1]);
271
-                return $lang_charset[1];
272
-            }
273
-        }
274
-
275
-        return (!empty($nls['charsets'][$language])) ? $nls['charsets'][$language] : $nls['defaults']['charset'];
276
-    }
277
-
278
-    /**
279
-     * Sets or returns the charset used under certain conditions.
280
-     *
281
-     * @access private
282
-     *
283
-     * @param integer $index   The ID of a cache slot. 0 for the UI charset, 1
284
-     *                         for the translation charset and 2 for the
285
-     *                         external charset.
286
-     * @param string $charset  If specified, this charset will be stored in the
287
-     *                         given cache slot. Otherwise the content of the
288
-     *                         specified cache slot will be returned.
289
-     */
290
-    function _cachedCharset($index, $charset = null)
291
-    {
292
-        static $cache;
293
-
294
-        if (!isset($cache)) {
295
-            $cache = array();
296
-        }
297
-
298
-        if ($charset == null) {
299
-            return isset($cache[$index]) ? $cache[$index] : null;
300
-        } else {
301
-            $cache[$index] = $charset;
302
-        }
303
-    }
304
-
305
-    /**
306
-     * Returns the charset to use for outgoing emails.
307
-     *
308
-     * @return string  The preferred charset for outgoing mails based on
309
-     *                 the user's preferences and the current language.
310
-     */
311
-    function getEmailCharset()
312
-    {
313
-        global $prefs, $language, $nls;
314
-
315
-        $charset = $prefs->getValue('sending_charset');
316
-        if (!empty($charset)) {
317
-            return $charset;
318
-        }
319
-        return isset($nls['emails'][$language]) ? $nls['emails'][$language] :
320
-               (isset($nls['charsets'][$language]) ? $nls['charsets'][$language] : $nls['defaults']['charset']);
321
-    }
322
-
323
-    /**
324
-     * Check to see if character set is valid for htmlspecialchars() calls.
325
-     *
326
-     * @access public
327
-     *
328
-     * @param string $charset  The character set to check.
329
-     *
330
-     * @return boolean  Is charset valid for the current system?
331
-     */
332
-    function checkCharset($charset)
333
-    {
334
-        static $check;
335
-
336
-        if (is_null($charset) || empty($charset)) {
337
-            return false;
338
-        }
339
-
340
-        if (isset($check[$charset])) {
341
-            return $check[$charset];
342
-        } elseif (!isset($check)) {
343
-            $check = array();
344
-        }
345
-
346
-        $valid = true;
347
-
348
-        ini_set('track_errors', 1);
349
-        @htmlspecialchars('', ENT_COMPAT, $charset);
350
-        if (isset($php_errormsg)) {
351
-            $valid = false;
352
-        }
353
-        ini_restore('track_errors');
354
-
355
-        $check[$charset] = $valid;
356
-
357
-        return $valid;
358
-    }
359
-
360
-    /**
361
-     * Sets the current timezone, if available.
362
-     *
363
-     * @access public
364
-     */
365
-    function setTimeZone()
366
-    {
367
-        global $prefs;
368
-
369
-        $tz = $prefs->getValue('timezone');
370
-        if (!empty($tz)) {
371
-            @putenv('TZ=' . $tz);
372
-        }
373
-    }
374
-
375
-    /**
376
-     * Get the locale info returned by localeconv(), but cache it, to
377
-     * avoid repeated calls.
378
-     *
379
-     * @access public
380
-     *
381
-     * @return array  The results of localeconv().
382
-     */
383
-    function getLocaleInfo()
384
-    {
385
-        static $lc_info;
386
-
387
-        if (!isset($lc_info)) {
388
-            $lc_info = localeconv();
389
-        }
390
-
391
-        return $lc_info;
392
-    }
393
-
394
-    /**
395
-     * Get the language info returned by nl_langinfo(), but cache it, to
396
-     * avoid repeated calls.
397
-     *
398
-     * @access public
399
-     * @since Horde 3.1
400
-     *
401
-     * @param const $item  The langinfo item to return.
402
-     *
403
-     * @return array  The results of nl_langinfo().
404
-     */
405
-    function getLangInfo($item)
406
-    {
407
-        static $nl_info = array();
408
-
409
-        if (!isset($nl_info[$item])) {
410
-            $nl_info[$item] = nl_langinfo($item);
411
-        }
412
-
413
-        return $nl_info[$item];
414
-    }
415
-
416
-    /**
417
-     * Get country information from a hostname or IP address.
418
-     *
419
-     * @access public
420
-     *
421
-     * @param string $host  The hostname or IP address.
422
-     *
423
-     * @return mixed  On success, return an array with the following entries:
424
-     *                'code'  =>  Country Code
425
-     *                'name'  =>  Country Name
426
-     *                On failure, return false.
427
-     */
428
-    function getCountryByHost($host)
429
-    {
430
-        global $conf;
431
-
432
-        /* List of generic domains that we know is not in the country TLD
42
+		if (isset($prefs) && $prefs->isLocked('language')) {
43
+			$language = $prefs->getValue('language');
44
+		/* Check if the user selected a language from the login screen */
45
+		} elseif (!empty($lang)) {
46
+			$language = $lang;
47
+		/* Check if we have a language set in a cookie */
48
+		} elseif (isset($_SESSION['horde_language'])) {
49
+			$language = $_SESSION['horde_language'];
50
+		/* Use site-wide default, if one is defined */
51
+		} elseif (!empty($nls['defaults']['language'])) {
52
+			$language = $nls['defaults']['language'];
53
+		/* Try browser-accepted languages. */
54
+		} elseif (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
55
+			/* The browser supplies a list, so return the first valid one. */
56
+			$browser_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
57
+			foreach ($browser_langs as $lang) {
58
+				/* Strip quality value for language */
59
+				if (($pos = strpos($lang, ';')) !== false) {
60
+					$lang = substr($lang, 0, $pos);
61
+				}
62
+				$lang = NLS::_map(trim($lang));
63
+				if (NLS::isValid($lang)) {
64
+					$language = $lang;
65
+					break;
66
+				}
67
+				/* In case no full match, save best guess based on prefix */
68
+				if (!isset($partial_lang) &&
69
+					NLS::isValid(NLS::_map(substr($lang, 0, 2)))) {
70
+					$partial_lang = NLS::_map(substr($lang, 0, 2));
71
+				}
72
+			}
73
+		}
74
+
75
+		if (!isset($language)) {
76
+			if (isset($partial_lang)) {
77
+				$language = $partial_lang;
78
+			} else {
79
+				/* No dice auto-detecting, default to US English. */
80
+				$language = 'en_US';
81
+			}
82
+		}
83
+
84
+		return basename($language);
85
+	}
86
+
87
+	/**
88
+	 * Sets the language.
89
+	 *
90
+	 * @access public
91
+	 *
92
+	 * @param optional string $lang     The language abbriviation.
93
+	 */
94
+	function setLang($lang = null)
95
+	{
96
+		include_once HORDE_BASE . '/config/nls.php';
97
+
98
+		if (empty($lang) || !NLS::isValid($lang)) {
99
+			$lang = NLS::select();
100
+		}
101
+
102
+		if (isset($GLOBALS['language']) && $GLOBALS['language'] == $lang) {
103
+			return;
104
+		}
105
+
106
+		$GLOBALS['language'] = $lang;
107
+
108
+		/* First try language with the current charset. */
109
+		$lang_charset = $lang . '.' . NLS::getCharset();
110
+		if ($lang_charset != setlocale(LC_ALL, $lang_charset)) {
111
+			/* Next try language with its default charset. */
112
+			global $nls;
113
+			$charset = !empty($nls['charsets'][$lang]) ? $nls['charsets'][$lang] : $nls['defaults']['charset'];
114
+			$lang_charset = $lang . '.' . $charset;
115
+			NLS::_cachedCharset(0, $charset);
116
+			if ($lang_charset != setlocale(LC_ALL, $lang_charset)) {
117
+				/* At last try language solely. */
118
+				$lang_charset = $lang;
119
+				setlocale(LC_ALL, $lang_charset);
120
+			}
121
+		}
122
+		@putenv('LANG=' . $lang_charset);
123
+		@putenv('LANGUAGE=' . $lang_charset);
124
+	}
125
+
126
+	/**
127
+	 * Sets the gettext domain.
128
+	 *
129
+	 * @access public
130
+	 *
131
+	 * @param string $app        The application name.
132
+	 * @param string $directory  The directory where the application's
133
+	 *                           LC_MESSAGES directory resides.
134
+	 * @param string $charset    The charset.
135
+	 */
136
+	function setTextdomain($app, $directory, $charset)
137
+	{
138
+		bindtextdomain($app, $directory);
139
+		textdomain($app);
140
+
141
+		/* The existence of this function depends on the platform. */
142
+		if (function_exists('bind_textdomain_codeset')) {
143
+			NLS::_cachedCharset(0, bind_textdomain_codeset($app, $charset));
144
+		}
145
+
146
+		if (!headers_sent()) {
147
+			header('Content-Type: text/html; charset=' . $charset);
148
+		}
149
+	}
150
+
151
+	/**
152
+	 * Determines whether the supplied language is valid.
153
+	 *
154
+	 * @access public
155
+	 *
156
+	 * @param string $language  The abbreviated name of the language.
157
+	 *
158
+	 * @return boolean  True if the language is valid, false if it's not
159
+	 *                  valid or unknown.
160
+	 */
161
+	function isValid($language)
162
+	{
163
+		return !empty($GLOBALS['nls']['languages'][$language]);
164
+	}
165
+
166
+	/**
167
+	 * Maps languages with common two-letter codes (such as nl) to the
168
+	 * full gettext code (in this case, nl_NL). Returns the language
169
+	 * unmodified if it isn't an alias.
170
+	 *
171
+	 * @access private
172
+	 *
173
+	 * @param string $language  The language code to map.
174
+	 *
175
+	 * @return string  The mapped language code.
176
+	 */
177
+
178
+	function _map($language)
179
+	{
180
+		require_once 'Horde/String.php';
181
+
182
+		$aliases = &$GLOBALS['nls']['aliases'];
183
+
184
+		// Translate the $language to get broader matches.
185
+		// (eg. de-DE should match de_DE)
186
+		$trans_lang = str_replace('-', '_', $language);
187
+		$lang_parts = explode('_', $trans_lang);
188
+		$trans_lang = String::lower($lang_parts[0]);
189
+		if (isset($lang_parts[1])) {
190
+			$trans_lang .= '_' . String::upper($lang_parts[1]);
191
+		}
192
+
193
+		// See if we get a match for this
194
+		if (!empty($aliases[$trans_lang])) {
195
+			return $aliases[$trans_lang];
196
+		}
197
+
198
+		// If we get that far down, the language cannot be found.
199
+		// Return $trans_lang.
200
+		return $trans_lang;
201
+	}
202
+
203
+	/**
204
+	 * Returns the charset for the current language.
205
+	 *
206
+	 * @access public
207
+	 *
208
+	 * @param boolean $original  If true returns the original charset of the
209
+	 *                           translation, the actually used one otherwise.
210
+	 *
211
+	 * @return string  The character set that should be used with the current
212
+	 *                 locale settings.
213
+	 */
214
+	function getCharset($original = false)
215
+	{
216
+		global $language, $nls;
217
+
218
+		/* Get cached results. */
219
+		$cacheKey = intval($original);
220
+		$charset = NLS::_cachedCharset($cacheKey);
221
+		if (!is_null($charset)) {
222
+			return $charset;
223
+		}
224
+
225
+		if ($original) {
226
+			$charset = empty($nls['charsets'][$language]) ? $nls['defaults']['charset'] : $nls['charsets'][$language];
227
+		} else {
228
+			require_once 'Horde/Browser.php';
229
+			$browser = &Browser::singleton();
230
+
231
+			if ($browser->hasFeature('utf') &&
232
+				(Util::extensionExists('iconv') ||
233
+				 Util::extensionExists('mbstring'))) {
234
+				$charset = 'UTF-8';
235
+			}
236
+		}
237
+
238
+		if (is_null($charset)) {
239
+			$charset = NLS::getExternalCharset();
240
+		}
241
+
242
+		NLS::_cachedCharset($cacheKey, $charset);
243
+		return $charset;
244
+	}
245
+
246
+
247
+	/**
248
+	 * Returns the current charset of the environment
249
+	 *
250
+	 * @access public
251
+	 *
252
+	 * @return string  The character set that should be used with the current
253
+	 *                 locale settings.
254
+	 */
255
+	function getExternalCharset()
256
+	{
257
+		global $language, $nls;
258
+
259
+		/* Get cached results. */
260
+		$charset = NLS::_cachedCharset(2);
261
+		if (!is_null($charset)) {
262
+			return $charset;
263
+		}
264
+
265
+		$lang_charset = setlocale(LC_ALL, 0);
266
+		if (strpos($lang_charset, ';') === false &&
267
+			strpos($lang_charset, '/') === false) {
268
+			$lang_charset = explode('.', $lang_charset);
269
+			if ((count($lang_charset) == 2) && !empty($lang_charset[1])) {
270
+				NLS::_cachedCharset(2, $lang_charset[1]);
271
+				return $lang_charset[1];
272
+			}
273
+		}
274
+
275
+		return (!empty($nls['charsets'][$language])) ? $nls['charsets'][$language] : $nls['defaults']['charset'];
276
+	}
277
+
278
+	/**
279
+	 * Sets or returns the charset used under certain conditions.
280
+	 *
281
+	 * @access private
282
+	 *
283
+	 * @param integer $index   The ID of a cache slot. 0 for the UI charset, 1
284
+	 *                         for the translation charset and 2 for the
285
+	 *                         external charset.
286
+	 * @param string $charset  If specified, this charset will be stored in the
287
+	 *                         given cache slot. Otherwise the content of the
288
+	 *                         specified cache slot will be returned.
289
+	 */
290
+	function _cachedCharset($index, $charset = null)
291
+	{
292
+		static $cache;
293
+
294
+		if (!isset($cache)) {
295
+			$cache = array();
296
+		}
297
+
298
+		if ($charset == null) {
299
+			return isset($cache[$index]) ? $cache[$index] : null;
300
+		} else {
301
+			$cache[$index] = $charset;
302
+		}
303
+	}
304
+
305
+	/**
306
+	 * Returns the charset to use for outgoing emails.
307
+	 *
308
+	 * @return string  The preferred charset for outgoing mails based on
309
+	 *                 the user's preferences and the current language.
310
+	 */
311
+	function getEmailCharset()
312
+	{
313
+		global $prefs, $language, $nls;
314
+
315
+		$charset = $prefs->getValue('sending_charset');
316
+		if (!empty($charset)) {
317
+			return $charset;
318
+		}
319
+		return isset($nls['emails'][$language]) ? $nls['emails'][$language] :
320
+			   (isset($nls['charsets'][$language]) ? $nls['charsets'][$language] : $nls['defaults']['charset']);
321
+	}
322
+
323
+	/**
324
+	 * Check to see if character set is valid for htmlspecialchars() calls.
325
+	 *
326
+	 * @access public
327
+	 *
328
+	 * @param string $charset  The character set to check.
329
+	 *
330
+	 * @return boolean  Is charset valid for the current system?
331
+	 */
332
+	function checkCharset($charset)
333
+	{
334
+		static $check;
335
+
336
+		if (is_null($charset) || empty($charset)) {
337
+			return false;
338
+		}
339
+
340
+		if (isset($check[$charset])) {
341
+			return $check[$charset];
342
+		} elseif (!isset($check)) {
343
+			$check = array();
344
+		}
345
+
346
+		$valid = true;
347
+
348
+		ini_set('track_errors', 1);
349
+		@htmlspecialchars('', ENT_COMPAT, $charset);
350
+		if (isset($php_errormsg)) {
351
+			$valid = false;
352
+		}
353
+		ini_restore('track_errors');
354
+
355
+		$check[$charset] = $valid;
356
+
357
+		return $valid;
358
+	}
359
+
360
+	/**
361
+	 * Sets the current timezone, if available.
362
+	 *
363
+	 * @access public
364
+	 */
365
+	function setTimeZone()
366
+	{
367
+		global $prefs;
368
+
369
+		$tz = $prefs->getValue('timezone');
370
+		if (!empty($tz)) {
371
+			@putenv('TZ=' . $tz);
372
+		}
373
+	}
374
+
375
+	/**
376
+	 * Get the locale info returned by localeconv(), but cache it, to
377
+	 * avoid repeated calls.
378
+	 *
379
+	 * @access public
380
+	 *
381
+	 * @return array  The results of localeconv().
382
+	 */
383
+	function getLocaleInfo()
384
+	{
385
+		static $lc_info;
386
+
387
+		if (!isset($lc_info)) {
388
+			$lc_info = localeconv();
389
+		}
390
+
391
+		return $lc_info;
392
+	}
393
+
394
+	/**
395
+	 * Get the language info returned by nl_langinfo(), but cache it, to
396
+	 * avoid repeated calls.
397
+	 *
398
+	 * @access public
399
+	 * @since Horde 3.1
400
+	 *
401
+	 * @param const $item  The langinfo item to return.
402
+	 *
403
+	 * @return array  The results of nl_langinfo().
404
+	 */
405
+	function getLangInfo($item)
406
+	{
407
+		static $nl_info = array();
408
+
409
+		if (!isset($nl_info[$item])) {
410
+			$nl_info[$item] = nl_langinfo($item);
411
+		}
412
+
413
+		return $nl_info[$item];
414
+	}
415
+
416
+	/**
417
+	 * Get country information from a hostname or IP address.
418
+	 *
419
+	 * @access public
420
+	 *
421
+	 * @param string $host  The hostname or IP address.
422
+	 *
423
+	 * @return mixed  On success, return an array with the following entries:
424
+	 *                'code'  =>  Country Code
425
+	 *                'name'  =>  Country Name
426
+	 *                On failure, return false.
427
+	 */
428
+	function getCountryByHost($host)
429
+	{
430
+		global $conf;
431
+
432
+		/* List of generic domains that we know is not in the country TLD
433 433
            list. See: http://www.iana.org/gtld/gtld.htm */
434
-        $generic = array(
435
-            'aero', 'biz', 'com', 'coop', 'edu', 'gov', 'info', 'int', 'mil',
436
-            'museum', 'name', 'net', 'org', 'pro'
437
-        );
438
-
439
-        $checkHost = $host;
440
-        if (preg_match('/^\d+\.\d+\.\d+\.\d+$/', $host)) {
441
-            $checkHost = @gethostbyaddr($host);
442
-        }
443
-
444
-        /* Get the TLD of the hostname. */
445
-        $pos = strrpos($checkHost, '.');
446
-        if ($pos === false) {
447
-            return false;
448
-        }
449
-        $domain = String::lower(substr($checkHost, $pos + 1));
450
-
451
-        /* Try lookup via TLD first. */
452
-        if (!in_array($domain, $generic)) {
453
-            require 'Horde/NLS/tld.php';
454
-            if (isset($tld[$domain])) {
455
-                return array('code' => $domain, 'name' => $tld[$domain]);
456
-            }
457
-        }
458
-
459
-        /* Try GeoIP lookup next. */
460
-        if (!empty($conf['geoip']['datafile'])) {
461
-            require_once 'Horde/NLS/GeoIP.php';
462
-            $geoip = &NLS_GeoIP::singleton($conf['geoip']['datafile']);
463
-            $id = $geoip->countryIdByName($checkHost);
464
-            if (!empty($id)) {
465
-                return array('code' => String::lower($GLOBALS['GEOIP_COUNTRY_CODES'][$id]), 'name' => $GLOBALS['GEOIP_COUNTRY_NAMES'][$id]);
466
-            }
467
-        }
468
-
469
-        return false;
470
-    }
471
-
472
-    /**
473
-     * Returns a Horde image link to the country flag.
474
-     *
475
-     * @access public
476
-     *
477
-     * @param string $host  The hostname or IP address.
478
-     *
479
-     * @return string  The image URL, or the empty string on error.
480
-     */
481
-    function generateFlagImageByHost($host)
482
-    {
483
-        global $registry;
484
-
485
-        $data = NLS::getCountryByHost($host);
486
-        if ($data !== false) {
487
-            $img = $data['code'] . '.png';
488
-            if (file_exists($registry->get('themesfs', 'horde') . '/graphics/flags/' . $img)) {
489
-                return Horde::img($img, $data['name'], '', $registry->getImageDir('horde') . '/flags');
490
-            } else {
491
-                return '[' . $data['name'] . ']';
492
-            }
493
-        }
494
-
495
-        return '';
496
-    }
497
-
498
-    /**
499
-     * Returns either a specific or all ISO-3166 country names.
500
-     *
501
-     * @access public
502
-     *
503
-     * @param optional string $code  The ISO 3166 country code.
504
-     *
505
-     * @return mixed  If a country code has been requested will return the
506
-     *                corresponding country name. If empty will return an
507
-     *                array of all the country codes and their names.
508
-     */
509
-    function &getCountryISO($code = '')
510
-    {
511
-        static $countries = array();
512
-        if (empty($countries)) {
513
-            require_once 'Horde/NLS/countries.php';
514
-        }
515
-        if (empty($code)) {
516
-            return $countries;
517
-        } elseif (isset($countries[$code])) {
518
-            return $countries[$code];
519
-        }
520
-        return false;
521
-    }
434
+		$generic = array(
435
+			'aero', 'biz', 'com', 'coop', 'edu', 'gov', 'info', 'int', 'mil',
436
+			'museum', 'name', 'net', 'org', 'pro'
437
+		);
438
+
439
+		$checkHost = $host;
440
+		if (preg_match('/^\d+\.\d+\.\d+\.\d+$/', $host)) {
441
+			$checkHost = @gethostbyaddr($host);
442
+		}
443
+
444
+		/* Get the TLD of the hostname. */
445
+		$pos = strrpos($checkHost, '.');
446
+		if ($pos === false) {
447
+			return false;
448
+		}
449
+		$domain = String::lower(substr($checkHost, $pos + 1));
450
+
451
+		/* Try lookup via TLD first. */
452
+		if (!in_array($domain, $generic)) {
453
+			require 'Horde/NLS/tld.php';
454
+			if (isset($tld[$domain])) {
455
+				return array('code' => $domain, 'name' => $tld[$domain]);
456
+			}
457
+		}
458
+
459
+		/* Try GeoIP lookup next. */
460
+		if (!empty($conf['geoip']['datafile'])) {
461
+			require_once 'Horde/NLS/GeoIP.php';
462
+			$geoip = &NLS_GeoIP::singleton($conf['geoip']['datafile']);
463
+			$id = $geoip->countryIdByName($checkHost);
464
+			if (!empty($id)) {
465
+				return array('code' => String::lower($GLOBALS['GEOIP_COUNTRY_CODES'][$id]), 'name' => $GLOBALS['GEOIP_COUNTRY_NAMES'][$id]);
466
+			}
467
+		}
468
+
469
+		return false;
470
+	}
471
+
472
+	/**
473
+	 * Returns a Horde image link to the country flag.
474
+	 *
475
+	 * @access public
476
+	 *
477
+	 * @param string $host  The hostname or IP address.
478
+	 *
479
+	 * @return string  The image URL, or the empty string on error.
480
+	 */
481
+	function generateFlagImageByHost($host)
482
+	{
483
+		global $registry;
484
+
485
+		$data = NLS::getCountryByHost($host);
486
+		if ($data !== false) {
487
+			$img = $data['code'] . '.png';
488
+			if (file_exists($registry->get('themesfs', 'horde') . '/graphics/flags/' . $img)) {
489
+				return Horde::img($img, $data['name'], '', $registry->getImageDir('horde') . '/flags');
490
+			} else {
491
+				return '[' . $data['name'] . ']';
492
+			}
493
+		}
494
+
495
+		return '';
496
+	}
497
+
498
+	/**
499
+	 * Returns either a specific or all ISO-3166 country names.
500
+	 *
501
+	 * @access public
502
+	 *
503
+	 * @param optional string $code  The ISO 3166 country code.
504
+	 *
505
+	 * @return mixed  If a country code has been requested will return the
506
+	 *                corresponding country name. If empty will return an
507
+	 *                array of all the country codes and their names.
508
+	 */
509
+	function &getCountryISO($code = '')
510
+	{
511
+		static $countries = array();
512
+		if (empty($countries)) {
513
+			require_once 'Horde/NLS/countries.php';
514
+		}
515
+		if (empty($code)) {
516
+			return $countries;
517
+		} elseif (isset($countries[$code])) {
518
+			return $countries[$code];
519
+		}
520
+		return false;
521
+	}
522 522
 
523 523
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -14 removed lines patch added patch discarded remove patch
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
      */
94 94
     function setLang($lang = null)
95 95
     {
96
-        include_once HORDE_BASE . '/config/nls.php';
96
+        include_once HORDE_BASE.'/config/nls.php';
97 97
 
98 98
         if (empty($lang) || !NLS::isValid($lang)) {
99 99
             $lang = NLS::select();
@@ -106,12 +106,12 @@  discard block
 block discarded – undo
106 106
         $GLOBALS['language'] = $lang;
107 107
 
108 108
         /* First try language with the current charset. */
109
-        $lang_charset = $lang . '.' . NLS::getCharset();
109
+        $lang_charset = $lang.'.'.NLS::getCharset();
110 110
         if ($lang_charset != setlocale(LC_ALL, $lang_charset)) {
111 111
             /* Next try language with its default charset. */
112 112
             global $nls;
113 113
             $charset = !empty($nls['charsets'][$lang]) ? $nls['charsets'][$lang] : $nls['defaults']['charset'];
114
-            $lang_charset = $lang . '.' . $charset;
114
+            $lang_charset = $lang.'.'.$charset;
115 115
             NLS::_cachedCharset(0, $charset);
116 116
             if ($lang_charset != setlocale(LC_ALL, $lang_charset)) {
117 117
                 /* At last try language solely. */
@@ -119,8 +119,8 @@  discard block
 block discarded – undo
119 119
                 setlocale(LC_ALL, $lang_charset);
120 120
             }
121 121
         }
122
-        @putenv('LANG=' . $lang_charset);
123
-        @putenv('LANGUAGE=' . $lang_charset);
122
+        @putenv('LANG='.$lang_charset);
123
+        @putenv('LANGUAGE='.$lang_charset);
124 124
     }
125 125
 
126 126
     /**
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
         }
145 145
 
146 146
         if (!headers_sent()) {
147
-            header('Content-Type: text/html; charset=' . $charset);
147
+            header('Content-Type: text/html; charset='.$charset);
148 148
         }
149 149
     }
150 150
 
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
         $lang_parts = explode('_', $trans_lang);
188 188
         $trans_lang = String::lower($lang_parts[0]);
189 189
         if (isset($lang_parts[1])) {
190
-            $trans_lang .= '_' . String::upper($lang_parts[1]);
190
+            $trans_lang .= '_'.String::upper($lang_parts[1]);
191 191
         }
192 192
 
193 193
         // See if we get a match for this
@@ -316,8 +316,7 @@  discard block
 block discarded – undo
316 316
         if (!empty($charset)) {
317 317
             return $charset;
318 318
         }
319
-        return isset($nls['emails'][$language]) ? $nls['emails'][$language] :
320
-               (isset($nls['charsets'][$language]) ? $nls['charsets'][$language] : $nls['defaults']['charset']);
319
+        return isset($nls['emails'][$language]) ? $nls['emails'][$language] : (isset($nls['charsets'][$language]) ? $nls['charsets'][$language] : $nls['defaults']['charset']);
321 320
     }
322 321
 
323 322
     /**
@@ -368,7 +367,7 @@  discard block
 block discarded – undo
368 367
 
369 368
         $tz = $prefs->getValue('timezone');
370 369
         if (!empty($tz)) {
371
-            @putenv('TZ=' . $tz);
370
+            @putenv('TZ='.$tz);
372 371
         }
373 372
     }
374 373
 
@@ -484,11 +483,11 @@  discard block
 block discarded – undo
484 483
 
485 484
         $data = NLS::getCountryByHost($host);
486 485
         if ($data !== false) {
487
-            $img = $data['code'] . '.png';
488
-            if (file_exists($registry->get('themesfs', 'horde') . '/graphics/flags/' . $img)) {
489
-                return Horde::img($img, $data['name'], '', $registry->getImageDir('horde') . '/flags');
486
+            $img = $data['code'].'.png';
487
+            if (file_exists($registry->get('themesfs', 'horde').'/graphics/flags/'.$img)) {
488
+                return Horde::img($img, $data['name'], '', $registry->getImageDir('horde').'/flags');
490 489
             } else {
491
-                return '[' . $data['name'] . ']';
490
+                return '['.$data['name'].']';
492 491
             }
493 492
         }
494 493
 
Please login to merge, or discard this patch.
Braces   +114 added lines, -52 removed lines patch added patch discarded remove patch
@@ -22,7 +22,8 @@  discard block
 block discarded – undo
22 22
  * @since   Horde 3.0
23 23
  * @package Horde_NLS
24 24
  */
25
-class NLS {
25
+class NLS
26
+{
26 27
 
27 28
     /**
28 29
      * Selects the most preferred language for the current client session.
@@ -39,43 +40,60 @@  discard block
 block discarded – undo
39 40
 
40 41
         /* First, check if language pref is locked and, if so, set it to its
41 42
            value */
42
-        if (isset($prefs) && $prefs->isLocked('language')) {
43
+        if (isset($prefs) && $prefs->isLocked('language'))
44
+        {
43 45
             $language = $prefs->getValue('language');
44 46
         /* Check if the user selected a language from the login screen */
45
-        } elseif (!empty($lang)) {
47
+        }
48
+        elseif (!empty($lang))
49
+        {
46 50
             $language = $lang;
47 51
         /* Check if we have a language set in a cookie */
48
-        } elseif (isset($_SESSION['horde_language'])) {
52
+        }
53
+        elseif (isset($_SESSION['horde_language']))
54
+        {
49 55
             $language = $_SESSION['horde_language'];
50 56
         /* Use site-wide default, if one is defined */
51
-        } elseif (!empty($nls['defaults']['language'])) {
57
+        }
58
+        elseif (!empty($nls['defaults']['language']))
59
+        {
52 60
             $language = $nls['defaults']['language'];
53 61
         /* Try browser-accepted languages. */
54
-        } elseif (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
62
+        }
63
+        elseif (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
64
+        {
55 65
             /* The browser supplies a list, so return the first valid one. */
56 66
             $browser_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
57
-            foreach ($browser_langs as $lang) {
67
+            foreach ($browser_langs as $lang)
68
+            {
58 69
                 /* Strip quality value for language */
59
-                if (($pos = strpos($lang, ';')) !== false) {
70
+                if (($pos = strpos($lang, ';')) !== false)
71
+                {
60 72
                     $lang = substr($lang, 0, $pos);
61 73
                 }
62 74
                 $lang = NLS::_map(trim($lang));
63
-                if (NLS::isValid($lang)) {
75
+                if (NLS::isValid($lang))
76
+                {
64 77
                     $language = $lang;
65 78
                     break;
66 79
                 }
67 80
                 /* In case no full match, save best guess based on prefix */
68 81
                 if (!isset($partial_lang) &&
69
-                    NLS::isValid(NLS::_map(substr($lang, 0, 2)))) {
82
+                    NLS::isValid(NLS::_map(substr($lang, 0, 2))))
83
+                {
70 84
                     $partial_lang = NLS::_map(substr($lang, 0, 2));
71 85
                 }
72 86
             }
73 87
         }
74 88
 
75
-        if (!isset($language)) {
76
-            if (isset($partial_lang)) {
89
+        if (!isset($language))
90
+        {
91
+            if (isset($partial_lang))
92
+            {
77 93
                 $language = $partial_lang;
78
-            } else {
94
+            }
95
+            else
96
+            {
79 97
                 /* No dice auto-detecting, default to US English. */
80 98
                 $language = 'en_US';
81 99
             }
@@ -95,11 +113,13 @@  discard block
 block discarded – undo
95 113
     {
96 114
         include_once HORDE_BASE . '/config/nls.php';
97 115
 
98
-        if (empty($lang) || !NLS::isValid($lang)) {
116
+        if (empty($lang) || !NLS::isValid($lang))
117
+        {
99 118
             $lang = NLS::select();
100 119
         }
101 120
 
102
-        if (isset($GLOBALS['language']) && $GLOBALS['language'] == $lang) {
121
+        if (isset($GLOBALS['language']) && $GLOBALS['language'] == $lang)
122
+        {
103 123
             return;
104 124
         }
105 125
 
@@ -107,13 +127,15 @@  discard block
 block discarded – undo
107 127
 
108 128
         /* First try language with the current charset. */
109 129
         $lang_charset = $lang . '.' . NLS::getCharset();
110
-        if ($lang_charset != setlocale(LC_ALL, $lang_charset)) {
130
+        if ($lang_charset != setlocale(LC_ALL, $lang_charset))
131
+        {
111 132
             /* Next try language with its default charset. */
112 133
             global $nls;
113 134
             $charset = !empty($nls['charsets'][$lang]) ? $nls['charsets'][$lang] : $nls['defaults']['charset'];
114 135
             $lang_charset = $lang . '.' . $charset;
115 136
             NLS::_cachedCharset(0, $charset);
116
-            if ($lang_charset != setlocale(LC_ALL, $lang_charset)) {
137
+            if ($lang_charset != setlocale(LC_ALL, $lang_charset))
138
+            {
117 139
                 /* At last try language solely. */
118 140
                 $lang_charset = $lang;
119 141
                 setlocale(LC_ALL, $lang_charset);
@@ -139,11 +161,13 @@  discard block
 block discarded – undo
139 161
         textdomain($app);
140 162
 
141 163
         /* The existence of this function depends on the platform. */
142
-        if (function_exists('bind_textdomain_codeset')) {
164
+        if (function_exists('bind_textdomain_codeset'))
165
+        {
143 166
             NLS::_cachedCharset(0, bind_textdomain_codeset($app, $charset));
144 167
         }
145 168
 
146
-        if (!headers_sent()) {
169
+        if (!headers_sent())
170
+        {
147 171
             header('Content-Type: text/html; charset=' . $charset);
148 172
         }
149 173
     }
@@ -186,12 +210,14 @@  discard block
 block discarded – undo
186 210
         $trans_lang = str_replace('-', '_', $language);
187 211
         $lang_parts = explode('_', $trans_lang);
188 212
         $trans_lang = String::lower($lang_parts[0]);
189
-        if (isset($lang_parts[1])) {
213
+        if (isset($lang_parts[1]))
214
+        {
190 215
             $trans_lang .= '_' . String::upper($lang_parts[1]);
191 216
         }
192 217
 
193 218
         // See if we get a match for this
194
-        if (!empty($aliases[$trans_lang])) {
219
+        if (!empty($aliases[$trans_lang]))
220
+        {
195 221
             return $aliases[$trans_lang];
196 222
         }
197 223
 
@@ -218,24 +244,30 @@  discard block
 block discarded – undo
218 244
         /* Get cached results. */
219 245
         $cacheKey = intval($original);
220 246
         $charset = NLS::_cachedCharset($cacheKey);
221
-        if (!is_null($charset)) {
247
+        if (!is_null($charset))
248
+        {
222 249
             return $charset;
223 250
         }
224 251
 
225
-        if ($original) {
252
+        if ($original)
253
+        {
226 254
             $charset = empty($nls['charsets'][$language]) ? $nls['defaults']['charset'] : $nls['charsets'][$language];
227
-        } else {
255
+        }
256
+        else
257
+        {
228 258
             require_once 'Horde/Browser.php';
229 259
             $browser = &Browser::singleton();
230 260
 
231 261
             if ($browser->hasFeature('utf') &&
232 262
                 (Util::extensionExists('iconv') ||
233
-                 Util::extensionExists('mbstring'))) {
263
+                 Util::extensionExists('mbstring')))
264
+            {
234 265
                 $charset = 'UTF-8';
235 266
             }
236 267
         }
237 268
 
238
-        if (is_null($charset)) {
269
+        if (is_null($charset))
270
+        {
239 271
             $charset = NLS::getExternalCharset();
240 272
         }
241 273
 
@@ -258,15 +290,18 @@  discard block
 block discarded – undo
258 290
 
259 291
         /* Get cached results. */
260 292
         $charset = NLS::_cachedCharset(2);
261
-        if (!is_null($charset)) {
293
+        if (!is_null($charset))
294
+        {
262 295
             return $charset;
263 296
         }
264 297
 
265 298
         $lang_charset = setlocale(LC_ALL, 0);
266 299
         if (strpos($lang_charset, ';') === false &&
267
-            strpos($lang_charset, '/') === false) {
300
+            strpos($lang_charset, '/') === false)
301
+        {
268 302
             $lang_charset = explode('.', $lang_charset);
269
-            if ((count($lang_charset) == 2) && !empty($lang_charset[1])) {
303
+            if ((count($lang_charset) == 2) && !empty($lang_charset[1]))
304
+            {
270 305
                 NLS::_cachedCharset(2, $lang_charset[1]);
271 306
                 return $lang_charset[1];
272 307
             }
@@ -291,13 +326,17 @@  discard block
 block discarded – undo
291 326
     {
292 327
         static $cache;
293 328
 
294
-        if (!isset($cache)) {
329
+        if (!isset($cache))
330
+        {
295 331
             $cache = array();
296 332
         }
297 333
 
298
-        if ($charset == null) {
334
+        if ($charset == null)
335
+        {
299 336
             return isset($cache[$index]) ? $cache[$index] : null;
300
-        } else {
337
+        }
338
+        else
339
+        {
301 340
             $cache[$index] = $charset;
302 341
         }
303 342
     }
@@ -313,7 +352,8 @@  discard block
 block discarded – undo
313 352
         global $prefs, $language, $nls;
314 353
 
315 354
         $charset = $prefs->getValue('sending_charset');
316
-        if (!empty($charset)) {
355
+        if (!empty($charset))
356
+        {
317 357
             return $charset;
318 358
         }
319 359
         return isset($nls['emails'][$language]) ? $nls['emails'][$language] :
@@ -333,13 +373,17 @@  discard block
 block discarded – undo
333 373
     {
334 374
         static $check;
335 375
 
336
-        if (is_null($charset) || empty($charset)) {
376
+        if (is_null($charset) || empty($charset))
377
+        {
337 378
             return false;
338 379
         }
339 380
 
340
-        if (isset($check[$charset])) {
381
+        if (isset($check[$charset]))
382
+        {
341 383
             return $check[$charset];
342
-        } elseif (!isset($check)) {
384
+        }
385
+        elseif (!isset($check))
386
+        {
343 387
             $check = array();
344 388
         }
345 389
 
@@ -347,7 +391,8 @@  discard block
 block discarded – undo
347 391
 
348 392
         ini_set('track_errors', 1);
349 393
         @htmlspecialchars('', ENT_COMPAT, $charset);
350
-        if (isset($php_errormsg)) {
394
+        if (isset($php_errormsg))
395
+        {
351 396
             $valid = false;
352 397
         }
353 398
         ini_restore('track_errors');
@@ -367,7 +412,8 @@  discard block
 block discarded – undo
367 412
         global $prefs;
368 413
 
369 414
         $tz = $prefs->getValue('timezone');
370
-        if (!empty($tz)) {
415
+        if (!empty($tz))
416
+        {
371 417
             @putenv('TZ=' . $tz);
372 418
         }
373 419
     }
@@ -384,7 +430,8 @@  discard block
 block discarded – undo
384 430
     {
385 431
         static $lc_info;
386 432
 
387
-        if (!isset($lc_info)) {
433
+        if (!isset($lc_info))
434
+        {
388 435
             $lc_info = localeconv();
389 436
         }
390 437
 
@@ -406,7 +453,8 @@  discard block
 block discarded – undo
406 453
     {
407 454
         static $nl_info = array();
408 455
 
409
-        if (!isset($nl_info[$item])) {
456
+        if (!isset($nl_info[$item]))
457
+        {
410 458
             $nl_info[$item] = nl_langinfo($item);
411 459
         }
412 460
 
@@ -437,31 +485,37 @@  discard block
 block discarded – undo
437 485
         );
438 486
 
439 487
         $checkHost = $host;
440
-        if (preg_match('/^\d+\.\d+\.\d+\.\d+$/', $host)) {
488
+        if (preg_match('/^\d+\.\d+\.\d+\.\d+$/', $host))
489
+        {
441 490
             $checkHost = @gethostbyaddr($host);
442 491
         }
443 492
 
444 493
         /* Get the TLD of the hostname. */
445 494
         $pos = strrpos($checkHost, '.');
446
-        if ($pos === false) {
495
+        if ($pos === false)
496
+        {
447 497
             return false;
448 498
         }
449 499
         $domain = String::lower(substr($checkHost, $pos + 1));
450 500
 
451 501
         /* Try lookup via TLD first. */
452
-        if (!in_array($domain, $generic)) {
502
+        if (!in_array($domain, $generic))
503
+        {
453 504
             require 'Horde/NLS/tld.php';
454
-            if (isset($tld[$domain])) {
505
+            if (isset($tld[$domain]))
506
+            {
455 507
                 return array('code' => $domain, 'name' => $tld[$domain]);
456 508
             }
457 509
         }
458 510
 
459 511
         /* Try GeoIP lookup next. */
460
-        if (!empty($conf['geoip']['datafile'])) {
512
+        if (!empty($conf['geoip']['datafile']))
513
+        {
461 514
             require_once 'Horde/NLS/GeoIP.php';
462 515
             $geoip = &NLS_GeoIP::singleton($conf['geoip']['datafile']);
463 516
             $id = $geoip->countryIdByName($checkHost);
464
-            if (!empty($id)) {
517
+            if (!empty($id))
518
+            {
465 519
                 return array('code' => String::lower($GLOBALS['GEOIP_COUNTRY_CODES'][$id]), 'name' => $GLOBALS['GEOIP_COUNTRY_NAMES'][$id]);
466 520
             }
467 521
         }
@@ -483,11 +537,15 @@  discard block
 block discarded – undo
483 537
         global $registry;
484 538
 
485 539
         $data = NLS::getCountryByHost($host);
486
-        if ($data !== false) {
540
+        if ($data !== false)
541
+        {
487 542
             $img = $data['code'] . '.png';
488
-            if (file_exists($registry->get('themesfs', 'horde') . '/graphics/flags/' . $img)) {
543
+            if (file_exists($registry->get('themesfs', 'horde') . '/graphics/flags/' . $img))
544
+            {
489 545
                 return Horde::img($img, $data['name'], '', $registry->getImageDir('horde') . '/flags');
490
-            } else {
546
+            }
547
+            else
548
+            {
491 549
                 return '[' . $data['name'] . ']';
492 550
             }
493 551
         }
@@ -509,12 +567,16 @@  discard block
 block discarded – undo
509 567
     function &getCountryISO($code = '')
510 568
     {
511 569
         static $countries = array();
512
-        if (empty($countries)) {
570
+        if (empty($countries))
571
+        {
513 572
             require_once 'Horde/NLS/countries.php';
514 573
         }
515
-        if (empty($code)) {
574
+        if (empty($code))
575
+        {
516 576
             return $countries;
517
-        } elseif (isset($countries[$code])) {
577
+        }
578
+        elseif (isset($countries[$code]))
579
+        {
518 580
             return $countries[$code];
519 581
         }
520 582
         return false;
Please login to merge, or discard this patch.
phpgwapi/inc/horde/Horde/Registry.php 4 patches
Doc Comments   +4 added lines, -2 removed lines patch added patch discarded remove patch
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
      *
94 94
      * @param optional integer $session_flags  Any session flags.
95 95
      *
96
-     * @return object Registry  The Horde Registry instance.
96
+     * @return Registry Registry  The Horde Registry instance.
97 97
      */
98 98
     function &singleton($session_flags = 0)
99 99
     {
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
      * @param string $path          The application string.
595 595
      * @param optional string $app  The application being called.
596 596
      *
597
-     * @return  TODO
597
+     * @return  string
598 598
      *          Returns PEAR_Error on error.
599 599
      */
600 600
     function applicationWebPath($path, $app = null)
@@ -729,6 +729,7 @@  discard block
 block discarded – undo
729 729
      *
730 730
      * @access public
731 731
      *
732
+     * @param integer $permission
732 733
      * @return boolean  Whether or not access is allowed.
733 734
      */
734 735
     function hasPermission($app, $permission = PERMS_READ)
@@ -921,6 +922,7 @@  discard block
 block discarded – undo
921 922
      * @param optional string $app  The application for which to get the
922 923
      *                              image directory. If blank will default
923 924
      *                              to current application.
925
+     * @param string $app
924 926
      *
925 927
      * @return string  The image directory uri path.
926 928
      */
Please login to merge, or discard this patch.
Indentation   +919 added lines, -919 removed lines patch added patch discarded remove patch
@@ -28,160 +28,160 @@  discard block
 block discarded – undo
28 28
  */
29 29
 class Registry {
30 30
 
31
-    /**
32
-     * Hash storing all of the known services and callbacks.
33
-     *
34
-     * @var array $_apiCache
35
-     */
36
-    var $_apiCache = array();
37
-
38
-    /**
39
-     * Hash storing all known data types.
40
-     *
41
-     * @var array $_typeCache
42
-     */
43
-    var $_typeCache = array();
44
-
45
-    /**
46
-     * Hash storing all of the registered interfaces that applications
47
-     * provide.
48
-     *
49
-     * @var array $_interfaces
50
-     */
51
-    var $_interfaces = array();
52
-
53
-    /**
54
-     * Hash storing information on each registry-aware application.
55
-     *
56
-     * @var array $applications
57
-     */
58
-    var $applications = array();
59
-
60
-    /**
61
-     * Stack of in-use applications.
62
-     *
63
-     * @var array $_appStack
64
-     */
65
-    var $_appStack = array();
66
-
67
-    /**
68
-     * Quick pointer to the current application.
69
-     *
70
-     * @var $_currentApp
71
-     */
72
-    var $_currentApp = null;
73
-
74
-    /**
75
-     * Cache of $prefs objects
76
-     *
77
-     * @var array $_prefsCache
78
-     */
79
-    var $_prefsCache = array();
80
-
81
-    /**
82
-     * Cache of application configurations.
83
-     *
84
-     * @var array $_confCache
85
-     */
86
-    var $_confCache = array();
87
-
88
-    /**
89
-     * Returns a reference to the global Registry object, only
90
-     * creating it if it doesn't already exist.
91
-     *
92
-     * This method must be invoked as: $registry = &Registry::singleton()
93
-     *
94
-     * @param optional integer $session_flags  Any session flags.
95
-     *
96
-     * @return object Registry  The Horde Registry instance.
97
-     */
98
-    function &singleton($session_flags = 0)
99
-    {
100
-        static $registry;
101
-
102
-        if (!isset($registry)) {
103
-            $registry = new Registry($session_flags);
104
-        }
105
-
106
-        return $registry;
107
-    }
108
-
109
-    /**
110
-     * Create a new registry instance. Should never be called except
111
-     * by &Registry::singleton().
112
-     *
113
-     * @param optional integer $session_flags  Any session flags.
114
-     *
115
-     * @access private
116
-     */
117
-    function Registry($session_flags = 0)
118
-    {
119
-        /* Import and global Horde's configuration values. */
120
-        $this->importConfig('horde');
121
-
122
-        /* Start a session. */
123
-        if ($session_flags & HORDE_SESSION_NONE) {
124
-            /* Never start a session if the session flags include
31
+	/**
32
+	 * Hash storing all of the known services and callbacks.
33
+	 *
34
+	 * @var array $_apiCache
35
+	 */
36
+	var $_apiCache = array();
37
+
38
+	/**
39
+	 * Hash storing all known data types.
40
+	 *
41
+	 * @var array $_typeCache
42
+	 */
43
+	var $_typeCache = array();
44
+
45
+	/**
46
+	 * Hash storing all of the registered interfaces that applications
47
+	 * provide.
48
+	 *
49
+	 * @var array $_interfaces
50
+	 */
51
+	var $_interfaces = array();
52
+
53
+	/**
54
+	 * Hash storing information on each registry-aware application.
55
+	 *
56
+	 * @var array $applications
57
+	 */
58
+	var $applications = array();
59
+
60
+	/**
61
+	 * Stack of in-use applications.
62
+	 *
63
+	 * @var array $_appStack
64
+	 */
65
+	var $_appStack = array();
66
+
67
+	/**
68
+	 * Quick pointer to the current application.
69
+	 *
70
+	 * @var $_currentApp
71
+	 */
72
+	var $_currentApp = null;
73
+
74
+	/**
75
+	 * Cache of $prefs objects
76
+	 *
77
+	 * @var array $_prefsCache
78
+	 */
79
+	var $_prefsCache = array();
80
+
81
+	/**
82
+	 * Cache of application configurations.
83
+	 *
84
+	 * @var array $_confCache
85
+	 */
86
+	var $_confCache = array();
87
+
88
+	/**
89
+	 * Returns a reference to the global Registry object, only
90
+	 * creating it if it doesn't already exist.
91
+	 *
92
+	 * This method must be invoked as: $registry = &Registry::singleton()
93
+	 *
94
+	 * @param optional integer $session_flags  Any session flags.
95
+	 *
96
+	 * @return object Registry  The Horde Registry instance.
97
+	 */
98
+	function &singleton($session_flags = 0)
99
+	{
100
+		static $registry;
101
+
102
+		if (!isset($registry)) {
103
+			$registry = new Registry($session_flags);
104
+		}
105
+
106
+		return $registry;
107
+	}
108
+
109
+	/**
110
+	 * Create a new registry instance. Should never be called except
111
+	 * by &Registry::singleton().
112
+	 *
113
+	 * @param optional integer $session_flags  Any session flags.
114
+	 *
115
+	 * @access private
116
+	 */
117
+	function Registry($session_flags = 0)
118
+	{
119
+		/* Import and global Horde's configuration values. */
120
+		$this->importConfig('horde');
121
+
122
+		/* Start a session. */
123
+		if ($session_flags & HORDE_SESSION_NONE) {
124
+			/* Never start a session if the session flags include
125 125
                HORDE_SESSION_NONE. */
126
-            $_SESSION = array();
127
-        } else {
128
-            Horde::setupSessionHandler();
129
-            @session_start();
130
-            if ($session_flags & HORDE_SESSION_READONLY) {
131
-                /* Close the session immediately so no changes can be
126
+			$_SESSION = array();
127
+		} else {
128
+			Horde::setupSessionHandler();
129
+			@session_start();
130
+			if ($session_flags & HORDE_SESSION_READONLY) {
131
+				/* Close the session immediately so no changes can be
132 132
                    made but values are still available. */
133
-                @session_write_close();
134
-            }
135
-        }
133
+				@session_write_close();
134
+			}
135
+		}
136 136
 
137
-        /* Read the registry configuration file. */
138
-        require_once HORDE_BASE . '/config/registry.php';
137
+		/* Read the registry configuration file. */
138
+		require_once HORDE_BASE . '/config/registry.php';
139 139
 
140
-        /* Initialize the localization routines and variables. */
140
+		/* Initialize the localization routines and variables. */
141 141
 #        NLS::setLang();
142 142
 #        NLS::setTextdomain('horde', HORDE_BASE . '/locale', NLS::getCharset());
143 143
 #        String::setDefaultCharset(NLS::getCharset());
144 144
 
145
-        /* Stop system if Horde is inactive. */
146
-        if ($this->applications['horde']['status'] == 'inactive') {
147
-            Horde::fatal(_("This system is currently deactivated."), __FILE__, __LINE__);
148
-        }
145
+		/* Stop system if Horde is inactive. */
146
+		if ($this->applications['horde']['status'] == 'inactive') {
147
+			Horde::fatal(_("This system is currently deactivated."), __FILE__, __LINE__);
148
+		}
149 149
 
150
-        /* Scan for all APIs provided by each app, and set other
150
+		/* Scan for all APIs provided by each app, and set other
151 151
          * common defaults like templates and graphics. */
152
-        $appList = array_keys($this->applications);
153
-        foreach ($appList as $appName) {
154
-            $app = &$this->applications[$appName];
155
-            if (($app['status'] == 'heading') ||
156
-                ($app['status'] == 'inactive') ||
157
-                ($app['status'] == 'admin' && !Auth::isAdmin())) {
158
-                continue;
159
-            }
160
-            if (isset($app['provides'])) {
161
-                if (is_array($app['provides'])) {
162
-                    foreach ($app['provides'] as $interface) {
163
-                        $this->_interfaces[$interface] = $appName;
164
-                    }
165
-                } else {
166
-                    $this->_interfaces[$app['provides']] = $appName;
167
-                }
168
-            }
169
-            if (!isset($app['templates']) && isset($app['fileroot'])) {
170
-                $app['templates'] = $app['fileroot'] . '/templates';
171
-            }
172
-            if (!isset($app['jsuri']) && isset($app['webroot'])) {
173
-                $app['jsuri'] = $app['webroot'] . '/js';
174
-            }
175
-            if (!isset($app['jsfs']) && isset($app['fileroot'])) {
176
-                $app['jsfs'] = $app['fileroot'] . '/js';
177
-            }
178
-            if (!isset($app['themesuri']) && isset($app['webroot'])) {
179
-                $app['themesuri'] = $app['webroot'] . '/themes';
180
-            }
181
-            if (!isset($app['themesfs']) && isset($app['fileroot'])) {
182
-                $app['themesfs'] = $app['fileroot'] . '/themes';
183
-            }
184
-        }
152
+		$appList = array_keys($this->applications);
153
+		foreach ($appList as $appName) {
154
+			$app = &$this->applications[$appName];
155
+			if (($app['status'] == 'heading') ||
156
+				($app['status'] == 'inactive') ||
157
+				($app['status'] == 'admin' && !Auth::isAdmin())) {
158
+				continue;
159
+			}
160
+			if (isset($app['provides'])) {
161
+				if (is_array($app['provides'])) {
162
+					foreach ($app['provides'] as $interface) {
163
+						$this->_interfaces[$interface] = $appName;
164
+					}
165
+				} else {
166
+					$this->_interfaces[$app['provides']] = $appName;
167
+				}
168
+			}
169
+			if (!isset($app['templates']) && isset($app['fileroot'])) {
170
+				$app['templates'] = $app['fileroot'] . '/templates';
171
+			}
172
+			if (!isset($app['jsuri']) && isset($app['webroot'])) {
173
+				$app['jsuri'] = $app['webroot'] . '/js';
174
+			}
175
+			if (!isset($app['jsfs']) && isset($app['fileroot'])) {
176
+				$app['jsfs'] = $app['fileroot'] . '/js';
177
+			}
178
+			if (!isset($app['themesuri']) && isset($app['webroot'])) {
179
+				$app['themesuri'] = $app['webroot'] . '/themes';
180
+			}
181
+			if (!isset($app['themesfs']) && isset($app['fileroot'])) {
182
+				$app['themesfs'] = $app['fileroot'] . '/themes';
183
+			}
184
+		}
185 185
 
186 186
 #        /* Create the global Perms object. */
187 187
 #        $GLOBALS['perms'] = &Perms::singleton();
@@ -190,639 +190,639 @@  discard block
 block discarded – undo
190 190
 #        $notification = &Notification::singleton();
191 191
 #        $notification->attach('javascript');
192 192
 
193
-        /* Register access key logger for translators. */
194
-        if (@$GLOBALS['conf']['log_accesskeys']) {
195
-            register_shutdown_function(create_function('', 'Horde::getAccessKey(null, null, true);'));
196
-        }
197
-    }
198
-
199
-    /**
200
-     * Return a list of the installed and registered applications.
201
-     *
202
-     * @since Horde 2.2
203
-     *
204
-     * @access public
205
-     *
206
-     * @param array   $filter      (optional) An array of the statuses that
207
-     *                             should be returned. Defaults to non-hidden.
208
-     * @param boolean $assoc       (optional) Associative array with app names
209
-     *                             as keys.
210
-     * @param integer $permission  (optional) The permission level to check
211
-     *                             for in the list. Defaults to PERMS_SHOW.
212
-     *
213
-     * @return array  List of apps registered with Horde. If no
214
-     *                applications are defined returns an empty array.
215
-     */
216
-    function listApps($filter = null, $assoc = false, $permission = PERMS_SHOW)
217
-    {
218
-        $apps = array();
219
-        if (is_null($filter)) {
220
-            $filter = array('notoolbar', 'active');
221
-        }
222
-
223
-        foreach ($this->applications as $app => $params) {
224
-            if (in_array($params['status'], $filter) &&
225
-                (defined('AUTH_HANDLER') || $this->hasPermission($app, $permission))) {
226
-                $assoc ? $apps[$app] = $app : $apps[] = $app;
227
-            }
228
-        }
229
-
230
-        return $apps;
231
-    }
232
-
233
-    /**
234
-     * Returns all available registry APIs.
235
-     *
236
-     * @access public
237
-     *
238
-     * @return array  The API list.
239
-     */
240
-    function listAPIs()
241
-    {
242
-        $apis = array();
243
-
244
-        foreach (array_keys($this->_interfaces) as $interface) {
245
-            @list($api, ) = explode('/', $interface);
246
-            $apis[] = $api;
247
-        }
248
-
249
-        return array_unique($apis);
250
-    }
251
-
252
-    /**
253
-     * Returns all of the available registry methods, or alternately
254
-     * only those for a specified API.
255
-     *
256
-     * @access public
257
-     *
258
-     * @param optional string $api  Defines the API for which the methods
259
-     *                              shall be returned.
260
-     *
261
-     * @return array  The method list.
262
-     */
263
-    function listMethods($api = null)
264
-    {
265
-        $methods = array();
266
-
267
-        $this->_fillAPICache();
268
-
269
-        foreach (array_keys($this->applications) as $app) {
270
-            if (isset($this->applications[$app]['provides'])) {
271
-                $provides = $this->applications[$app]['provides'];
272
-                if (!is_array($provides)) {
273
-                    $provides = array($provides);
274
-                }
275
-            } else {
276
-                $provides = array();
277
-            }
278
-
279
-            foreach ($provides as $method) {
280
-                if (strpos($method, '/') !== false) {
281
-                    if (is_null($api) ||
282
-                        (substr($method, 0, strlen($api)) == $api)) {
283
-                        $methods[] = $method;
284
-                    }
285
-                } elseif (is_null($api) || ($method == $api)) {
286
-                    if (isset($this->_apiCache[$app])) {
287
-                        foreach (array_keys($this->_apiCache[$app]) as $service) {
288
-                            $methods[] = $method . '/' . $service;
289
-                        }
290
-                    }
291
-                }
292
-            }
293
-        }
294
-
295
-        return array_unique($methods);
296
-    }
297
-
298
-    /**
299
-     * Returns all of the available registry data types.
300
-     *
301
-     * @access public
302
-     *
303
-     * @return array  The data type list.
304
-     */
305
-    function listTypes()
306
-    {
307
-        $this->_fillAPICache();
308
-        return $this->_typeCache;
309
-    }
310
-
311
-    /**
312
-     * Returns a method's signature.
313
-     *
314
-     * @access public
315
-     *
316
-     * @param string $method  The full name of the method to check for.
317
-     *
318
-     * @return array  A two dimensional array. The first element contains an
319
-     *                array with the parameter names, the second one the return
320
-     *                type.
321
-     */
322
-    function getSignature($method)
323
-    {
324
-        if (!($app = $this->hasMethod($method))) {
325
-            return;
326
-        }
327
-
328
-        $this->_fillAPICache();
329
-
330
-        @list(, $function) = explode('/', $method);
331
-        if (isset($this->_apiCache[$app][$function]['type']) &&
332
-            isset($this->_apiCache[$app][$function]['args'])) {
333
-            return array($this->_apiCache[$app][$function]['args'], $this->_apiCache[$app][$function]['type']);
334
-        }
335
-    }
336
-
337
-    /**
338
-     * Determine if an interface is implemented by an active
339
-     * application.
340
-     *
341
-     * @access public
342
-     *
343
-     * @param string $interface  The interface to check for.
344
-     *
345
-     * @return mixed  The application implementing $interface if we have it,
346
-     *                false if the interface is not implemented.
347
-     */
348
-    function hasInterface($interface)
349
-    {
350
-        return !empty($this->_interfaces[$interface]) ?
351
-            $this->_interfaces[$interface] :
352
-            false;
353
-    }
354
-
355
-    /**
356
-     * Determine if a method has been registered with the registry.
357
-     *
358
-     * @access public
359
-     *
360
-     * @param string  $method      The full name of the method to check for.
361
-     * @param string  $app         (optional) Only check this application.
362
-     *
363
-     * @return mixed  The application implementing $method if we have it,
364
-     *                false if the method doesn't exist.
365
-     */
366
-    function hasMethod($method, $app = null)
367
-    {
368
-        if (is_null($app)) {
369
-            @list($interface, $call) = explode('/', $method);
370
-            if (!empty($this->_interfaces[$method])) {
371
-                $app = $this->_interfaces[$method];
372
-            } elseif (!empty($this->_interfaces[$interface])) {
373
-                $app = $this->_interfaces[$interface];
374
-            } else {
375
-                return false;
376
-            }
377
-        } else {
378
-            $call = $method;
379
-        }
380
-
381
-        $this->_fillAPICache();
382
-
383
-        return !empty($this->_apiCache[$app][$call]) ? $app : false;
384
-    }
385
-
386
-    /**
387
-     * Return the hook corresponding to the default package that
388
-     * provides the functionality requested by the $method
389
-     * parameter. $method is a string consisting of
390
-     * "packagetype/methodname".
391
-     *
392
-     * @access public
393
-     *
394
-     * @param string $method        The method to call.
395
-     * @param optional array $args  Arguments to the method.
396
-     *
397
-     * @return  TODO
398
-     *          Returns PEAR_Error on error.
399
-     */
400
-    function call($method, $args = array())
401
-    {
402
-        @list($interface, $call) = explode('/', $method);
403
-
404
-        if (!empty($this->_interfaces[$method])) {
405
-            $app = $this->_interfaces[$method];
406
-        } elseif (!empty($this->_interfaces[$interface])) {
407
-            $app = $this->_interfaces[$interface];
408
-        } else {
409
-            return PEAR::raiseError('The method "' . $method . '" is not defined in the Horde Registry.');
410
-        }
411
-
412
-        return $this->callByPackage($app, $call, $args);
413
-    }
414
-
415
-    /**
416
-     * Output the hook corresponding to the specific package named.
417
-     *
418
-     * @access public
419
-     *
420
-     * @param string $app           The application being called.
421
-     * @param string $call          The method to call.
422
-     * @param optional array $args  Arguments to the method.
423
-     *
424
-     * @return  TODO
425
-     *          Returns PEAR_Error on error.
426
-     */
427
-    function callByPackage($app, $call, $args = array())
428
-    {
429
-        /* Note: calling hasMethod() makes sure that we've cached
193
+		/* Register access key logger for translators. */
194
+		if (@$GLOBALS['conf']['log_accesskeys']) {
195
+			register_shutdown_function(create_function('', 'Horde::getAccessKey(null, null, true);'));
196
+		}
197
+	}
198
+
199
+	/**
200
+	 * Return a list of the installed and registered applications.
201
+	 *
202
+	 * @since Horde 2.2
203
+	 *
204
+	 * @access public
205
+	 *
206
+	 * @param array   $filter      (optional) An array of the statuses that
207
+	 *                             should be returned. Defaults to non-hidden.
208
+	 * @param boolean $assoc       (optional) Associative array with app names
209
+	 *                             as keys.
210
+	 * @param integer $permission  (optional) The permission level to check
211
+	 *                             for in the list. Defaults to PERMS_SHOW.
212
+	 *
213
+	 * @return array  List of apps registered with Horde. If no
214
+	 *                applications are defined returns an empty array.
215
+	 */
216
+	function listApps($filter = null, $assoc = false, $permission = PERMS_SHOW)
217
+	{
218
+		$apps = array();
219
+		if (is_null($filter)) {
220
+			$filter = array('notoolbar', 'active');
221
+		}
222
+
223
+		foreach ($this->applications as $app => $params) {
224
+			if (in_array($params['status'], $filter) &&
225
+				(defined('AUTH_HANDLER') || $this->hasPermission($app, $permission))) {
226
+				$assoc ? $apps[$app] = $app : $apps[] = $app;
227
+			}
228
+		}
229
+
230
+		return $apps;
231
+	}
232
+
233
+	/**
234
+	 * Returns all available registry APIs.
235
+	 *
236
+	 * @access public
237
+	 *
238
+	 * @return array  The API list.
239
+	 */
240
+	function listAPIs()
241
+	{
242
+		$apis = array();
243
+
244
+		foreach (array_keys($this->_interfaces) as $interface) {
245
+			@list($api, ) = explode('/', $interface);
246
+			$apis[] = $api;
247
+		}
248
+
249
+		return array_unique($apis);
250
+	}
251
+
252
+	/**
253
+	 * Returns all of the available registry methods, or alternately
254
+	 * only those for a specified API.
255
+	 *
256
+	 * @access public
257
+	 *
258
+	 * @param optional string $api  Defines the API for which the methods
259
+	 *                              shall be returned.
260
+	 *
261
+	 * @return array  The method list.
262
+	 */
263
+	function listMethods($api = null)
264
+	{
265
+		$methods = array();
266
+
267
+		$this->_fillAPICache();
268
+
269
+		foreach (array_keys($this->applications) as $app) {
270
+			if (isset($this->applications[$app]['provides'])) {
271
+				$provides = $this->applications[$app]['provides'];
272
+				if (!is_array($provides)) {
273
+					$provides = array($provides);
274
+				}
275
+			} else {
276
+				$provides = array();
277
+			}
278
+
279
+			foreach ($provides as $method) {
280
+				if (strpos($method, '/') !== false) {
281
+					if (is_null($api) ||
282
+						(substr($method, 0, strlen($api)) == $api)) {
283
+						$methods[] = $method;
284
+					}
285
+				} elseif (is_null($api) || ($method == $api)) {
286
+					if (isset($this->_apiCache[$app])) {
287
+						foreach (array_keys($this->_apiCache[$app]) as $service) {
288
+							$methods[] = $method . '/' . $service;
289
+						}
290
+					}
291
+				}
292
+			}
293
+		}
294
+
295
+		return array_unique($methods);
296
+	}
297
+
298
+	/**
299
+	 * Returns all of the available registry data types.
300
+	 *
301
+	 * @access public
302
+	 *
303
+	 * @return array  The data type list.
304
+	 */
305
+	function listTypes()
306
+	{
307
+		$this->_fillAPICache();
308
+		return $this->_typeCache;
309
+	}
310
+
311
+	/**
312
+	 * Returns a method's signature.
313
+	 *
314
+	 * @access public
315
+	 *
316
+	 * @param string $method  The full name of the method to check for.
317
+	 *
318
+	 * @return array  A two dimensional array. The first element contains an
319
+	 *                array with the parameter names, the second one the return
320
+	 *                type.
321
+	 */
322
+	function getSignature($method)
323
+	{
324
+		if (!($app = $this->hasMethod($method))) {
325
+			return;
326
+		}
327
+
328
+		$this->_fillAPICache();
329
+
330
+		@list(, $function) = explode('/', $method);
331
+		if (isset($this->_apiCache[$app][$function]['type']) &&
332
+			isset($this->_apiCache[$app][$function]['args'])) {
333
+			return array($this->_apiCache[$app][$function]['args'], $this->_apiCache[$app][$function]['type']);
334
+		}
335
+	}
336
+
337
+	/**
338
+	 * Determine if an interface is implemented by an active
339
+	 * application.
340
+	 *
341
+	 * @access public
342
+	 *
343
+	 * @param string $interface  The interface to check for.
344
+	 *
345
+	 * @return mixed  The application implementing $interface if we have it,
346
+	 *                false if the interface is not implemented.
347
+	 */
348
+	function hasInterface($interface)
349
+	{
350
+		return !empty($this->_interfaces[$interface]) ?
351
+			$this->_interfaces[$interface] :
352
+			false;
353
+	}
354
+
355
+	/**
356
+	 * Determine if a method has been registered with the registry.
357
+	 *
358
+	 * @access public
359
+	 *
360
+	 * @param string  $method      The full name of the method to check for.
361
+	 * @param string  $app         (optional) Only check this application.
362
+	 *
363
+	 * @return mixed  The application implementing $method if we have it,
364
+	 *                false if the method doesn't exist.
365
+	 */
366
+	function hasMethod($method, $app = null)
367
+	{
368
+		if (is_null($app)) {
369
+			@list($interface, $call) = explode('/', $method);
370
+			if (!empty($this->_interfaces[$method])) {
371
+				$app = $this->_interfaces[$method];
372
+			} elseif (!empty($this->_interfaces[$interface])) {
373
+				$app = $this->_interfaces[$interface];
374
+			} else {
375
+				return false;
376
+			}
377
+		} else {
378
+			$call = $method;
379
+		}
380
+
381
+		$this->_fillAPICache();
382
+
383
+		return !empty($this->_apiCache[$app][$call]) ? $app : false;
384
+	}
385
+
386
+	/**
387
+	 * Return the hook corresponding to the default package that
388
+	 * provides the functionality requested by the $method
389
+	 * parameter. $method is a string consisting of
390
+	 * "packagetype/methodname".
391
+	 *
392
+	 * @access public
393
+	 *
394
+	 * @param string $method        The method to call.
395
+	 * @param optional array $args  Arguments to the method.
396
+	 *
397
+	 * @return  TODO
398
+	 *          Returns PEAR_Error on error.
399
+	 */
400
+	function call($method, $args = array())
401
+	{
402
+		@list($interface, $call) = explode('/', $method);
403
+
404
+		if (!empty($this->_interfaces[$method])) {
405
+			$app = $this->_interfaces[$method];
406
+		} elseif (!empty($this->_interfaces[$interface])) {
407
+			$app = $this->_interfaces[$interface];
408
+		} else {
409
+			return PEAR::raiseError('The method "' . $method . '" is not defined in the Horde Registry.');
410
+		}
411
+
412
+		return $this->callByPackage($app, $call, $args);
413
+	}
414
+
415
+	/**
416
+	 * Output the hook corresponding to the specific package named.
417
+	 *
418
+	 * @access public
419
+	 *
420
+	 * @param string $app           The application being called.
421
+	 * @param string $call          The method to call.
422
+	 * @param optional array $args  Arguments to the method.
423
+	 *
424
+	 * @return  TODO
425
+	 *          Returns PEAR_Error on error.
426
+	 */
427
+	function callByPackage($app, $call, $args = array())
428
+	{
429
+		/* Note: calling hasMethod() makes sure that we've cached
430 430
          * $app's services and included the API file, so we don't try
431 431
          * to do it again explicitly in this method. */
432
-        if (!$this->hasMethod($call, $app)) {
433
-            return PEAR::raiseError(sprintf('The method "%s" is not defined in the API for %s.', $call, $app));
434
-        }
432
+		if (!$this->hasMethod($call, $app)) {
433
+			return PEAR::raiseError(sprintf('The method "%s" is not defined in the API for %s.', $call, $app));
434
+		}
435 435
 
436
-        /* Make sure that the function actually exists. */
437
-        $function = '_' . $app . '_' . $call;
438
-        if (!function_exists($function)) {
439
-            return PEAR::raiseError('The function implementing ' . $call . ' (' . $function . ') is not defined in ' . $app . '\'s API.');
440
-        }
436
+		/* Make sure that the function actually exists. */
437
+		$function = '_' . $app . '_' . $call;
438
+		if (!function_exists($function)) {
439
+			return PEAR::raiseError('The function implementing ' . $call . ' (' . $function . ') is not defined in ' . $app . '\'s API.');
440
+		}
441 441
 
442
-        $checkPerms = isset($this->_apiCache[$app][$call]['checkperms']) ?
443
-                      $this->_apiCache[$app][$call]['checkperms'] : true;
442
+		$checkPerms = isset($this->_apiCache[$app][$call]['checkperms']) ?
443
+					  $this->_apiCache[$app][$call]['checkperms'] : true;
444 444
 
445
-        /* Switch application contexts now, if necessary, before
445
+		/* Switch application contexts now, if necessary, before
446 446
          * including any files which might do it for us. Return an
447 447
          * error immediately if pushApp() fails. */
448
-        $pushed = $this->pushApp($app, $checkPerms);
449
-        if (is_a($pushed, 'PEAR_Error')) {
450
-            return $pushed;
451
-        }
448
+		$pushed = $this->pushApp($app, $checkPerms);
449
+		if (is_a($pushed, 'PEAR_Error')) {
450
+			return $pushed;
451
+		}
452 452
 
453
-        $res = call_user_func_array($function, $args);
453
+		$res = call_user_func_array($function, $args);
454 454
 
455
-        /* If we changed application context in the course of this
455
+		/* If we changed application context in the course of this
456 456
          * call, undo that change now. */
457
-        if ($pushed === true) {
458
-            $this->popApp();
459
-        }
460
-
461
-        return $res;
462
-    }
463
-
464
-    /**
465
-     * Return the hook corresponding to the default package that
466
-     * provides the functionality requested by the $method
467
-     * parameter. $method is a string consisting of
468
-     * "packagetype/methodname".
469
-     *
470
-     * @access public
471
-     *
472
-     * @param string $method         The method to link to.
473
-     * @param optional array $args   Arguments to the method.
474
-     * @param optional mixed $extra  Extra, non-standard arguments to the
475
-     *                               method.
476
-     *
477
-     * @return  TODO
478
-     *          Returns PEAR_Error on error.
479
-     */
480
-    function link($method, $args = array(), $extra = '')
481
-    {
482
-        @list($interface, $call) = explode('/', $method);
483
-
484
-        if (!empty($this->_interfaces[$method])) {
485
-            $app = $this->_interfaces[$method];
486
-        } elseif (!empty($this->_interfaces[$interface])) {
487
-            $app = $this->_interfaces[$interface];
488
-        } else {
489
-            return PEAR::raiseError('The method "' . $method . '" is not defined in the Horde Registry.');
490
-        }
491
-
492
-        return $this->linkByPackage($app, $call, $args, $extra);
493
-    }
494
-
495
-    /**
496
-     * Output the hook corresponding to the specific package named.
497
-     *
498
-     * @access public
499
-     *
500
-     * @param string $app            The application being called.
501
-     * @param string $call           The method to link to.
502
-     * @param optional array $args   Arguments to the method.
503
-     * @param optional mixed $extra  Extra, non-standard arguments to the
504
-     *                               method.
505
-     *
506
-     * @return  TODO
507
-     *          Returns PEAR_Error on error.
508
-     */
509
-    function linkByPackage($app, $call, $args = array(), $extra = '')
510
-    {
511
-        /* Note: calling hasMethod makes sure that we've cached $app's
457
+		if ($pushed === true) {
458
+			$this->popApp();
459
+		}
460
+
461
+		return $res;
462
+	}
463
+
464
+	/**
465
+	 * Return the hook corresponding to the default package that
466
+	 * provides the functionality requested by the $method
467
+	 * parameter. $method is a string consisting of
468
+	 * "packagetype/methodname".
469
+	 *
470
+	 * @access public
471
+	 *
472
+	 * @param string $method         The method to link to.
473
+	 * @param optional array $args   Arguments to the method.
474
+	 * @param optional mixed $extra  Extra, non-standard arguments to the
475
+	 *                               method.
476
+	 *
477
+	 * @return  TODO
478
+	 *          Returns PEAR_Error on error.
479
+	 */
480
+	function link($method, $args = array(), $extra = '')
481
+	{
482
+		@list($interface, $call) = explode('/', $method);
483
+
484
+		if (!empty($this->_interfaces[$method])) {
485
+			$app = $this->_interfaces[$method];
486
+		} elseif (!empty($this->_interfaces[$interface])) {
487
+			$app = $this->_interfaces[$interface];
488
+		} else {
489
+			return PEAR::raiseError('The method "' . $method . '" is not defined in the Horde Registry.');
490
+		}
491
+
492
+		return $this->linkByPackage($app, $call, $args, $extra);
493
+	}
494
+
495
+	/**
496
+	 * Output the hook corresponding to the specific package named.
497
+	 *
498
+	 * @access public
499
+	 *
500
+	 * @param string $app            The application being called.
501
+	 * @param string $call           The method to link to.
502
+	 * @param optional array $args   Arguments to the method.
503
+	 * @param optional mixed $extra  Extra, non-standard arguments to the
504
+	 *                               method.
505
+	 *
506
+	 * @return  TODO
507
+	 *          Returns PEAR_Error on error.
508
+	 */
509
+	function linkByPackage($app, $call, $args = array(), $extra = '')
510
+	{
511
+		/* Note: calling hasMethod makes sure that we've cached $app's
512 512
          * services and included the API file, so we don't try to do
513 513
          * it it again explicitly in this method. */
514
-        if (!$this->hasMethod($call, $app)) {
515
-            return PEAR::raiseError('The method "' . $call . '" is not defined in ' . $app . '\'s API.');
516
-        }
517
-
518
-        /* Make sure the link is defined. */
519
-        if (empty($this->_apiCache[$app][$call]['link'])) {
520
-            return PEAR::raiseError('The link ' . $call . ' is not defined in ' . $app . '\'s API.');
521
-        }
522
-
523
-        /* Initial link value. */
524
-        $link = $this->_apiCache[$app][$call]['link'];
525
-
526
-        /* Fill in html-encoded arguments. */
527
-        foreach ($args as $key => $val) {
528
-            $link = str_replace('%' . $key . '%', htmlentities($val), $link);
529
-        }
530
-        if (isset($this->applications[$app]['webroot'])) {
531
-            $link = str_replace('%application%', $this->get('webroot', $app), $link);
532
-        }
533
-
534
-        /* Replace htmlencoded arguments that haven't been specified with
514
+		if (!$this->hasMethod($call, $app)) {
515
+			return PEAR::raiseError('The method "' . $call . '" is not defined in ' . $app . '\'s API.');
516
+		}
517
+
518
+		/* Make sure the link is defined. */
519
+		if (empty($this->_apiCache[$app][$call]['link'])) {
520
+			return PEAR::raiseError('The link ' . $call . ' is not defined in ' . $app . '\'s API.');
521
+		}
522
+
523
+		/* Initial link value. */
524
+		$link = $this->_apiCache[$app][$call]['link'];
525
+
526
+		/* Fill in html-encoded arguments. */
527
+		foreach ($args as $key => $val) {
528
+			$link = str_replace('%' . $key . '%', htmlentities($val), $link);
529
+		}
530
+		if (isset($this->applications[$app]['webroot'])) {
531
+			$link = str_replace('%application%', $this->get('webroot', $app), $link);
532
+		}
533
+
534
+		/* Replace htmlencoded arguments that haven't been specified with
535 535
            an empty string (this is where the default would be substituted
536 536
            in a stricter registry implementation). */
537
-        $link = preg_replace('|%.+%|U', '', $link);
538
-
539
-        /* Fill in urlencoded arguments. */
540
-        foreach ($args as $key => $val) {
541
-            $link = str_replace('|' . String::lower($key) . '|', urlencode($val), $link);
542
-        }
543
-
544
-        /* Append any extra, non-standard arguments. */
545
-        if (is_array($extra)) {
546
-            $extra_args = '';
547
-            foreach ($extra as $key => $val) {
548
-                $extra_args .- '&' . urlencode($key) . '=' . urlencode($val);
549
-            }
550
-        } else {
551
-            $extra_args = $extra;
552
-        }
553
-        $link = str_replace('|extra|', $extra_args, $link);
554
-
555
-        /* Replace html-encoded arguments that haven't been specified with
537
+		$link = preg_replace('|%.+%|U', '', $link);
538
+
539
+		/* Fill in urlencoded arguments. */
540
+		foreach ($args as $key => $val) {
541
+			$link = str_replace('|' . String::lower($key) . '|', urlencode($val), $link);
542
+		}
543
+
544
+		/* Append any extra, non-standard arguments. */
545
+		if (is_array($extra)) {
546
+			$extra_args = '';
547
+			foreach ($extra as $key => $val) {
548
+				$extra_args .- '&' . urlencode($key) . '=' . urlencode($val);
549
+			}
550
+		} else {
551
+			$extra_args = $extra;
552
+		}
553
+		$link = str_replace('|extra|', $extra_args, $link);
554
+
555
+		/* Replace html-encoded arguments that haven't been specified with
556 556
            an empty string (this is where the default would be substituted
557 557
            in a stricter registry implementation). */
558
-        $link = preg_replace('|\|.+\||U', '', $link);
559
-
560
-        return $link;
561
-    }
562
-
563
-    /**
564
-     * Replace any %application% strings with the filesystem path to
565
-     * the application.
566
-     *
567
-     * @access public
568
-     *
569
-     * @param string $path          The application string.
570
-     * @param optional string $app  The application being called.
571
-     *
572
-     * @return  TODO
573
-     *          Returns PEAR_Error on error.
574
-     */
575
-    function applicationFilePath($path, $app = null)
576
-    {
577
-        if (is_null($app)) {
578
-            $app = $this->_currentApp;
579
-        }
580
-
581
-        if (!isset($this->applications[$app])) {
582
-            return PEAR::raiseError(sprintf(_("'%s' is not configured in the Horde Registry."), $app));
583
-        }
584
-
585
-        return str_replace('%application%', $this->applications[$app]['fileroot'], $path);
586
-    }
587
-
588
-    /**
589
-     * Replace any %application% strings with the web path to the
590
-     * application.
591
-     *
592
-     * @access public
593
-     *
594
-     * @param string $path          The application string.
595
-     * @param optional string $app  The application being called.
596
-     *
597
-     * @return  TODO
598
-     *          Returns PEAR_Error on error.
599
-     */
600
-    function applicationWebPath($path, $app = null)
601
-    {
602
-        if (!isset($app)) {
603
-            $app = $this->_currentApp;
604
-        }
605
-
606
-        return str_replace('%application%', $this->applications[$app]['webroot'], $path);
607
-    }
608
-
609
-    /**
610
-     * Set the current application, adding it to the top of the Horde
611
-     * application stack. If this is the first application to be
612
-     * pushed, retrieve session information as well.
613
-     *
614
-     * pushApp() also reads the application's configuration file and
615
-     * sets up its global $conf hash.
616
-     *
617
-     * @access public
618
-     *
619
-     * @param string  $app         The name of the application to push.
620
-     * @param boolean $checkPerms  (optional) Make sure that the current user
621
-     *                             has permissions to the application being
622
-     *                             loaded. Defaults to true. Should ONLY
623
-     *                             be disabled by system scripts (cron jobs,
624
-     *                             etc.) and scripts that handle login.
625
-     *
626
-     * @return boolean  Whether or not the _appStack was modified.
627
-     *                  Return PEAR_Error on error.
628
-     */
629
-    function pushApp($app, $checkPerms = true)
630
-    {
631
-        if ($app == $this->_currentApp) {
632
-            return false;
633
-        }
634
-
635
-        /* Bail out if application is not present or inactive. */
636
-        if (!isset($this->applications[$app]) ||
637
-            $this->applications[$app]['status'] == 'inactive' ||
638
-            ($this->applications[$app]['status'] == 'admin' && !Auth::isAdmin())) {
639
-            Horde::fatal($app . ' is not activated', __FILE__, __LINE__);
640
-        }
641
-
642
-        /* If permissions checking is requested, return an error if
558
+		$link = preg_replace('|\|.+\||U', '', $link);
559
+
560
+		return $link;
561
+	}
562
+
563
+	/**
564
+	 * Replace any %application% strings with the filesystem path to
565
+	 * the application.
566
+	 *
567
+	 * @access public
568
+	 *
569
+	 * @param string $path          The application string.
570
+	 * @param optional string $app  The application being called.
571
+	 *
572
+	 * @return  TODO
573
+	 *          Returns PEAR_Error on error.
574
+	 */
575
+	function applicationFilePath($path, $app = null)
576
+	{
577
+		if (is_null($app)) {
578
+			$app = $this->_currentApp;
579
+		}
580
+
581
+		if (!isset($this->applications[$app])) {
582
+			return PEAR::raiseError(sprintf(_("'%s' is not configured in the Horde Registry."), $app));
583
+		}
584
+
585
+		return str_replace('%application%', $this->applications[$app]['fileroot'], $path);
586
+	}
587
+
588
+	/**
589
+	 * Replace any %application% strings with the web path to the
590
+	 * application.
591
+	 *
592
+	 * @access public
593
+	 *
594
+	 * @param string $path          The application string.
595
+	 * @param optional string $app  The application being called.
596
+	 *
597
+	 * @return  TODO
598
+	 *          Returns PEAR_Error on error.
599
+	 */
600
+	function applicationWebPath($path, $app = null)
601
+	{
602
+		if (!isset($app)) {
603
+			$app = $this->_currentApp;
604
+		}
605
+
606
+		return str_replace('%application%', $this->applications[$app]['webroot'], $path);
607
+	}
608
+
609
+	/**
610
+	 * Set the current application, adding it to the top of the Horde
611
+	 * application stack. If this is the first application to be
612
+	 * pushed, retrieve session information as well.
613
+	 *
614
+	 * pushApp() also reads the application's configuration file and
615
+	 * sets up its global $conf hash.
616
+	 *
617
+	 * @access public
618
+	 *
619
+	 * @param string  $app         The name of the application to push.
620
+	 * @param boolean $checkPerms  (optional) Make sure that the current user
621
+	 *                             has permissions to the application being
622
+	 *                             loaded. Defaults to true. Should ONLY
623
+	 *                             be disabled by system scripts (cron jobs,
624
+	 *                             etc.) and scripts that handle login.
625
+	 *
626
+	 * @return boolean  Whether or not the _appStack was modified.
627
+	 *                  Return PEAR_Error on error.
628
+	 */
629
+	function pushApp($app, $checkPerms = true)
630
+	{
631
+		if ($app == $this->_currentApp) {
632
+			return false;
633
+		}
634
+
635
+		/* Bail out if application is not present or inactive. */
636
+		if (!isset($this->applications[$app]) ||
637
+			$this->applications[$app]['status'] == 'inactive' ||
638
+			($this->applications[$app]['status'] == 'admin' && !Auth::isAdmin())) {
639
+			Horde::fatal($app . ' is not activated', __FILE__, __LINE__);
640
+		}
641
+
642
+		/* If permissions checking is requested, return an error if
643 643
          * the current user does not have read perms to the
644 644
          * application being loaded. We allow access:
645 645
          *
646 646
          *  - To all admins.
647 647
          *  - To all authenticated users if no permission is set on $app.
648 648
          *  - To anyone who is allowed by an explicit ACL on $app. */
649
-        if ($checkPerms && !$this->hasPermission($app)) {
650
-            Horde::logMessage(sprintf('User %s does not have READ permission for %s', Auth::getAuth(), $app), __FILE__, __LINE__, PEAR_LOG_DEBUG);
651
-            return PEAR::raiseError(sprintf(_("User %s is not authorised for %s."), Auth::getAuth(), $this->applications[$app]['name']), 'permission_denied');
652
-        }
653
-
654
-        /* Import this application's configuration values. */
655
-        $success = $this->importConfig($app);
656
-        if (is_a($success, 'PEAR_Error')) {
657
-            return $success;
658
-        }
659
-
660
-        /* Load preferences after the configuration has been loaded to
649
+		if ($checkPerms && !$this->hasPermission($app)) {
650
+			Horde::logMessage(sprintf('User %s does not have READ permission for %s', Auth::getAuth(), $app), __FILE__, __LINE__, PEAR_LOG_DEBUG);
651
+			return PEAR::raiseError(sprintf(_("User %s is not authorised for %s."), Auth::getAuth(), $this->applications[$app]['name']), 'permission_denied');
652
+		}
653
+
654
+		/* Import this application's configuration values. */
655
+		$success = $this->importConfig($app);
656
+		if (is_a($success, 'PEAR_Error')) {
657
+			return $success;
658
+		}
659
+
660
+		/* Load preferences after the configuration has been loaded to
661 661
          * make sure the prefs file has all the information it needs. */
662
-        $this->loadPrefs($app);
662
+		$this->loadPrefs($app);
663 663
 
664
-        /* Reset the language in case there is a different one
664
+		/* Reset the language in case there is a different one
665 665
          * selected in the preferences. */
666
-        $language = '';
667
-        if (isset($this->_prefsCache[$app]) &&
668
-            isset($this->_prefsCache[$app]->_prefs['language'])) {
669
-            $language = $this->_prefsCache[$app]->getValue('language');
670
-        }
671
-        NLS::setLang($language);
672
-        NLS::setTextdomain($app, $this->applications[$app]['fileroot'] . '/locale', NLS::getCharset());
673
-        String::setDefaultCharset(NLS::getCharset());
674
-
675
-        /* Once we know everything succeeded and is in a consistent
666
+		$language = '';
667
+		if (isset($this->_prefsCache[$app]) &&
668
+			isset($this->_prefsCache[$app]->_prefs['language'])) {
669
+			$language = $this->_prefsCache[$app]->getValue('language');
670
+		}
671
+		NLS::setLang($language);
672
+		NLS::setTextdomain($app, $this->applications[$app]['fileroot'] . '/locale', NLS::getCharset());
673
+		String::setDefaultCharset(NLS::getCharset());
674
+
675
+		/* Once we know everything succeeded and is in a consistent
676 676
          * state again, push the new application onto the stack. */
677
-        array_push($this->_appStack, $app);
678
-        $this->_currentApp = $app;
679
-
680
-        return true;
681
-    }
682
-
683
-    /**
684
-     * Remove the current app from the application stack, setting the
685
-     * current app to whichever app was current before this one took
686
-     * over.
687
-     *
688
-     * @access public
689
-     *
690
-     * @return string  The name of the application that was popped.
691
-     */
692
-    function popApp()
693
-    {
694
-        /* Pop the current application off of the stack. */
695
-        $previous = array_pop($this->_appStack);
696
-
697
-        /* Import the new active application's configuration values
677
+		array_push($this->_appStack, $app);
678
+		$this->_currentApp = $app;
679
+
680
+		return true;
681
+	}
682
+
683
+	/**
684
+	 * Remove the current app from the application stack, setting the
685
+	 * current app to whichever app was current before this one took
686
+	 * over.
687
+	 *
688
+	 * @access public
689
+	 *
690
+	 * @return string  The name of the application that was popped.
691
+	 */
692
+	function popApp()
693
+	{
694
+		/* Pop the current application off of the stack. */
695
+		$previous = array_pop($this->_appStack);
696
+
697
+		/* Import the new active application's configuration values
698 698
          * and set the gettext domain and the preferred language. */
699
-        $this->_currentApp = count($this->_appStack) ? end($this->_appStack) : null;
700
-        if ($this->_currentApp) {
701
-            $this->importConfig($this->_currentApp);
702
-            $this->loadPrefs($this->_currentApp);
703
-            #$language = $GLOBALS['prefs']->getValue('language');
704
-            #if (isset($language)) {
705
-            #    NLS::setLang($language);
706
-            #}
707
-            NLS::setTextdomain($this->_currentApp, $this->applications[$this->_currentApp]['fileroot'] . '/locale', NLS::getCharset());
708
-            String::setDefaultCharset(NLS::getCharset());
709
-        }
710
-
711
-        return $previous;
712
-    }
713
-
714
-    /**
715
-     * Return the current application - the app at the top of the
716
-     * application stack.
717
-     *
718
-     * @access public
719
-     *
720
-     * @return string  The current application.
721
-     */
722
-    function getApp()
723
-    {
724
-        return $this->_currentApp;
725
-    }
726
-
727
-    /**
728
-     * Check permissions on an application.
729
-     *
730
-     * @access public
731
-     *
732
-     * @return boolean  Whether or not access is allowed.
733
-     */
734
-    function hasPermission($app, $permission = PERMS_READ)
735
-    {
736
-    	return true;
737
-        #return Auth::isAdmin() || ($GLOBALS['perms']->exists($app) ?
738
-        #                           $GLOBALS['perms']->hasPermission($app, Auth::getAuth(), $permission) :
739
-        #                           (bool)Auth::getAuth());
740
-    }
741
-
742
-    /**
743
-     * Reads the configuration values for the given application and
744
-     * imports them into the global $conf variable.
745
-     *
746
-     * @access public
747
-     *
748
-     * @param string $app  The name of the application.
749
-     *
750
-     * @return boolean  True on success, PEAR_Error on error.
751
-     */
752
-    function importConfig($app)
753
-    {
754
-        /* Don't make config files global $registry themselves. */
755
-        global $registry;
756
-
757
-        /* Cache config values so that we don't re-read files on every
699
+		$this->_currentApp = count($this->_appStack) ? end($this->_appStack) : null;
700
+		if ($this->_currentApp) {
701
+			$this->importConfig($this->_currentApp);
702
+			$this->loadPrefs($this->_currentApp);
703
+			#$language = $GLOBALS['prefs']->getValue('language');
704
+			#if (isset($language)) {
705
+			#    NLS::setLang($language);
706
+			#}
707
+			NLS::setTextdomain($this->_currentApp, $this->applications[$this->_currentApp]['fileroot'] . '/locale', NLS::getCharset());
708
+			String::setDefaultCharset(NLS::getCharset());
709
+		}
710
+
711
+		return $previous;
712
+	}
713
+
714
+	/**
715
+	 * Return the current application - the app at the top of the
716
+	 * application stack.
717
+	 *
718
+	 * @access public
719
+	 *
720
+	 * @return string  The current application.
721
+	 */
722
+	function getApp()
723
+	{
724
+		return $this->_currentApp;
725
+	}
726
+
727
+	/**
728
+	 * Check permissions on an application.
729
+	 *
730
+	 * @access public
731
+	 *
732
+	 * @return boolean  Whether or not access is allowed.
733
+	 */
734
+	function hasPermission($app, $permission = PERMS_READ)
735
+	{
736
+		return true;
737
+		#return Auth::isAdmin() || ($GLOBALS['perms']->exists($app) ?
738
+		#                           $GLOBALS['perms']->hasPermission($app, Auth::getAuth(), $permission) :
739
+		#                           (bool)Auth::getAuth());
740
+	}
741
+
742
+	/**
743
+	 * Reads the configuration values for the given application and
744
+	 * imports them into the global $conf variable.
745
+	 *
746
+	 * @access public
747
+	 *
748
+	 * @param string $app  The name of the application.
749
+	 *
750
+	 * @return boolean  True on success, PEAR_Error on error.
751
+	 */
752
+	function importConfig($app)
753
+	{
754
+		/* Don't make config files global $registry themselves. */
755
+		global $registry;
756
+
757
+		/* Cache config values so that we don't re-read files on every
758 758
          * popApp() call. */
759
-        if (!isset($this->_confCache[$app])) {
760
-            if (!isset($this->_confCache['horde'])) {
761
-                $conf = array();
762
-                ob_start();
763
-                $success = include HORDE_BASE . '/config/conf.php';
764
-                $errors = ob_get_contents();
765
-                ob_end_clean();
766
-                if (!empty($errors)) {
767
-                    return PEAR::raiseError(sprintf('Failed to import Horde configuration: %s', strip_tags($errors)));
768
-                }
769
-                if (!$success) {
770
-                    return PEAR::raiseError('Failed to import Horde configuration.');
771
-                }
772
-
773
-                /* Initial Horde-wide settings. */
774
-
775
-                /* Set the error reporting level in accordance with
759
+		if (!isset($this->_confCache[$app])) {
760
+			if (!isset($this->_confCache['horde'])) {
761
+				$conf = array();
762
+				ob_start();
763
+				$success = include HORDE_BASE . '/config/conf.php';
764
+				$errors = ob_get_contents();
765
+				ob_end_clean();
766
+				if (!empty($errors)) {
767
+					return PEAR::raiseError(sprintf('Failed to import Horde configuration: %s', strip_tags($errors)));
768
+				}
769
+				if (!$success) {
770
+					return PEAR::raiseError('Failed to import Horde configuration.');
771
+				}
772
+
773
+				/* Initial Horde-wide settings. */
774
+
775
+				/* Set the error reporting level in accordance with
776 776
                  * the config settings. */
777
-                error_reporting($conf['debug_level']);
777
+				error_reporting($conf['debug_level']);
778 778
 
779
-                /* Set the maximum execution time in accordance with
779
+				/* Set the maximum execution time in accordance with
780 780
                  * the config settings. */
781
-                @set_time_limit($conf['max_exec_time']);
782
-
783
-                /* Set the umask according to config settings. */
784
-                if (isset($conf['umask'])) {
785
-                    umask($conf['umask']);
786
-                }
787
-            } else {
788
-                $conf = $this->_confCache['horde'];
789
-            }
790
-
791
-            if ($app !== 'horde') {
792
-                $success = @include $this->applications[$app]['fileroot'] . '/config/conf.php';
793
-                if (!$success) {
794
-                    return PEAR::raiseError('Failed to import application configuration for ' . $app);
795
-                }
796
-            }
797
-
798
-            $this->_confCache[$app] = &$conf;
799
-        }
800
-
801
-        $GLOBALS['conf'] = &$this->_confCache[$app];
802
-        return true;
803
-    }
804
-
805
-    /**
806
-     * Loads the preferences for the current user for the current
807
-     * application and imports them into the global $prefs variable.
808
-     *
809
-     * @access public
810
-     *
811
-     * @param string $app  The name of the application.
812
-     */
813
-    function loadPrefs($app = null)
814
-    {
815
-    	return array();
781
+				@set_time_limit($conf['max_exec_time']);
782
+
783
+				/* Set the umask according to config settings. */
784
+				if (isset($conf['umask'])) {
785
+					umask($conf['umask']);
786
+				}
787
+			} else {
788
+				$conf = $this->_confCache['horde'];
789
+			}
790
+
791
+			if ($app !== 'horde') {
792
+				$success = @include $this->applications[$app]['fileroot'] . '/config/conf.php';
793
+				if (!$success) {
794
+					return PEAR::raiseError('Failed to import application configuration for ' . $app);
795
+				}
796
+			}
797
+
798
+			$this->_confCache[$app] = &$conf;
799
+		}
800
+
801
+		$GLOBALS['conf'] = &$this->_confCache[$app];
802
+		return true;
803
+	}
804
+
805
+	/**
806
+	 * Loads the preferences for the current user for the current
807
+	 * application and imports them into the global $prefs variable.
808
+	 *
809
+	 * @access public
810
+	 *
811
+	 * @param string $app  The name of the application.
812
+	 */
813
+	function loadPrefs($app = null)
814
+	{
815
+		return array();
816 816
     	
817
-        static $prefs_default = false;
817
+		static $prefs_default = false;
818 818
 
819
-        require_once 'Horde/Prefs.php';
819
+		require_once 'Horde/Prefs.php';
820 820
 
821
-        if ($app === null) {
822
-            $app = $this->_currentApp;
823
-        }
821
+		if ($app === null) {
822
+			$app = $this->_currentApp;
823
+		}
824 824
 
825
-        /* If there is no logged in user, return an empty Prefs::
825
+		/* If there is no logged in user, return an empty Prefs::
826 826
          * object with just default preferences. */
827 827
 #        if (!Auth::getAuth()) {
828 828
 #            $prefs = &Prefs::factory('none', $app, '', '', null, false);
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
 #            return;
834 834
 #        }
835 835
 
836
-        /* Cache prefs objects so that we don't re-load them on every
836
+		/* Cache prefs objects so that we don't re-load them on every
837 837
          * popApp() call. */
838 838
 #        if (!isset($this->_prefsCache[$app]) ||
839 839
 #            !empty($prefs_default)) {
@@ -843,186 +843,186 @@  discard block
 block discarded – undo
843 843
 #            $this->_prefsCache[$app] = &$prefs;
844 844
 #       }
845 845
 
846
-        $GLOBALS['prefs'] = &$this->_prefsCache[$app];
847
-    }
848
-
849
-    /**
850
-     * Unload preferences from an application or (if no application is
851
-     * specified) from ALL applications. Useful when a user has logged
852
-     * out but you need to continue on the same page, etc.
853
-     *
854
-     * After unloading, if there is an application on the app stack to
855
-     * load preferences from, then we reload a fresh set.
856
-     *
857
-     * @access public
858
-     *
859
-     * @param string $app  (optional) The application to unload prefrences for.
860
-     *                     If null, ALL preferences are reset.
861
-     */
862
-    function unloadPrefs($app = null)
863
-    {
864
-        if ($app === null) {
865
-            $this->_prefsCache = array();
866
-        } elseif (isset($this->_prefsCache[$app])) {
867
-            unset($this->_prefsCache[$app]);
868
-        } else {
869
-            return;
870
-        }
871
-
872
-        if ($this->_currentApp) {
873
-            $this->loadPrefs();
874
-        }
875
-    }
876
-
877
-    /**
878
-     * Return the requested configuration parameter for the specified
879
-     * application. If no application is specified, the value of
880
-     * $this->_currentApp (the current application) is used. However,
881
-     * if the parameter is not present for that application, the
882
-     * Horde-wide value is used instead. If that is not present, we
883
-     * return null.
884
-     *
885
-     * @access public
886
-     *
887
-     * @param string $parameter     The configuration value to retrieve.
888
-     * @param optional string $app  The application to get the value for.
889
-     *
890
-     * @return string  The requested parameter, or null if it is not set.
891
-     */
892
-    function get($parameter, $app = null)
893
-    {
894
-        if (is_null($app)) {
895
-            $app = $this->_currentApp;
896
-        }
897
-
898
-        if (isset($this->applications[$app][$parameter])) {
899
-            $pval = $this->applications[$app][$parameter];
900
-        } else {
901
-            if ($parameter == 'icon') {
902
-                $pval = $this->_getIcon($app);
903
-            } else {
904
-                $pval = isset($this->applications['horde'][$parameter]) ? $this->applications['horde'][$parameter] : null;
905
-            }
906
-        }
907
-
908
-        if ($parameter == 'name') {
909
-            return _($pval);
910
-        } else {
911
-            return $pval;
912
-        }
913
-    }
914
-
915
-    /**
916
-     * Function to work out an application's graphics URI, taking into
917
-     * account any themes directories that may be set up.
918
-     *
919
-     * @access public
920
-     *
921
-     * @param optional string $app  The application for which to get the
922
-     *                              image directory. If blank will default
923
-     *                              to current application.
924
-     *
925
-     * @return string  The image directory uri path.
926
-     */
927
-    function getImageDir($app = null)
928
-    {
929
-        if (empty($app)) {
930
-            $app = $this->_currentApp;
931
-        }
932
-
933
-        static $img_dir = array();
934
-        if (isset($img_dir[$app])) {
935
-            return $img_dir[$app];
936
-        }
937
-
938
-        /* This is the default location for the graphics. */
939
-        $img_dir[$app] = $this->get('themesuri', $app) . '/graphics';
940
-
941
-        /* Figure out if this is going to be overridden by any theme
846
+		$GLOBALS['prefs'] = &$this->_prefsCache[$app];
847
+	}
848
+
849
+	/**
850
+	 * Unload preferences from an application or (if no application is
851
+	 * specified) from ALL applications. Useful when a user has logged
852
+	 * out but you need to continue on the same page, etc.
853
+	 *
854
+	 * After unloading, if there is an application on the app stack to
855
+	 * load preferences from, then we reload a fresh set.
856
+	 *
857
+	 * @access public
858
+	 *
859
+	 * @param string $app  (optional) The application to unload prefrences for.
860
+	 *                     If null, ALL preferences are reset.
861
+	 */
862
+	function unloadPrefs($app = null)
863
+	{
864
+		if ($app === null) {
865
+			$this->_prefsCache = array();
866
+		} elseif (isset($this->_prefsCache[$app])) {
867
+			unset($this->_prefsCache[$app]);
868
+		} else {
869
+			return;
870
+		}
871
+
872
+		if ($this->_currentApp) {
873
+			$this->loadPrefs();
874
+		}
875
+	}
876
+
877
+	/**
878
+	 * Return the requested configuration parameter for the specified
879
+	 * application. If no application is specified, the value of
880
+	 * $this->_currentApp (the current application) is used. However,
881
+	 * if the parameter is not present for that application, the
882
+	 * Horde-wide value is used instead. If that is not present, we
883
+	 * return null.
884
+	 *
885
+	 * @access public
886
+	 *
887
+	 * @param string $parameter     The configuration value to retrieve.
888
+	 * @param optional string $app  The application to get the value for.
889
+	 *
890
+	 * @return string  The requested parameter, or null if it is not set.
891
+	 */
892
+	function get($parameter, $app = null)
893
+	{
894
+		if (is_null($app)) {
895
+			$app = $this->_currentApp;
896
+		}
897
+
898
+		if (isset($this->applications[$app][$parameter])) {
899
+			$pval = $this->applications[$app][$parameter];
900
+		} else {
901
+			if ($parameter == 'icon') {
902
+				$pval = $this->_getIcon($app);
903
+			} else {
904
+				$pval = isset($this->applications['horde'][$parameter]) ? $this->applications['horde'][$parameter] : null;
905
+			}
906
+		}
907
+
908
+		if ($parameter == 'name') {
909
+			return _($pval);
910
+		} else {
911
+			return $pval;
912
+		}
913
+	}
914
+
915
+	/**
916
+	 * Function to work out an application's graphics URI, taking into
917
+	 * account any themes directories that may be set up.
918
+	 *
919
+	 * @access public
920
+	 *
921
+	 * @param optional string $app  The application for which to get the
922
+	 *                              image directory. If blank will default
923
+	 *                              to current application.
924
+	 *
925
+	 * @return string  The image directory uri path.
926
+	 */
927
+	function getImageDir($app = null)
928
+	{
929
+		if (empty($app)) {
930
+			$app = $this->_currentApp;
931
+		}
932
+
933
+		static $img_dir = array();
934
+		if (isset($img_dir[$app])) {
935
+			return $img_dir[$app];
936
+		}
937
+
938
+		/* This is the default location for the graphics. */
939
+		$img_dir[$app] = $this->get('themesuri', $app) . '/graphics';
940
+
941
+		/* Figure out if this is going to be overridden by any theme
942 942
          * settings. */
943
-        if (isset($GLOBALS['prefs']) && ($theme = $GLOBALS['prefs']->getValue('theme')) &&
944
-            (@include $this->get('themesfs', 'horde') . '/' . $theme . '/info.php') &&
945
-            isset($theme_icons) &&
946
-            in_array($app, $theme_icons)) {
947
-            $img_dir[$app] = $this->get('themesuri', $app) . '/' . $theme . '/graphics';
948
-        }
949
-
950
-        return $img_dir[$app];
951
-    }
952
-
953
-    /**
954
-     * Returns the path to an application's icon, respecting whether the
955
-     * current theme has its own icons.
956
-     *
957
-     * @access private
958
-     *
959
-     * @param string $app  The application for which to get the icon.
960
-     */
961
-    function _getIcon($app)
962
-    {
963
-        return $this->getImageDir($app) . '/' . $app . '.png';
964
-    }
965
-
966
-    /**
967
-     * Query the initial page for an application - the webroot, if
968
-     * there is no initial_page set, and the initial_page, if it is
969
-     * set.
970
-     *
971
-     * @access public
972
-     *
973
-     * @param optional string $app  The name of the application.
974
-     *
975
-     * @return string  URL pointing to the inital page of the application.
976
-     *                 Returns PEAR_Error on error.
977
-     */
978
-    function getInitialPage($app = null)
979
-    {
980
-        if (is_null($app)) {
981
-            $app = $this->_currentApp;
982
-        }
983
-
984
-        if (!isset($this->applications[$app])) {
985
-            return PEAR::raiseError(sprintf(_("'%s' is not configured in the Horde Registry."), $app));
986
-        }
987
-        return $this->applications[$app]['webroot'] . '/' . (isset($this->applications[$app]['initial_page']) ? $this->applications[$app]['initial_page'] : '');
988
-    }
989
-
990
-    /**
991
-     * Fills the registry's API cache with the available services.
992
-     *
993
-     * @access private
994
-     */
995
-    function _fillAPICache()
996
-    {
997
-        if (!empty($this->_apiCache)) {
998
-            return;
999
-        }
1000
-
1001
-        $status = array('active', 'notoolbar', 'hidden');
943
+		if (isset($GLOBALS['prefs']) && ($theme = $GLOBALS['prefs']->getValue('theme')) &&
944
+			(@include $this->get('themesfs', 'horde') . '/' . $theme . '/info.php') &&
945
+			isset($theme_icons) &&
946
+			in_array($app, $theme_icons)) {
947
+			$img_dir[$app] = $this->get('themesuri', $app) . '/' . $theme . '/graphics';
948
+		}
949
+
950
+		return $img_dir[$app];
951
+	}
952
+
953
+	/**
954
+	 * Returns the path to an application's icon, respecting whether the
955
+	 * current theme has its own icons.
956
+	 *
957
+	 * @access private
958
+	 *
959
+	 * @param string $app  The application for which to get the icon.
960
+	 */
961
+	function _getIcon($app)
962
+	{
963
+		return $this->getImageDir($app) . '/' . $app . '.png';
964
+	}
965
+
966
+	/**
967
+	 * Query the initial page for an application - the webroot, if
968
+	 * there is no initial_page set, and the initial_page, if it is
969
+	 * set.
970
+	 *
971
+	 * @access public
972
+	 *
973
+	 * @param optional string $app  The name of the application.
974
+	 *
975
+	 * @return string  URL pointing to the inital page of the application.
976
+	 *                 Returns PEAR_Error on error.
977
+	 */
978
+	function getInitialPage($app = null)
979
+	{
980
+		if (is_null($app)) {
981
+			$app = $this->_currentApp;
982
+		}
983
+
984
+		if (!isset($this->applications[$app])) {
985
+			return PEAR::raiseError(sprintf(_("'%s' is not configured in the Horde Registry."), $app));
986
+		}
987
+		return $this->applications[$app]['webroot'] . '/' . (isset($this->applications[$app]['initial_page']) ? $this->applications[$app]['initial_page'] : '');
988
+	}
989
+
990
+	/**
991
+	 * Fills the registry's API cache with the available services.
992
+	 *
993
+	 * @access private
994
+	 */
995
+	function _fillAPICache()
996
+	{
997
+		if (!empty($this->_apiCache)) {
998
+			return;
999
+		}
1000
+
1001
+		$status = array('active', 'notoolbar', 'hidden');
1002 1002
 #        if (Auth::isAdmin()) {
1003 1003
 #            $status[] = 'admin';
1004 1004
 #        }
1005
-        $apps = $this->listApps($status);
1006
-        foreach ($apps as $app) {
1007
-            $_services = $_types = null;
1008
-            $api = $this->get('fileroot', $app) . '/lib/api.php';
1009
-            if (is_readable($api)) {
1010
-                include_once $api;
1011
-            }
1012
-            if (!isset($_services)) {
1013
-                $this->_apiCache[$app] = array();
1014
-            } else {
1015
-                $this->_apiCache[$app] = $_services;
1016
-            }
1017
-            if (isset($_types)) {
1018
-                foreach ($_types as $type => $params) {
1019
-                    /* Prefix non-Horde types with the application
1005
+		$apps = $this->listApps($status);
1006
+		foreach ($apps as $app) {
1007
+			$_services = $_types = null;
1008
+			$api = $this->get('fileroot', $app) . '/lib/api.php';
1009
+			if (is_readable($api)) {
1010
+				include_once $api;
1011
+			}
1012
+			if (!isset($_services)) {
1013
+				$this->_apiCache[$app] = array();
1014
+			} else {
1015
+				$this->_apiCache[$app] = $_services;
1016
+			}
1017
+			if (isset($_types)) {
1018
+				foreach ($_types as $type => $params) {
1019
+					/* Prefix non-Horde types with the application
1020 1020
                      * name. */
1021
-                    $prefix = $app == 'horde' ? '' : "${app}_";
1022
-                    $this->_typeCache[$prefix . $type] = $params;
1023
-                }
1024
-            }
1025
-        }
1026
-    }
1021
+					$prefix = $app == 'horde' ? '' : "${app}_";
1022
+					$this->_typeCache[$prefix . $type] = $params;
1023
+				}
1024
+			}
1025
+		}
1026
+	}
1027 1027
 
1028 1028
 }
Please login to merge, or discard this patch.
Spacing   +33 added lines, -34 removed lines patch added patch discarded remove patch
@@ -120,14 +120,14 @@  discard block
 block discarded – undo
120 120
         $this->importConfig('horde');
121 121
 
122 122
         /* Start a session. */
123
-        if ($session_flags & HORDE_SESSION_NONE) {
123
+        if ($session_flags&HORDE_SESSION_NONE) {
124 124
             /* Never start a session if the session flags include
125 125
                HORDE_SESSION_NONE. */
126 126
             $_SESSION = array();
127 127
         } else {
128 128
             Horde::setupSessionHandler();
129 129
             @session_start();
130
-            if ($session_flags & HORDE_SESSION_READONLY) {
130
+            if ($session_flags&HORDE_SESSION_READONLY) {
131 131
                 /* Close the session immediately so no changes can be
132 132
                    made but values are still available. */
133 133
                 @session_write_close();
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
         }
136 136
 
137 137
         /* Read the registry configuration file. */
138
-        require_once HORDE_BASE . '/config/registry.php';
138
+        require_once HORDE_BASE.'/config/registry.php';
139 139
 
140 140
         /* Initialize the localization routines and variables. */
141 141
 #        NLS::setLang();
@@ -167,19 +167,19 @@  discard block
 block discarded – undo
167 167
                 }
168 168
             }
169 169
             if (!isset($app['templates']) && isset($app['fileroot'])) {
170
-                $app['templates'] = $app['fileroot'] . '/templates';
170
+                $app['templates'] = $app['fileroot'].'/templates';
171 171
             }
172 172
             if (!isset($app['jsuri']) && isset($app['webroot'])) {
173
-                $app['jsuri'] = $app['webroot'] . '/js';
173
+                $app['jsuri'] = $app['webroot'].'/js';
174 174
             }
175 175
             if (!isset($app['jsfs']) && isset($app['fileroot'])) {
176
-                $app['jsfs'] = $app['fileroot'] . '/js';
176
+                $app['jsfs'] = $app['fileroot'].'/js';
177 177
             }
178 178
             if (!isset($app['themesuri']) && isset($app['webroot'])) {
179
-                $app['themesuri'] = $app['webroot'] . '/themes';
179
+                $app['themesuri'] = $app['webroot'].'/themes';
180 180
             }
181 181
             if (!isset($app['themesfs']) && isset($app['fileroot'])) {
182
-                $app['themesfs'] = $app['fileroot'] . '/themes';
182
+                $app['themesfs'] = $app['fileroot'].'/themes';
183 183
             }
184 184
         }
185 185
 
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
         $apis = array();
243 243
 
244 244
         foreach (array_keys($this->_interfaces) as $interface) {
245
-            @list($api, ) = explode('/', $interface);
245
+            @list($api,) = explode('/', $interface);
246 246
             $apis[] = $api;
247 247
         }
248 248
 
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
                 } elseif (is_null($api) || ($method == $api)) {
286 286
                     if (isset($this->_apiCache[$app])) {
287 287
                         foreach (array_keys($this->_apiCache[$app]) as $service) {
288
-                            $methods[] = $method . '/' . $service;
288
+                            $methods[] = $method.'/'.$service;
289 289
                         }
290 290
                     }
291 291
                 }
@@ -348,8 +348,7 @@  discard block
 block discarded – undo
348 348
     function hasInterface($interface)
349 349
     {
350 350
         return !empty($this->_interfaces[$interface]) ?
351
-            $this->_interfaces[$interface] :
352
-            false;
351
+            $this->_interfaces[$interface] : false;
353 352
     }
354 353
 
355 354
     /**
@@ -406,7 +405,7 @@  discard block
 block discarded – undo
406 405
         } elseif (!empty($this->_interfaces[$interface])) {
407 406
             $app = $this->_interfaces[$interface];
408 407
         } else {
409
-            return PEAR::raiseError('The method "' . $method . '" is not defined in the Horde Registry.');
408
+            return PEAR::raiseError('The method "'.$method.'" is not defined in the Horde Registry.');
410 409
         }
411 410
 
412 411
         return $this->callByPackage($app, $call, $args);
@@ -434,9 +433,9 @@  discard block
 block discarded – undo
434 433
         }
435 434
 
436 435
         /* Make sure that the function actually exists. */
437
-        $function = '_' . $app . '_' . $call;
436
+        $function = '_'.$app.'_'.$call;
438 437
         if (!function_exists($function)) {
439
-            return PEAR::raiseError('The function implementing ' . $call . ' (' . $function . ') is not defined in ' . $app . '\'s API.');
438
+            return PEAR::raiseError('The function implementing '.$call.' ('.$function.') is not defined in '.$app.'\'s API.');
440 439
         }
441 440
 
442 441
         $checkPerms = isset($this->_apiCache[$app][$call]['checkperms']) ?
@@ -486,7 +485,7 @@  discard block
 block discarded – undo
486 485
         } elseif (!empty($this->_interfaces[$interface])) {
487 486
             $app = $this->_interfaces[$interface];
488 487
         } else {
489
-            return PEAR::raiseError('The method "' . $method . '" is not defined in the Horde Registry.');
488
+            return PEAR::raiseError('The method "'.$method.'" is not defined in the Horde Registry.');
490 489
         }
491 490
 
492 491
         return $this->linkByPackage($app, $call, $args, $extra);
@@ -512,12 +511,12 @@  discard block
 block discarded – undo
512 511
          * services and included the API file, so we don't try to do
513 512
          * it it again explicitly in this method. */
514 513
         if (!$this->hasMethod($call, $app)) {
515
-            return PEAR::raiseError('The method "' . $call . '" is not defined in ' . $app . '\'s API.');
514
+            return PEAR::raiseError('The method "'.$call.'" is not defined in '.$app.'\'s API.');
516 515
         }
517 516
 
518 517
         /* Make sure the link is defined. */
519 518
         if (empty($this->_apiCache[$app][$call]['link'])) {
520
-            return PEAR::raiseError('The link ' . $call . ' is not defined in ' . $app . '\'s API.');
519
+            return PEAR::raiseError('The link '.$call.' is not defined in '.$app.'\'s API.');
521 520
         }
522 521
 
523 522
         /* Initial link value. */
@@ -525,7 +524,7 @@  discard block
 block discarded – undo
525 524
 
526 525
         /* Fill in html-encoded arguments. */
527 526
         foreach ($args as $key => $val) {
528
-            $link = str_replace('%' . $key . '%', htmlentities($val), $link);
527
+            $link = str_replace('%'.$key.'%', htmlentities($val), $link);
529 528
         }
530 529
         if (isset($this->applications[$app]['webroot'])) {
531 530
             $link = str_replace('%application%', $this->get('webroot', $app), $link);
@@ -538,14 +537,14 @@  discard block
 block discarded – undo
538 537
 
539 538
         /* Fill in urlencoded arguments. */
540 539
         foreach ($args as $key => $val) {
541
-            $link = str_replace('|' . String::lower($key) . '|', urlencode($val), $link);
540
+            $link = str_replace('|'.String::lower($key).'|', urlencode($val), $link);
542 541
         }
543 542
 
544 543
         /* Append any extra, non-standard arguments. */
545 544
         if (is_array($extra)) {
546 545
             $extra_args = '';
547 546
             foreach ($extra as $key => $val) {
548
-                $extra_args .- '&' . urlencode($key) . '=' . urlencode($val);
547
+                $extra_args.- '&'.urlencode($key).'='.urlencode($val);
549 548
             }
550 549
         } else {
551 550
             $extra_args = $extra;
@@ -636,7 +635,7 @@  discard block
 block discarded – undo
636 635
         if (!isset($this->applications[$app]) ||
637 636
             $this->applications[$app]['status'] == 'inactive' ||
638 637
             ($this->applications[$app]['status'] == 'admin' && !Auth::isAdmin())) {
639
-            Horde::fatal($app . ' is not activated', __FILE__, __LINE__);
638
+            Horde::fatal($app.' is not activated', __FILE__, __LINE__);
640 639
         }
641 640
 
642 641
         /* If permissions checking is requested, return an error if
@@ -669,7 +668,7 @@  discard block
 block discarded – undo
669 668
             $language = $this->_prefsCache[$app]->getValue('language');
670 669
         }
671 670
         NLS::setLang($language);
672
-        NLS::setTextdomain($app, $this->applications[$app]['fileroot'] . '/locale', NLS::getCharset());
671
+        NLS::setTextdomain($app, $this->applications[$app]['fileroot'].'/locale', NLS::getCharset());
673 672
         String::setDefaultCharset(NLS::getCharset());
674 673
 
675 674
         /* Once we know everything succeeded and is in a consistent
@@ -704,7 +703,7 @@  discard block
 block discarded – undo
704 703
             #if (isset($language)) {
705 704
             #    NLS::setLang($language);
706 705
             #}
707
-            NLS::setTextdomain($this->_currentApp, $this->applications[$this->_currentApp]['fileroot'] . '/locale', NLS::getCharset());
706
+            NLS::setTextdomain($this->_currentApp, $this->applications[$this->_currentApp]['fileroot'].'/locale', NLS::getCharset());
708 707
             String::setDefaultCharset(NLS::getCharset());
709 708
         }
710 709
 
@@ -760,7 +759,7 @@  discard block
 block discarded – undo
760 759
             if (!isset($this->_confCache['horde'])) {
761 760
                 $conf = array();
762 761
                 ob_start();
763
-                $success = include HORDE_BASE . '/config/conf.php';
762
+                $success = include HORDE_BASE.'/config/conf.php';
764 763
                 $errors = ob_get_contents();
765 764
                 ob_end_clean();
766 765
                 if (!empty($errors)) {
@@ -789,9 +788,9 @@  discard block
 block discarded – undo
789 788
             }
790 789
 
791 790
             if ($app !== 'horde') {
792
-                $success = @include $this->applications[$app]['fileroot'] . '/config/conf.php';
791
+                $success = @include $this->applications[$app]['fileroot'].'/config/conf.php';
793 792
                 if (!$success) {
794
-                    return PEAR::raiseError('Failed to import application configuration for ' . $app);
793
+                    return PEAR::raiseError('Failed to import application configuration for '.$app);
795 794
                 }
796 795
             }
797 796
 
@@ -936,15 +935,15 @@  discard block
 block discarded – undo
936 935
         }
937 936
 
938 937
         /* This is the default location for the graphics. */
939
-        $img_dir[$app] = $this->get('themesuri', $app) . '/graphics';
938
+        $img_dir[$app] = $this->get('themesuri', $app).'/graphics';
940 939
 
941 940
         /* Figure out if this is going to be overridden by any theme
942 941
          * settings. */
943 942
         if (isset($GLOBALS['prefs']) && ($theme = $GLOBALS['prefs']->getValue('theme')) &&
944
-            (@include $this->get('themesfs', 'horde') . '/' . $theme . '/info.php') &&
943
+            (@include $this->get('themesfs', 'horde').'/'.$theme.'/info.php') &&
945 944
             isset($theme_icons) &&
946 945
             in_array($app, $theme_icons)) {
947
-            $img_dir[$app] = $this->get('themesuri', $app) . '/' . $theme . '/graphics';
946
+            $img_dir[$app] = $this->get('themesuri', $app).'/'.$theme.'/graphics';
948 947
         }
949 948
 
950 949
         return $img_dir[$app];
@@ -960,7 +959,7 @@  discard block
 block discarded – undo
960 959
      */
961 960
     function _getIcon($app)
962 961
     {
963
-        return $this->getImageDir($app) . '/' . $app . '.png';
962
+        return $this->getImageDir($app).'/'.$app.'.png';
964 963
     }
965 964
 
966 965
     /**
@@ -984,7 +983,7 @@  discard block
 block discarded – undo
984 983
         if (!isset($this->applications[$app])) {
985 984
             return PEAR::raiseError(sprintf(_("'%s' is not configured in the Horde Registry."), $app));
986 985
         }
987
-        return $this->applications[$app]['webroot'] . '/' . (isset($this->applications[$app]['initial_page']) ? $this->applications[$app]['initial_page'] : '');
986
+        return $this->applications[$app]['webroot'].'/'.(isset($this->applications[$app]['initial_page']) ? $this->applications[$app]['initial_page'] : '');
988 987
     }
989 988
 
990 989
     /**
@@ -1005,7 +1004,7 @@  discard block
 block discarded – undo
1005 1004
         $apps = $this->listApps($status);
1006 1005
         foreach ($apps as $app) {
1007 1006
             $_services = $_types = null;
1008
-            $api = $this->get('fileroot', $app) . '/lib/api.php';
1007
+            $api = $this->get('fileroot', $app).'/lib/api.php';
1009 1008
             if (is_readable($api)) {
1010 1009
                 include_once $api;
1011 1010
             }
@@ -1019,7 +1018,7 @@  discard block
 block discarded – undo
1019 1018
                     /* Prefix non-Horde types with the application
1020 1019
                      * name. */
1021 1020
                     $prefix = $app == 'horde' ? '' : "${app}_";
1022
-                    $this->_typeCache[$prefix . $type] = $params;
1021
+                    $this->_typeCache[$prefix.$type] = $params;
1023 1022
                 }
1024 1023
             }
1025 1024
         }
Please login to merge, or discard this patch.
Braces   +215 added lines, -98 removed lines patch added patch discarded remove patch
@@ -26,7 +26,8 @@  discard block
 block discarded – undo
26 26
  * @since   Horde 1.3
27 27
  * @package Horde_Framework
28 28
  */
29
-class Registry {
29
+class Registry
30
+{
30 31
 
31 32
     /**
32 33
      * Hash storing all of the known services and callbacks.
@@ -99,7 +100,8 @@  discard block
 block discarded – undo
99 100
     {
100 101
         static $registry;
101 102
 
102
-        if (!isset($registry)) {
103
+        if (!isset($registry))
104
+        {
103 105
             $registry = new Registry($session_flags);
104 106
         }
105 107
 
@@ -120,14 +122,18 @@  discard block
 block discarded – undo
120 122
         $this->importConfig('horde');
121 123
 
122 124
         /* Start a session. */
123
-        if ($session_flags & HORDE_SESSION_NONE) {
125
+        if ($session_flags & HORDE_SESSION_NONE)
126
+        {
124 127
             /* Never start a session if the session flags include
125 128
                HORDE_SESSION_NONE. */
126 129
             $_SESSION = array();
127
-        } else {
130
+        }
131
+        else
132
+        {
128 133
             Horde::setupSessionHandler();
129 134
             @session_start();
130
-            if ($session_flags & HORDE_SESSION_READONLY) {
135
+            if ($session_flags & HORDE_SESSION_READONLY)
136
+            {
131 137
                 /* Close the session immediately so no changes can be
132 138
                    made but values are still available. */
133 139
                 @session_write_close();
@@ -143,42 +149,55 @@  discard block
 block discarded – undo
143 149
 #        String::setDefaultCharset(NLS::getCharset());
144 150
 
145 151
         /* Stop system if Horde is inactive. */
146
-        if ($this->applications['horde']['status'] == 'inactive') {
152
+        if ($this->applications['horde']['status'] == 'inactive')
153
+        {
147 154
             Horde::fatal(_("This system is currently deactivated."), __FILE__, __LINE__);
148 155
         }
149 156
 
150 157
         /* Scan for all APIs provided by each app, and set other
151 158
          * common defaults like templates and graphics. */
152 159
         $appList = array_keys($this->applications);
153
-        foreach ($appList as $appName) {
160
+        foreach ($appList as $appName)
161
+        {
154 162
             $app = &$this->applications[$appName];
155 163
             if (($app['status'] == 'heading') ||
156 164
                 ($app['status'] == 'inactive') ||
157
-                ($app['status'] == 'admin' && !Auth::isAdmin())) {
165
+                ($app['status'] == 'admin' && !Auth::isAdmin()))
166
+            {
158 167
                 continue;
159 168
             }
160
-            if (isset($app['provides'])) {
161
-                if (is_array($app['provides'])) {
162
-                    foreach ($app['provides'] as $interface) {
169
+            if (isset($app['provides']))
170
+            {
171
+                if (is_array($app['provides']))
172
+                {
173
+                    foreach ($app['provides'] as $interface)
174
+                    {
163 175
                         $this->_interfaces[$interface] = $appName;
164 176
                     }
165
-                } else {
177
+                }
178
+                else
179
+                {
166 180
                     $this->_interfaces[$app['provides']] = $appName;
167 181
                 }
168 182
             }
169
-            if (!isset($app['templates']) && isset($app['fileroot'])) {
183
+            if (!isset($app['templates']) && isset($app['fileroot']))
184
+            {
170 185
                 $app['templates'] = $app['fileroot'] . '/templates';
171 186
             }
172
-            if (!isset($app['jsuri']) && isset($app['webroot'])) {
187
+            if (!isset($app['jsuri']) && isset($app['webroot']))
188
+            {
173 189
                 $app['jsuri'] = $app['webroot'] . '/js';
174 190
             }
175
-            if (!isset($app['jsfs']) && isset($app['fileroot'])) {
191
+            if (!isset($app['jsfs']) && isset($app['fileroot']))
192
+            {
176 193
                 $app['jsfs'] = $app['fileroot'] . '/js';
177 194
             }
178
-            if (!isset($app['themesuri']) && isset($app['webroot'])) {
195
+            if (!isset($app['themesuri']) && isset($app['webroot']))
196
+            {
179 197
                 $app['themesuri'] = $app['webroot'] . '/themes';
180 198
             }
181
-            if (!isset($app['themesfs']) && isset($app['fileroot'])) {
199
+            if (!isset($app['themesfs']) && isset($app['fileroot']))
200
+            {
182 201
                 $app['themesfs'] = $app['fileroot'] . '/themes';
183 202
             }
184 203
         }
@@ -191,7 +210,8 @@  discard block
 block discarded – undo
191 210
 #        $notification->attach('javascript');
192 211
 
193 212
         /* Register access key logger for translators. */
194
-        if (@$GLOBALS['conf']['log_accesskeys']) {
213
+        if (@$GLOBALS['conf']['log_accesskeys'])
214
+        {
195 215
             register_shutdown_function(create_function('', 'Horde::getAccessKey(null, null, true);'));
196 216
         }
197 217
     }
@@ -216,13 +236,16 @@  discard block
 block discarded – undo
216 236
     function listApps($filter = null, $assoc = false, $permission = PERMS_SHOW)
217 237
     {
218 238
         $apps = array();
219
-        if (is_null($filter)) {
239
+        if (is_null($filter))
240
+        {
220 241
             $filter = array('notoolbar', 'active');
221 242
         }
222 243
 
223
-        foreach ($this->applications as $app => $params) {
244
+        foreach ($this->applications as $app => $params)
245
+        {
224 246
             if (in_array($params['status'], $filter) &&
225
-                (defined('AUTH_HANDLER') || $this->hasPermission($app, $permission))) {
247
+                (defined('AUTH_HANDLER') || $this->hasPermission($app, $permission)))
248
+            {
226 249
                 $assoc ? $apps[$app] = $app : $apps[] = $app;
227 250
             }
228 251
         }
@@ -241,7 +264,8 @@  discard block
 block discarded – undo
241 264
     {
242 265
         $apis = array();
243 266
 
244
-        foreach (array_keys($this->_interfaces) as $interface) {
267
+        foreach (array_keys($this->_interfaces) as $interface)
268
+        {
245 269
             @list($api, ) = explode('/', $interface);
246 270
             $apis[] = $api;
247 271
         }
@@ -266,25 +290,37 @@  discard block
 block discarded – undo
266 290
 
267 291
         $this->_fillAPICache();
268 292
 
269
-        foreach (array_keys($this->applications) as $app) {
270
-            if (isset($this->applications[$app]['provides'])) {
293
+        foreach (array_keys($this->applications) as $app)
294
+        {
295
+            if (isset($this->applications[$app]['provides']))
296
+            {
271 297
                 $provides = $this->applications[$app]['provides'];
272
-                if (!is_array($provides)) {
298
+                if (!is_array($provides))
299
+                {
273 300
                     $provides = array($provides);
274 301
                 }
275
-            } else {
302
+            }
303
+            else
304
+            {
276 305
                 $provides = array();
277 306
             }
278 307
 
279
-            foreach ($provides as $method) {
280
-                if (strpos($method, '/') !== false) {
308
+            foreach ($provides as $method)
309
+            {
310
+                if (strpos($method, '/') !== false)
311
+                {
281 312
                     if (is_null($api) ||
282
-                        (substr($method, 0, strlen($api)) == $api)) {
313
+                        (substr($method, 0, strlen($api)) == $api))
314
+                    {
283 315
                         $methods[] = $method;
284 316
                     }
285
-                } elseif (is_null($api) || ($method == $api)) {
286
-                    if (isset($this->_apiCache[$app])) {
287
-                        foreach (array_keys($this->_apiCache[$app]) as $service) {
317
+                }
318
+                elseif (is_null($api) || ($method == $api))
319
+                {
320
+                    if (isset($this->_apiCache[$app]))
321
+                    {
322
+                        foreach (array_keys($this->_apiCache[$app]) as $service)
323
+                        {
288 324
                             $methods[] = $method . '/' . $service;
289 325
                         }
290 326
                     }
@@ -321,7 +357,8 @@  discard block
 block discarded – undo
321 357
      */
322 358
     function getSignature($method)
323 359
     {
324
-        if (!($app = $this->hasMethod($method))) {
360
+        if (!($app = $this->hasMethod($method)))
361
+        {
325 362
             return;
326 363
         }
327 364
 
@@ -329,7 +366,8 @@  discard block
 block discarded – undo
329 366
 
330 367
         @list(, $function) = explode('/', $method);
331 368
         if (isset($this->_apiCache[$app][$function]['type']) &&
332
-            isset($this->_apiCache[$app][$function]['args'])) {
369
+            isset($this->_apiCache[$app][$function]['args']))
370
+        {
333 371
             return array($this->_apiCache[$app][$function]['args'], $this->_apiCache[$app][$function]['type']);
334 372
         }
335 373
     }
@@ -365,16 +403,24 @@  discard block
 block discarded – undo
365 403
      */
366 404
     function hasMethod($method, $app = null)
367 405
     {
368
-        if (is_null($app)) {
406
+        if (is_null($app))
407
+        {
369 408
             @list($interface, $call) = explode('/', $method);
370
-            if (!empty($this->_interfaces[$method])) {
409
+            if (!empty($this->_interfaces[$method]))
410
+            {
371 411
                 $app = $this->_interfaces[$method];
372
-            } elseif (!empty($this->_interfaces[$interface])) {
412
+            }
413
+            elseif (!empty($this->_interfaces[$interface]))
414
+            {
373 415
                 $app = $this->_interfaces[$interface];
374
-            } else {
416
+            }
417
+            else
418
+            {
375 419
                 return false;
376 420
             }
377
-        } else {
421
+        }
422
+        else
423
+        {
378 424
             $call = $method;
379 425
         }
380 426
 
@@ -401,11 +447,16 @@  discard block
 block discarded – undo
401 447
     {
402 448
         @list($interface, $call) = explode('/', $method);
403 449
 
404
-        if (!empty($this->_interfaces[$method])) {
450
+        if (!empty($this->_interfaces[$method]))
451
+        {
405 452
             $app = $this->_interfaces[$method];
406
-        } elseif (!empty($this->_interfaces[$interface])) {
453
+        }
454
+        elseif (!empty($this->_interfaces[$interface]))
455
+        {
407 456
             $app = $this->_interfaces[$interface];
408
-        } else {
457
+        }
458
+        else
459
+        {
409 460
             return PEAR::raiseError('The method "' . $method . '" is not defined in the Horde Registry.');
410 461
         }
411 462
 
@@ -429,13 +480,15 @@  discard block
 block discarded – undo
429 480
         /* Note: calling hasMethod() makes sure that we've cached
430 481
          * $app's services and included the API file, so we don't try
431 482
          * to do it again explicitly in this method. */
432
-        if (!$this->hasMethod($call, $app)) {
483
+        if (!$this->hasMethod($call, $app))
484
+        {
433 485
             return PEAR::raiseError(sprintf('The method "%s" is not defined in the API for %s.', $call, $app));
434 486
         }
435 487
 
436 488
         /* Make sure that the function actually exists. */
437 489
         $function = '_' . $app . '_' . $call;
438
-        if (!function_exists($function)) {
490
+        if (!function_exists($function))
491
+        {
439 492
             return PEAR::raiseError('The function implementing ' . $call . ' (' . $function . ') is not defined in ' . $app . '\'s API.');
440 493
         }
441 494
 
@@ -446,7 +499,8 @@  discard block
 block discarded – undo
446 499
          * including any files which might do it for us. Return an
447 500
          * error immediately if pushApp() fails. */
448 501
         $pushed = $this->pushApp($app, $checkPerms);
449
-        if (is_a($pushed, 'PEAR_Error')) {
502
+        if (is_a($pushed, 'PEAR_Error'))
503
+        {
450 504
             return $pushed;
451 505
         }
452 506
 
@@ -454,7 +508,8 @@  discard block
 block discarded – undo
454 508
 
455 509
         /* If we changed application context in the course of this
456 510
          * call, undo that change now. */
457
-        if ($pushed === true) {
511
+        if ($pushed === true)
512
+        {
458 513
             $this->popApp();
459 514
         }
460 515
 
@@ -481,11 +536,16 @@  discard block
 block discarded – undo
481 536
     {
482 537
         @list($interface, $call) = explode('/', $method);
483 538
 
484
-        if (!empty($this->_interfaces[$method])) {
539
+        if (!empty($this->_interfaces[$method]))
540
+        {
485 541
             $app = $this->_interfaces[$method];
486
-        } elseif (!empty($this->_interfaces[$interface])) {
542
+        }
543
+        elseif (!empty($this->_interfaces[$interface]))
544
+        {
487 545
             $app = $this->_interfaces[$interface];
488
-        } else {
546
+        }
547
+        else
548
+        {
489 549
             return PEAR::raiseError('The method "' . $method . '" is not defined in the Horde Registry.');
490 550
         }
491 551
 
@@ -511,12 +571,14 @@  discard block
 block discarded – undo
511 571
         /* Note: calling hasMethod makes sure that we've cached $app's
512 572
          * services and included the API file, so we don't try to do
513 573
          * it it again explicitly in this method. */
514
-        if (!$this->hasMethod($call, $app)) {
574
+        if (!$this->hasMethod($call, $app))
575
+        {
515 576
             return PEAR::raiseError('The method "' . $call . '" is not defined in ' . $app . '\'s API.');
516 577
         }
517 578
 
518 579
         /* Make sure the link is defined. */
519
-        if (empty($this->_apiCache[$app][$call]['link'])) {
580
+        if (empty($this->_apiCache[$app][$call]['link']))
581
+        {
520 582
             return PEAR::raiseError('The link ' . $call . ' is not defined in ' . $app . '\'s API.');
521 583
         }
522 584
 
@@ -524,10 +586,12 @@  discard block
 block discarded – undo
524 586
         $link = $this->_apiCache[$app][$call]['link'];
525 587
 
526 588
         /* Fill in html-encoded arguments. */
527
-        foreach ($args as $key => $val) {
589
+        foreach ($args as $key => $val)
590
+        {
528 591
             $link = str_replace('%' . $key . '%', htmlentities($val), $link);
529 592
         }
530
-        if (isset($this->applications[$app]['webroot'])) {
593
+        if (isset($this->applications[$app]['webroot']))
594
+        {
531 595
             $link = str_replace('%application%', $this->get('webroot', $app), $link);
532 596
         }
533 597
 
@@ -537,17 +601,22 @@  discard block
 block discarded – undo
537 601
         $link = preg_replace('|%.+%|U', '', $link);
538 602
 
539 603
         /* Fill in urlencoded arguments. */
540
-        foreach ($args as $key => $val) {
604
+        foreach ($args as $key => $val)
605
+        {
541 606
             $link = str_replace('|' . String::lower($key) . '|', urlencode($val), $link);
542 607
         }
543 608
 
544 609
         /* Append any extra, non-standard arguments. */
545
-        if (is_array($extra)) {
610
+        if (is_array($extra))
611
+        {
546 612
             $extra_args = '';
547
-            foreach ($extra as $key => $val) {
613
+            foreach ($extra as $key => $val)
614
+            {
548 615
                 $extra_args .- '&' . urlencode($key) . '=' . urlencode($val);
549 616
             }
550
-        } else {
617
+        }
618
+        else
619
+        {
551 620
             $extra_args = $extra;
552 621
         }
553 622
         $link = str_replace('|extra|', $extra_args, $link);
@@ -574,11 +643,13 @@  discard block
 block discarded – undo
574 643
      */
575 644
     function applicationFilePath($path, $app = null)
576 645
     {
577
-        if (is_null($app)) {
646
+        if (is_null($app))
647
+        {
578 648
             $app = $this->_currentApp;
579 649
         }
580 650
 
581
-        if (!isset($this->applications[$app])) {
651
+        if (!isset($this->applications[$app]))
652
+        {
582 653
             return PEAR::raiseError(sprintf(_("'%s' is not configured in the Horde Registry."), $app));
583 654
         }
584 655
 
@@ -599,7 +670,8 @@  discard block
 block discarded – undo
599 670
      */
600 671
     function applicationWebPath($path, $app = null)
601 672
     {
602
-        if (!isset($app)) {
673
+        if (!isset($app))
674
+        {
603 675
             $app = $this->_currentApp;
604 676
         }
605 677
 
@@ -628,14 +700,16 @@  discard block
 block discarded – undo
628 700
      */
629 701
     function pushApp($app, $checkPerms = true)
630 702
     {
631
-        if ($app == $this->_currentApp) {
703
+        if ($app == $this->_currentApp)
704
+        {
632 705
             return false;
633 706
         }
634 707
 
635 708
         /* Bail out if application is not present or inactive. */
636 709
         if (!isset($this->applications[$app]) ||
637 710
             $this->applications[$app]['status'] == 'inactive' ||
638
-            ($this->applications[$app]['status'] == 'admin' && !Auth::isAdmin())) {
711
+            ($this->applications[$app]['status'] == 'admin' && !Auth::isAdmin()))
712
+        {
639 713
             Horde::fatal($app . ' is not activated', __FILE__, __LINE__);
640 714
         }
641 715
 
@@ -646,14 +720,16 @@  discard block
 block discarded – undo
646 720
          *  - To all admins.
647 721
          *  - To all authenticated users if no permission is set on $app.
648 722
          *  - To anyone who is allowed by an explicit ACL on $app. */
649
-        if ($checkPerms && !$this->hasPermission($app)) {
723
+        if ($checkPerms && !$this->hasPermission($app))
724
+        {
650 725
             Horde::logMessage(sprintf('User %s does not have READ permission for %s', Auth::getAuth(), $app), __FILE__, __LINE__, PEAR_LOG_DEBUG);
651 726
             return PEAR::raiseError(sprintf(_("User %s is not authorised for %s."), Auth::getAuth(), $this->applications[$app]['name']), 'permission_denied');
652 727
         }
653 728
 
654 729
         /* Import this application's configuration values. */
655 730
         $success = $this->importConfig($app);
656
-        if (is_a($success, 'PEAR_Error')) {
731
+        if (is_a($success, 'PEAR_Error'))
732
+        {
657 733
             return $success;
658 734
         }
659 735
 
@@ -665,7 +741,8 @@  discard block
 block discarded – undo
665 741
          * selected in the preferences. */
666 742
         $language = '';
667 743
         if (isset($this->_prefsCache[$app]) &&
668
-            isset($this->_prefsCache[$app]->_prefs['language'])) {
744
+            isset($this->_prefsCache[$app]->_prefs['language']))
745
+        {
669 746
             $language = $this->_prefsCache[$app]->getValue('language');
670 747
         }
671 748
         NLS::setLang($language);
@@ -697,7 +774,8 @@  discard block
 block discarded – undo
697 774
         /* Import the new active application's configuration values
698 775
          * and set the gettext domain and the preferred language. */
699 776
         $this->_currentApp = count($this->_appStack) ? end($this->_appStack) : null;
700
-        if ($this->_currentApp) {
777
+        if ($this->_currentApp)
778
+        {
701 779
             $this->importConfig($this->_currentApp);
702 780
             $this->loadPrefs($this->_currentApp);
703 781
             #$language = $GLOBALS['prefs']->getValue('language');
@@ -756,17 +834,21 @@  discard block
 block discarded – undo
756 834
 
757 835
         /* Cache config values so that we don't re-read files on every
758 836
          * popApp() call. */
759
-        if (!isset($this->_confCache[$app])) {
760
-            if (!isset($this->_confCache['horde'])) {
837
+        if (!isset($this->_confCache[$app]))
838
+        {
839
+            if (!isset($this->_confCache['horde']))
840
+            {
761 841
                 $conf = array();
762 842
                 ob_start();
763 843
                 $success = include HORDE_BASE . '/config/conf.php';
764 844
                 $errors = ob_get_contents();
765 845
                 ob_end_clean();
766
-                if (!empty($errors)) {
846
+                if (!empty($errors))
847
+                {
767 848
                     return PEAR::raiseError(sprintf('Failed to import Horde configuration: %s', strip_tags($errors)));
768 849
                 }
769
-                if (!$success) {
850
+                if (!$success)
851
+                {
770 852
                     return PEAR::raiseError('Failed to import Horde configuration.');
771 853
                 }
772 854
 
@@ -781,16 +863,21 @@  discard block
 block discarded – undo
781 863
                 @set_time_limit($conf['max_exec_time']);
782 864
 
783 865
                 /* Set the umask according to config settings. */
784
-                if (isset($conf['umask'])) {
866
+                if (isset($conf['umask']))
867
+                {
785 868
                     umask($conf['umask']);
786 869
                 }
787
-            } else {
870
+            }
871
+            else
872
+            {
788 873
                 $conf = $this->_confCache['horde'];
789 874
             }
790 875
 
791
-            if ($app !== 'horde') {
876
+            if ($app !== 'horde')
877
+            {
792 878
                 $success = @include $this->applications[$app]['fileroot'] . '/config/conf.php';
793
-                if (!$success) {
879
+                if (!$success)
880
+                {
794 881
                     return PEAR::raiseError('Failed to import application configuration for ' . $app);
795 882
                 }
796 883
             }
@@ -818,7 +905,8 @@  discard block
 block discarded – undo
818 905
 
819 906
         require_once 'Horde/Prefs.php';
820 907
 
821
-        if ($app === null) {
908
+        if ($app === null)
909
+        {
822 910
             $app = $this->_currentApp;
823 911
         }
824 912
 
@@ -861,15 +949,21 @@  discard block
 block discarded – undo
861 949
      */
862 950
     function unloadPrefs($app = null)
863 951
     {
864
-        if ($app === null) {
952
+        if ($app === null)
953
+        {
865 954
             $this->_prefsCache = array();
866
-        } elseif (isset($this->_prefsCache[$app])) {
955
+        }
956
+        elseif (isset($this->_prefsCache[$app]))
957
+        {
867 958
             unset($this->_prefsCache[$app]);
868
-        } else {
959
+        }
960
+        else
961
+        {
869 962
             return;
870 963
         }
871 964
 
872
-        if ($this->_currentApp) {
965
+        if ($this->_currentApp)
966
+        {
873 967
             $this->loadPrefs();
874 968
         }
875 969
     }
@@ -891,23 +985,33 @@  discard block
 block discarded – undo
891 985
      */
892 986
     function get($parameter, $app = null)
893 987
     {
894
-        if (is_null($app)) {
988
+        if (is_null($app))
989
+        {
895 990
             $app = $this->_currentApp;
896 991
         }
897 992
 
898
-        if (isset($this->applications[$app][$parameter])) {
993
+        if (isset($this->applications[$app][$parameter]))
994
+        {
899 995
             $pval = $this->applications[$app][$parameter];
900
-        } else {
901
-            if ($parameter == 'icon') {
996
+        }
997
+        else
998
+        {
999
+            if ($parameter == 'icon')
1000
+            {
902 1001
                 $pval = $this->_getIcon($app);
903
-            } else {
1002
+            }
1003
+            else
1004
+            {
904 1005
                 $pval = isset($this->applications['horde'][$parameter]) ? $this->applications['horde'][$parameter] : null;
905 1006
             }
906 1007
         }
907 1008
 
908
-        if ($parameter == 'name') {
1009
+        if ($parameter == 'name')
1010
+        {
909 1011
             return _($pval);
910
-        } else {
1012
+        }
1013
+        else
1014
+        {
911 1015
             return $pval;
912 1016
         }
913 1017
     }
@@ -926,12 +1030,14 @@  discard block
 block discarded – undo
926 1030
      */
927 1031
     function getImageDir($app = null)
928 1032
     {
929
-        if (empty($app)) {
1033
+        if (empty($app))
1034
+        {
930 1035
             $app = $this->_currentApp;
931 1036
         }
932 1037
 
933 1038
         static $img_dir = array();
934
-        if (isset($img_dir[$app])) {
1039
+        if (isset($img_dir[$app]))
1040
+        {
935 1041
             return $img_dir[$app];
936 1042
         }
937 1043
 
@@ -943,7 +1049,8 @@  discard block
 block discarded – undo
943 1049
         if (isset($GLOBALS['prefs']) && ($theme = $GLOBALS['prefs']->getValue('theme')) &&
944 1050
             (@include $this->get('themesfs', 'horde') . '/' . $theme . '/info.php') &&
945 1051
             isset($theme_icons) &&
946
-            in_array($app, $theme_icons)) {
1052
+            in_array($app, $theme_icons))
1053
+        {
947 1054
             $img_dir[$app] = $this->get('themesuri', $app) . '/' . $theme . '/graphics';
948 1055
         }
949 1056
 
@@ -977,11 +1084,13 @@  discard block
 block discarded – undo
977 1084
      */
978 1085
     function getInitialPage($app = null)
979 1086
     {
980
-        if (is_null($app)) {
1087
+        if (is_null($app))
1088
+        {
981 1089
             $app = $this->_currentApp;
982 1090
         }
983 1091
 
984
-        if (!isset($this->applications[$app])) {
1092
+        if (!isset($this->applications[$app]))
1093
+        {
985 1094
             return PEAR::raiseError(sprintf(_("'%s' is not configured in the Horde Registry."), $app));
986 1095
         }
987 1096
         return $this->applications[$app]['webroot'] . '/' . (isset($this->applications[$app]['initial_page']) ? $this->applications[$app]['initial_page'] : '');
@@ -994,7 +1103,8 @@  discard block
 block discarded – undo
994 1103
      */
995 1104
     function _fillAPICache()
996 1105
     {
997
-        if (!empty($this->_apiCache)) {
1106
+        if (!empty($this->_apiCache))
1107
+        {
998 1108
             return;
999 1109
         }
1000 1110
 
@@ -1003,19 +1113,26 @@  discard block
 block discarded – undo
1003 1113
 #            $status[] = 'admin';
1004 1114
 #        }
1005 1115
         $apps = $this->listApps($status);
1006
-        foreach ($apps as $app) {
1116
+        foreach ($apps as $app)
1117
+        {
1007 1118
             $_services = $_types = null;
1008 1119
             $api = $this->get('fileroot', $app) . '/lib/api.php';
1009
-            if (is_readable($api)) {
1120
+            if (is_readable($api))
1121
+            {
1010 1122
                 include_once $api;
1011 1123
             }
1012
-            if (!isset($_services)) {
1124
+            if (!isset($_services))
1125
+            {
1013 1126
                 $this->_apiCache[$app] = array();
1014
-            } else {
1127
+            }
1128
+            else
1129
+            {
1015 1130
                 $this->_apiCache[$app] = $_services;
1016 1131
             }
1017
-            if (isset($_types)) {
1018
-                foreach ($_types as $type => $params) {
1132
+            if (isset($_types))
1133
+            {
1134
+                foreach ($_types as $type => $params)
1135
+                {
1019 1136
                     /* Prefix non-Horde types with the application
1020 1137
                      * name. */
1021 1138
                     $prefix = $app == 'horde' ? '' : "${app}_";
Please login to merge, or discard this patch.