Test Failed
Push — CI ( 0f01dd...c95a04 )
by Adam
55:13
created

HTTP_WebDAV_Server_vCal::ServeRequest()   F

Complexity

Conditions 16
Paths 2304

Size

Total Lines 126
Code Lines 50

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 126
rs 2
cc 16
eloc 50
nc 2304
nop 1

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3
/*********************************************************************************
4
 * SugarCRM Community Edition is a customer relationship management program developed by
5
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
6
7
 * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
8
 * Copyright (C) 2011 - 2014 Salesagility Ltd.
9
 *
10
 * This program is free software; you can redistribute it and/or modify it under
11
 * the terms of the GNU Affero General Public License version 3 as published by the
12
 * Free Software Foundation with the addition of the following permission added
13
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
14
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
15
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
16
 *
17
 * This program is distributed in the hope that it will be useful, but WITHOUT
18
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
20
 * details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License along with
23
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
24
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
25
 * 02110-1301 USA.
26
 *
27
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
28
 * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
29
 *
30
 * The interactive user interfaces in modified source and object code versions
31
 * of this program must display Appropriate Legal Notices, as required under
32
 * Section 5 of the GNU Affero General Public License version 3.
33
 *
34
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
35
 * these Appropriate Legal Notices must retain the display of the "Powered by
36
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
37
 * reasonably feasible for  technical reasons, the Appropriate Legal Notices must
38
 * display the words  "Powered by SugarCRM" and "Supercharged by SuiteCRM".
39
 ********************************************************************************/
40
41
42
43
44
45
46
require_once 'modules/Calendar/Calendar.php';
47
48
require_once 'include/HTTP_WebDAV_Server/Server.php';
49
50
51
    /**
52
     * Filesystem access using WebDAV
53
     *
54
     * @access public
55
     */
56
    class HTTP_WebDAV_Server_vCal extends HTTP_WebDAV_Server
57
    {
58
        /**
59
         * Root directory for WebDAV access
60
         *
61
         * Defaults to webserver document root (set by ServeRequest)
62
         *
63
         * @access private
64
         * @var    string
65
         */
66
        var $base = "";
67
        var $vcal_focus;
68
        var $vcal_type = "";
69
        var $source = "";
70
        var $publish_key = "";
71
72
        function HTTP_WebDAV_Server_vCal()
73
        {
74
           $this->vcal_focus = new vCal();
75
           $this->user_focus = new User();
76
        }
77
78
79
        /**
80
         * Serve a webdav request
81
         *
82
         * @access public
83
         * @param  string
84
         */
85
        function ServeRequest($base = false)
86
        {
87
88
            global $sugar_config,$current_language;
89
90
            if (!empty($sugar_config['session_dir']))
91
            {
92
               session_save_path($sugar_config['session_dir']);
93
            }
94
95
            session_start();
96
97
            // clean_incoming_data();
98
99
100
            $current_language = $sugar_config['default_language'];
101
102
            // special treatment for litmus compliance test
103
            // reply on its identifier header
104
            // not needed for the test itself but eases debugging
105
/*
106
            foreach(apache_request_headers() as $key => $value) {
107
                if(stristr($key,"litmus")) {
108
                    error_log("Litmus test $value");
109
                    header("X-Litmus-reply: ".$value);
110
                }
111
            }
112
*/
113
114
            // set root directory, defaults to webserver document root if not set
115
            if ($base) {
116
                $this->base = realpath($base); // TODO throw if not a directory
117
            } else if(!$this->base) {
118
                $this->base = $_SERVER['DOCUMENT_ROOT'];
119
            }
120
121
122
            $query_arr =  array();
123
             // set path
124
            if ( empty($_SERVER["PATH_INFO"]))
125
            {
126
				$this->path = "/";
127
				if(strtolower($_SERVER["REQUEST_METHOD"]) == 'get'){
128
					$query_arr = $_REQUEST;
129
				}else{
130
					parse_str($_REQUEST['parms'],$query_arr);
131
				}
132
            } else{
133
              $this->path = $this->_urldecode( $_SERVER["PATH_INFO"]);
134
135
              if(ini_get("magic_quotes_gpc")) {
136
               $this->path = stripslashes($this->path);
137
              }
138
139
              $query_str = preg_replace('/^\//','',$this->path);
140
              $query_arr =  array();
141
              parse_str($query_str,$query_arr);
142
            }
143
144
145
            if ( ! empty($query_arr['type']))
146
            {
147
              $this->vcal_type = $query_arr['type'];
148
            }
149
            else {
150
              $this->vcal_type = 'vfb';
151
            }
152
153
            if ( ! empty($query_arr['source']))
154
            {
155
              $this->source = $query_arr['source'];
156
            }
157
            else {
158
              $this->source = 'outlook';
159
            }
160
161
            if ( ! empty($query_arr['key']))
162
            {
163
              $this->publish_key = $query_arr['key'];
164
            }
165
166
            // select user by email
167
            if ( ! empty($query_arr['email']))
168
            {
169
170
171
              // clean the string!
172
              $query_arr['email'] = clean_string($query_arr['email']);
173
              //get user info
174
              $this->user_focus->retrieve_by_email_address( $query_arr['email']);
175
176
            }
177
            // else select user by user_name
178
            else if ( ! empty($query_arr['user_name']))
179
            {
180
              // clean the string!
181
              $query_arr['user_name'] = clean_string($query_arr['user_name']);
182
183
              //get user info
184
              $arr = array('user_name'=>$query_arr['user_name']);
185
              $this->user_focus->retrieve_by_string_fields($arr);
186
            }
187
            // else select user by user id
188
            else if ( ! empty($query_arr['user_id']))
189
            {
190
                $this->user_focus->retrieve($query_arr['user_id']);
191
            }
192
193
            // if we haven't found a user, then return 404
194
            if ( empty($this->user_focus->id) || $this->user_focus->id == -1)
195
            {
196
                $this->http_status('401 Unauthorized');
197
                if (!isset($query_arr['noAuth'])) {
198
                    header('WWW-Authenticate: Basic realm="'.($this->http_auth_realm).'"');
199
                }
200
                return;
201
            }
202
203
//            if(empty($this->user_focus->user_preferences))
204
//            {
205
                     $this->user_focus->loadPreferences();
206
//            }
207
208
            // let the base class do all the work
209
            parent::ServeRequest();
210
        }
211
212
        /**
213
         * No authentication is needed here
214
         *
215
         * @access private
216
         * @param  string  HTTP Authentication type (Basic, Digest, ...)
217
         * @param  string  Username
218
         * @param  string  Password
219
         * @return bool    true on successful authentication
220
         */
221
        function check_auth($type, $user, $pass)
222
        {
223
            if(isset($_SESSION['authenticated_user_id'])) {
224
                // allow logged in users access to freebusy info
225
                return true;
226
            }
227
            if(!empty($this->publish_key) && !empty($this->user_focus) && $this->user_focus->getPreference('calendar_publish_key' ) == $this->publish_key) {
228
                return true;
229
            }
230
            return false;
231
        }
232
233
234
        function GET()
235
        {
236
            return true;
237
        }
238
239
        // {{{ http_GET()
240
241
        /**
242
        * GET method handler
243
        *
244
        * @param void
245
        * @returns void
246
        */
247
        function http_GET()
248
        {
249
250
           if ($this->vcal_type == 'vfb')
251
           {
252
             $this->http_status("200 OK");
253
             echo $this->vcal_focus->get_vcal_freebusy($this->user_focus);
254
           } else {
255
             $this->http_status("404 Not Found");
256
           }
257
258
        }
259
        // }}}
260
261
262
        // {{{ http_PUT()
263
264
        /**
265
        * PUT method handler
266
        *
267
        * @param  void
268
        * @return void
269
        */
270
        function http_PUT()
271
        {
272
            $options = Array();
273
            $options["path"] = $this->path;
274
            $options["content_length"] = $_SERVER["CONTENT_LENGTH"];
275
276
            // get the Content-type
277
            if (isset($_SERVER["CONTENT_TYPE"])) {
278
                // for now we do not support any sort of multipart requests
279
                if (!strncmp($_SERVER["CONTENT_TYPE"], "multipart/", 10)) {
280
                    $this->http_status("501 not implemented");
281
                    echo "The service does not support mulipart PUT requests";
282
                    return;
283
                }
284
                $options["content_type"] = $_SERVER["CONTENT_TYPE"];
285
            } else {
286
                // default content type if none given
287
                $options["content_type"] = "application/octet-stream";
288
            }
289
290
            /* RFC 2616 2.6 says: "The recipient of the entity MUST NOT
291
               ignore any Content-* (e.g. Content-Range) headers that it
292
               does not understand or implement and MUST return a 501
293
               (Not Implemented) response in such cases."
294
            */
295
            foreach ($_SERVER as $key => $val) {
296
                if (strncmp($key, "HTTP_CONTENT", 11)) continue;
297
                switch ($key) {
298
                case 'HTTP_CONTENT_ENCODING': // RFC 2616 14.11
299
                    // TODO support this if ext/zlib filters are available
300
                    $this->http_status("501 not implemented");
301
                    echo "The service does not support '$val' content encoding";
302
                    return;
303
304
                case 'HTTP_CONTENT_LANGUAGE': // RFC 2616 14.12
305
                    // we assume it is not critical if this one is ignored
306
                    // in the actual PUT implementation ...
307
                    $options["content_language"] = $val;
308
                    break;
309
310
                case 'HTTP_CONTENT_LOCATION': // RFC 2616 14.14
311
                    /* The meaning of the Content-Location header in PUT
312
                       or POST requests is undefined; servers are free
313
                       to ignore it in those cases. */
314
                    break;
315
316
                case 'HTTP_CONTENT_RANGE':    // RFC 2616 14.16
317
                    // single byte range requests are NOT supported
318
                    // the header format is also specified in RFC 2616 14.16
319
                    // TODO we have to ensure that implementations support this or send 501 instead
320
                        $this->http_status("400 bad request");
321
                        echo "The service does only support single byte ranges";
322
                        return;
323
324
                case 'HTTP_CONTENT_MD5':      // RFC 2616 14.15
325
                    // TODO: maybe we can just pretend here?
326
                    $this->http_status("501 not implemented");
327
                    echo "The service does not support content MD5 checksum verification";
328
                    return;
329
330
				case 'HTTP_CONTENT_LENGTH': // RFC 2616 14.14
331
                    /* The meaning of the Content-Location header in PUT
332
                       or POST requests is undefined; servers are free
333
                       to ignore it in those cases. */
334
                    break;
335
336
                default:
337
                    // any other unknown Content-* headers
338
                    $this->http_status("501 not implemented");
339
                    echo "The service does not support '$key'";
340
                    return;
341
                }
342
            }
343
344
            // DO AUTHORIZATION for publishing Free/busy to Sugar:
345
            if ( empty($this->publish_key) ||
346
                $this->publish_key != $this->user_focus->getPreference('calendar_publish_key' ))
347
            {
348
                    $this->http_status("401 not authorized");
349
                    return;
350
351
            }
352
353
            // retrieve
354
            $arr = array('user_id'=>$this->user_focus->id,'type'=>'vfb','source'=>$this->source);
355
            $this->vcal_focus->retrieve_by_string_fields($arr);
356
357
            $isUpdate  = false;
358
359
            if ( ! empty($this->vcal_focus->user_id ) &&
360
                $this->vcal_focus->user_id != -1 )
361
            {
362
              $isUpdate  = true;
363
            }
364
365
            // open input stream
366
            $options["stream"] = fopen("php://input", "r");
367
            $content = '';
368
369
            // read in input stream
370
            while (!feof($options["stream"]))
371
            {
372
               $content .= fread($options["stream"], 4096);
373
            }
374
375
            // set freebusy members and save
376
            $this->vcal_focus->content = $content;
377
            $this->vcal_focus->type = 'vfb';
378
            $this->vcal_focus->source = $this->source;
379
            $focus->date_modified = null;
380
            $this->vcal_focus->user_id = $this->user_focus->id;
381
            $this->vcal_focus->save();
382
383
            if ( $isUpdate )
384
            {
385
               $this->http_status("204 No Content");
386
            } else {
387
               $this->http_status("201 Created");
388
            }
389
        }
390
391
        /**
392
         * PUT method handler
393
         *
394
         * @param  array  parameter passing array
395
         * @return bool   true on success
396
         */
397
        function PUT(&$options)
398
        {
399
400
        }
401
402
        /**
403
         * LOCK method handler
404
         *
405
         * @param  array  general parameter passing array
406
         * @return bool   true on success
407
         */
408
        function lock(&$options)
409
        {
410
411
            $options["timeout"] = time()+300; // 5min. hardcoded
412
            return true;
413
        }
414
415
        /**
416
         * UNLOCK method handler
417
         *
418
         * @param  array  general parameter passing array
419
         * @return bool   true on success
420
         */
421
        function unlock(&$options)
422
        {
423
424
            return "200 OK";
425
        }
426
427
428
        /**
429
         * checkLock() helper
430
         *
431
         * @param  string resource path to check for locks
432
         * @return bool   true on success
433
         */
434
        function checkLock($path)
435
        {
436
            return false;
437
438
        }
439
440
    }
441
442
443
?>
444