Completed
Push — tp71 ( 6d1cb0 )
by Richard
08:06
created

XoopsApi::newPost()   F

Complexity

Conditions 20
Paths 677

Size

Total Lines 90
Code Lines 68

Duplication

Lines 9
Ratio 10 %

Code Coverage

Tests 0
CRAP Score 420

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 9
loc 90
ccs 0
cts 57
cp 0
rs 2.3199
cc 20
eloc 68
nc 677
nop 0
crap 420

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/*
3
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
*/
11
12
use Xoops\Core\Kernel\Handlers\XoopsModule;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, XoopsModule.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
13
14
/**
15
 * @copyright       XOOPS Project (http://xoops.org)
16
 * @license         GNU GPL 2 (http://www.gnu.org/licenses/gpl-2.0.html)
17
 * @package         class
18
 * @subpackage      xml
19
 * @since           1.0.0
20
 * @author          Kazumi Ono (AKA onokazu)
21
 * @version         $Id $
22
 */
23
class XoopsApi extends XoopsXmlRpcApi
24
{
25
    /**
26
     * @param array $params
27
     * @param XoopsXmlRpcResponse $response
28
     * @param XoopsModule $module
29
     */
30 2
    public function __construct(array &$params, XoopsXmlRpcResponse $response, XoopsModule $module)
31
    {
32 2
        parent::__construct($params, $response, $module);
33 2
    }
34
35
    /**
36
     * @return void
37
     */
38
    public function newPost()
39
    {
40
        if (!$this->_checkUser($this->params[1], $this->params[2])) {
41
            $this->response->add(new XoopsXmlRpcFault(104));
42
        } else {
43
            if (!$fields = $this->_getPostFields(null, $this->params[0])) {
44
                $this->response->add(new XoopsXmlRpcFault(106));
45
            } else {
46
                $missing = array();
47
                foreach ($fields as $tag => $detail) {
48
                    if (!isset($this->params[3][$tag])) {
49
                        $data = $this->_getTagCdata($this->params[3]['xoops_text'], $tag, true);
50
                        if (trim($data) == '') {
51
                            if ($detail['required']) {
52
                                $missing[] = $tag;
53
                            }
54
                        } else {
55
                            $post[$tag] = $data;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$post was never initialized. Although not strictly required by PHP, it is generally a good practice to add $post = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
56
                        }
57
                    } else {
58
                        $post[$tag] = $this->params[3][$tag];
0 ignored issues
show
Bug introduced by
The variable $post does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
59
                    }
60
                }
61
                if (count($missing) > 0) {
62
                    $msg = '';
63
                    foreach ($missing as $m) {
64
                        $msg .= '<' . $m . '> ';
65
                    }
66
                    $this->response->add(new XoopsXmlRpcFault(109, $msg));
67
                } else {
68
                    // will be removed... don't worry if this looks bad
69 View Code Duplication
                    if (!XoopsLoad::loadFile(\XoopsBaseConfig::get('root-path').'/modules/news/class/class.newsstory.php', true)) {
70
                        $this->response->add(new XoopsXmlRpcFault(103));
71
                        return;
72
                    }
73
                    $story = new NewsStory();
74
                    $error = false;
75
                    if ((int)$this->params[4] > 0) {
76
                        if (!$this->_checkAdmin()) {
77
                            // non admin users cannot publish
78
                            $error = true;
79
                            $this->response->add(new XoopsXmlRpcFault(111));
80
                        } else {
81
                            $story->setType('admin');
82
                            $story->setApproved(true);
83
                            $story->setPublished(time());
84
                        }
85
                    } else {
86
                        if (!$this->_checkAdmin()) {
87
                            $story->setType('user');
88
                        } else {
89
                            $story->setType('admin');
90
                        }
91
                    }
92
                    if (!$error) {
93
                        if (isset($post['categories']) && !empty($post['categories'][0])) {
94
                            $story->setTopicId((int)($post['categories'][0]['categoryId']));
95
                        } else {
96
                            $story->setTopicId(1);
97
                        }
98
                        $story->setTitle(addslashes(trim($post['title'])));
99
                        if (isset($post['moretext'])) {
100
                            $story->setBodytext(addslashes(trim($post['moretext'])));
101
                        }
102 View Code Duplication
                        if (!isset($post['hometext'])) {
103
                            $story->setHometext(addslashes(trim($this->params[3]['xoops_text'])));
104
                        } else {
105
                            $story->setHometext(addslashes(trim($post['hometext'])));
106
                        }
107
                        $story->setUid($this->user->getVar('uid'));
108
                        $story->setHostname($_SERVER['REMOTE_ADDR']);
109
                        if (!$this->_checkAdmin()) {
110
                            $story->setNohtml(1);
111
                        } else {
112
                            $story->setNohtml(0);
113
                        }
114
                        $story->setNosmiley(0);
115
                        $story->setNotifyPub(1);
116
                        $story->setTopicalign('R');
117
                        $ret = $story->store();
118
                        if (!$ret) {
119
                            $this->response->add(new XoopsXmlRpcFault(106));
120
                        } else {
121
                            $this->response->add(new XoopsXmlRpcString($ret));
122
                        }
123
                    }
124
                }
125
            }
126
        }
127
    }
128
129
    public function editPost()
130
    {
131
        if (!$this->_checkUser($this->params[1], $this->params[2])) {
132
            $this->response->add(new XoopsXmlRpcFault(104));
133
        } else {
134
            if (!$fields = $this->_getPostFields($this->params[0])) {
135
            } else {
136
                $missing = array();
137
                foreach ($fields as $tag => $detail) {
138
                    if (!isset($this->params[3][$tag])) {
139
                        $data = $this->_getTagCdata($this->params[3]['xoops_text'], $tag, true);
140
                        if (trim($data) == '') {
141
                            if ($detail['required']) {
142
                                $missing[] = $tag;
143
                            }
144
                        } else {
145
                            $post[$tag] = $data;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$post was never initialized. Although not strictly required by PHP, it is generally a good practice to add $post = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
146
                        }
147
                    } else {
148
                        $post[$tag] = $this->params[3][$tag];
0 ignored issues
show
Bug introduced by
The variable $post does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
149
                    }
150
                }
151
                if (count($missing) > 0) {
152
                    $msg = '';
153
                    foreach ($missing as $m) {
154
                        $msg .= '<' . $m . '> ';
155
                    }
156
                    $this->response->add(new XoopsXmlRpcFault(109, $msg));
157
                } else {
158
                    // will be removed... don't worry if this looks bad
159 View Code Duplication
                    if (!XoopsLoad::loadFile(\XoopsBaseConfig::get('root-path').'/modules/news/class/class.newsstory.php', true)) {
160
                        $this->response->add(new XoopsXmlRpcFault(103));
161
                        return;
162
                    }
163
                    $story = new NewsStory($this->params[0]);
164
                    $storyid = $story->storyid();
165
                    if (empty($storyid)) {
166
                        $this->response->add(new XoopsXmlRpcFault(106));
167
                    } elseif (!$this->_checkAdmin()) {
168
                        $this->response->add(new XoopsXmlRpcFault(111));
169
                    } else {
170
                        $story->setTitle(addslashes(trim($post['title'])));
171
                        if (isset($post['moretext'])) {
172
                            $story->setBodytext(addslashes(trim($post['moretext'])));
173
                        }
174 View Code Duplication
                        if (!isset($post['hometext'])) {
175
                            $story->setHometext(addslashes(trim($this->params[3]['xoops_text'])));
176
                        } else {
177
                            $story->setHometext(addslashes(trim($post['hometext'])));
178
                        }
179
                        if ($this->params[4]) {
180
                            $story->setApproved(true);
181
                            $story->setPublished(time());
182
                        }
183
                        $story->setTopicalign('R');
184 View Code Duplication
                        if (!$story->store()) {
185
                            $this->response->add(new XoopsXmlRpcFault(106));
186
                        } else {
187
                            $this->response->add(new XoopsXmlRpcBoolean(true));
188
                        }
189
                    }
190
                }
191
            }
192
        }
193
    }
194
195
    public function deletePost()
196
    {
197
        if (!$this->_checkUser($this->params[1], $this->params[2])) {
198
            $this->response->add(new XoopsXmlRpcFault(104));
199
        } else {
200
            if (!$this->_checkAdmin()) {
201
                $this->response->add(new XoopsXmlRpcFault(111));
202
            } else {
203
                // will be removed... don't worry if this looks bad
204 View Code Duplication
                if (!XoopsLoad::loadFile(\XoopsBaseConfig::get('root-path').'/modules/news/class/class.newsstory.php', true)) {
205
                    $this->response->add(new XoopsXmlRpcFault(103));
206
                    return;
207
                }
208
                $story = new NewsStory($this->params[0]);
209 View Code Duplication
                if (!$story->delete()) {
210
                    $this->response->add(new XoopsXmlRpcFault(106));
211
                } else {
212
                    $this->response->add(new XoopsXmlRpcBoolean(true));
213
                }
214
            }
215
        }
216
    }
217
218
    // currently returns the same struct as in metaWeblogApi
219
    /**
220
     * @param bool $respond
221
     *
222
     * @return array
223
     */
224
    public function &getPost($respond = true)
225
    {
226
        if (!$this->_checkUser($this->params[1], $this->params[2])) {
227
            $this->response->add(new XoopsXmlRpcFault(104));
228
        } else {
229
            // will be removed... don't worry if this looks bad
230 View Code Duplication
            if (!XoopsLoad::loadFile(\XoopsBaseConfig::get('root-path').'/modules/news/class/class.newsstory.php', true)) {
231
                $this->response->add(new XoopsXmlRpcFault(103));
232
                return;
233
            }
234
            $story = new NewsStory($this->params[0]);
235
            $ret = array(
236
                'uid'       => $story->uid(),
237
                'published' => $story->published(),
238
                'storyid'   => $story->storyId(),
239
                'title'     => $story->title('Edit'),
240
                'hometext'  => $story->hometext('Edit'),
241
                'moretext'  => $story->bodytext('Edit')
242
            );
243
            if (!$respond) {
244
                return $ret;
245
            } else {
246
                if (!$ret) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ret of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
247
                    $this->response->add(new XoopsXmlRpcFault(106));
248
                } else {
249
                    $struct = new XoopsXmlRpcStruct();
250
                    $content = '';
251 View Code Duplication
                    foreach ($ret as $key => $value) {
252
                        switch($key) {
253
                            case 'uid':
254
                                $struct->add('userid', new XoopsXmlRpcString($value));
255
                                break;
256
                            case 'published':
257
                                $struct->add('dateCreated', new XoopsXmlRpcDatetime($value));
258
                                break;
259
                            case 'storyid':
260
                                $struct->add('postid', new XoopsXmlRpcString($value));
261
                                $struct->add('link', new XoopsXmlRpcString(\XoopsBaseConfig::get('url') . '/modules/news/article.php?item_id=' . $value));
262
                                $struct->add('permaLink', new XoopsXmlRpcString(\XoopsBaseConfig::get('url') . '/modules/news/article.php?item_id=' . $value));
263
                                break;
264
                            case 'title':
265
                                $struct->add('title', new XoopsXmlRpcString($value));
266
                                break;
267
                            default :
268
                                $content .= '<' . $key . '>' . trim($value) . '</' . $key . '>';
269
                                break;
270
                        }
271
                    }
272
                    $struct->add('description', new XoopsXmlRpcString($content));
273
                    $this->response->add($struct);
274
                }
275
            }
276
        }
277
        return null;
278
    }
279
280
    /**
281
     * @param bool $respond
282
     *
283
     * @return array
284
     */
285
    public function &getRecentPosts($respond = true)
286
    {
287
        if (!$this->_checkUser($this->params[1], $this->params[2])) {
288
            $this->response->add(new XoopsXmlRpcFault(104));
289
        } else {
290 View Code Duplication
            if (!XoopsLoad::loadFile(\XoopsBaseConfig::get('root-path').'/modules/news/class/class.newsstory.php', true)) {
291
                $this->response->add(new XoopsXmlRpcFault(103));
292
                return;
293
            }
294
            if (isset($this->params[4]) && (int)($this->params[4]) > 0) {
295
                $stories = NewsStory::getAllPublished((int)($this->params[3]), 0, $this->params[4]);
296
            } else {
297
                $stories = NewsStory::getAllPublished((int)($this->params[3]));
298
            }
299
            $scount = count($stories);
300
            $ret = array();
301
            for ($i = 0; $i < $scount; ++$i) {
302
                $ret[] = array(
303
                    'uid'       => $stories[$i]->uid(),
304
                    'published' => $stories[$i]->published(),
305
                    'storyid'   => $stories[$i]->storyId(),
306
                    'title'     => $stories[$i]->title('Edit'),
307
                    'hometext'  => $stories[$i]->hometext('Edit'),
308
                    'moretext'  => $stories[$i]->bodytext('Edit')
309
                );
310
            }
311
            if (!$respond) {
312
                return $ret;
313
            } else {
314
                if (count($ret) == 0) {
315
                    $this->response->add(new XoopsXmlRpcFault(106, 'Found 0 Entries'));
316
                } else {
317
                    $arr = new XoopsXmlRpcArray();
318
                    $count = count($ret);
319
                    for ($i = 0; $i < $count; ++$i) {
320
                        $struct = new XoopsXmlRpcStruct();
321
                        $content = '';
322 View Code Duplication
                        foreach($ret[$i] as $key => $value) {
323
                            switch($key) {
324
                                case 'uid':
325
                                    $struct->add('userid', new XoopsXmlRpcString($value));
326
                                    break;
327
                                case 'published':
328
                                    $struct->add('dateCreated', new XoopsXmlRpcDatetime($value));
329
                                    break;
330
                                case 'storyid':
331
                                    $struct->add('postid', new XoopsXmlRpcString($value));
332
                                    $struct->add('link', new XoopsXmlRpcString(\XoopsBaseConfig::get('url') . '/modules/news/article.php?item_id=' . $value));
333
                                    $struct->add('permaLink', new XoopsXmlRpcString(\XoopsBaseConfig::get('url') . '/modules/news/article.php?item_id=' . $value));
334
                                    break;
335
                                case 'title':
336
                                    $struct->add('title', new XoopsXmlRpcString($value));
337
                                    break;
338
                                default :
339
                                    $content .= '<' . $key . '>' . trim($value) . '</' . $key . '>';
340
                                    break;
341
                            }
342
                        }
343
                        $struct->add('description', new XoopsXmlRpcString($content));
344
                        $arr->add($struct);
345
                        unset($struct);
346
                    }
347
                    $this->response->add($arr);
348
                }
349
            }
350
        }
351
        return null;
352
    }
353
354
    function getCategories($respond=true)
355
    {
356
        global $xoopsDB;
357
        if (!$this->_checkUser($this->params[1], $this->params[2])) {
358
            $this->response->add(new XoopsXmlRpcFault(104));
359
        } else {
360 View Code Duplication
            if (!XoopsLoad::loadFile(\XoopsBaseConfig::get('root-path').'/class/xoopstopic.php', true)) {
361
                $this->response->add(new XoopsXmlRpcFault(103));
362
                return;
363
            }
364
            //$this->db = xoopsDB;
365
            $xt = new XoopsTopic($xoopsDB->prefix('topics'));
366
            $ret = $xt->getTopicsList();
367
            if (!$respond) {
368
                return $ret;
369
            } else {
370
                if (count($ret) == 0) {
371
                    $this->response->add(new XoopsXmlRpcFault(106, 'Found 0 Entries'));
372 View Code Duplication
                } else {
373
                    $arr = new XoopsXmlRpcArray();
374
                    foreach ($ret as $topic_id => $topic_vars) {
375
                        $struct = new XoopsXmlRpcStruct();
376
                        $struct->add('categoryId', new XoopsXmlRpcString($topic_id));
377
                        $struct->add('categoryName', new XoopsXmlRpcString($topic_vars['title']));
378
                        $struct->add('categoryPid', new XoopsXmlRpcString($topic_vars['pid']));
379
                        $arr->add($struct);
380
                        unset($struct);
381
                    }
382
                    $this->response->add($arr);
383
                }
384
            }
385
        }
386
        return null;
387
    }
388
}
389