Completed
Push — master ( 484dcf...d1b073 )
by Michael
14s
created

issues.php ➔ xoopspartnersGetHeaderFromArray()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 6
nop 3
dl 0
loc 10
rs 9.2
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 39 and the first side effect is on line 22.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/*
3
 You may not change or alter any portion of this comment or credits of
4
 supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit
6
 authors.
7
8
 This program is distributed in the hope that it will be useful, but
9
 WITHOUT ANY WARRANTY; without even the implied warranty of
10
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 */
12
/**
13
 * Module: xoopsPartners
14
 *
15
 * @package         module\xoopspartners\include
16
 * @author          ZySpec <[email protected]>
17
 * @copyright       http://xoops.org 2001-2016 XOOPS Project
18
 * @license         http://www.fsf.org/copyleft/gpl.html GNU public license
19
 * @since           1.13
20
 */
21
22
$moduleDirName = basename(dirname(__DIR__));
23
$xpHelper = \Xmf\Module\Helper::getHelper($modueDirName);
24
$xpHelper->loadLanguage('admin');
25
//include_once dirname(__DIR__) . "/language/english/admin.php"; // messages will be in english
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
26
27
session_start();
28
29
global $hdrs;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
30
$hdrs = array();
31
/**
32
 * Function to put HTTP headers in an array
33
 *
34
 * @param unknown $curl
35
 * @param string $hdrLine
36
 *
37
 * @return int length of header line put into array
38
 */
39
function xoopspartnersHandleHeaderLine($curl, $hdrLine) {
0 ignored issues
show
Unused Code introduced by
The parameter $curl is not used and could be removed.

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

Loading history...
40
    global $hdrs;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
41
    $hdrs[] = trim($hdrLine);
42
    return strlen($hdrLine);
43
}
44
45
/**
46
 *
47
 * @param string $hdr
48
 * @param array $hdrs
0 ignored issues
show
Bug introduced by
There is no parameter named $hdrs. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
49
 *
50
 * @return array|false array($hdr=>value) or false if not found
0 ignored issues
show
Documentation introduced by
Should the return type not be array<string,string>|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
51
 */
52
function xoopspartnersGetHeaderFromArray($hdr, $hdrArray, $asArray = false) {
53
    $val = '';
54
    foreach ($hdrArray as $thisHdr) {
55
        if (preg_match("/^{$hdr}/i", $thisHdr)) {
56
            $val = substr($thisHdr, strlen($hdr));
57
            break;
58
        }
59
    }
60
    return (bool)$asArray ? array($hdr => trim($val)) : trim($val);
61
}
62
63
$serviceUrl   = "https://github.com/XoopsModules25x/{$moduleDirName}/issues?state=open";
64
$sessPrefix   = "{$moduleDirName}_";
65
$err          = '';
66
$sKeyEtag     = "{$sessPrefix}github_etag";
67
$sKeyHdrSize  = "{$sessPrefix}github_hdr_size";
68
$sKeyResponse = "{$sessPrefix}github_curl_response";
69
$sKeyArray    = array($sKeyEtag, $sKeyHdrSize, $sKeyResponse);
70
71
$cachedEtag = (isset($_SESSION[$sKeyEtag])) ? base64_decode(unserialize($_SESSION[$sKeyEtag])) : false;
72
if ($cachedEtag) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $cachedEtag of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
73
    // found the session var so check to see if anything's changed since last time we checked
74
    $curl = curl_init($serviceUrl);
75
    curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => true,
76
        CURLOPT_HEADER      => true,
77
        CURLOPT_VERBOSE     => true,
78
        CURLOPT_TIMEOUT     => 5,
79
        CURLOPT_HTTPGET     => true,
80
        CURLOPT_USERAGENT   => "XOOPS-{$moduleDirName}",
81
        CURLOPT_HTTPHEADER  => array('Content-type:application/json',
82
                                     'If-None-Match: ' . $cachedEtag),
83
        CURLINFO_HEADER_OUT => true,
84
        CURLOPT_HEADERFUNCTION => "xoopspartnersHandleHeaderLine")
85
    );
86
    // execute the session
87
    $curl_response = curl_exec($curl);
88
    // get the header size and finish off the session
89
    $hdrSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
90
    curl_close($curl);
91
92
    $status = xoopspartnersGetHeaderFromArray('Status: ', $hdrs);
93
    if (preg_match('/^304 Not Modified/', $status)) {
94
        // hasn't been modified so get response & header size from session
95
        $curl_response = isset($_SESSION[$sKeyResponse])
96
                               ? base64_decode(unserialize($_SESSION[$sKeyResponse]))
97
                               : array();
98
        $hdrSize       = isset($_SESSION[$sKeyHdrSize])
99
                               ? unserialize($_SESSION[$sKeyHdrSize])
100
                               : 0;
101 View Code Duplication
    } elseif (preg_match('/^200 OK/', $status)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
102
        // ok - request new info
103
        $hdrs = array(); //reset the header array for new curl op
104
        $curl = curl_init($serviceUrl);
105
        curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => true,
106
            CURLOPT_HEADER         => true,
107
            CURLOPT_VERBOSE        => true,
108
            CURLOPT_TIMEOUT        => 5,
109
            CURLOPT_HTTPGET        => true,
110
            CURLOPT_USERAGENT      => "XOOPS-{$moduleDirName}",
111
            CURLOPT_HTTPHEADER     => array('Content-type:application/json'),
112
            CURLOPT_HEADERFUNCTION => 'xoopspartnersHandleHeaderLine')
113
        );
114
        // execute the session
115
        $curl_response = curl_exec($curl);
116
        // get the header size and finish off the session
117
        $hdrSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
118
        curl_close($curl);
119
120
        $hdrEtag = xoopspartnersGetHeaderFromArray('Etag: ', $hdrs);
121
        $_SESSION[$sKeyEtag] = serialize(base64_encode($hdrEtag));
122
        $_SESSION[$sKeyHdrSize] = serialize((int)$hdrSize);
123
        $_SESSION[$sKeyResponse] = serialize(base64_encode($curl_response));
124
    } elseif (preg_match('/^403 Forbidden/', $status)) {
125
        // probably exceeded rate limit
126
        $responseArray = explode('\n', $curl_response);
127
        $msgEle        = array_search('message: ', $responseArray);
128
        if (false !== $msgEle) {
129
            //found the error message so set it
130
            $err = substr($responseArray[$msgEle], 8); //get the message
131
        } else {
132
            // couldn't find error message, but something went wrong
133
            // clear session vars
134
            foreach ($sKeyArray as $key) {
135
                $_SESSION[$key] = null;
136
                unset($_SESSION[$key]);
137
            }
138
            $err = _AM_XOOPSPARTNERS_ISSUES_ERR_UNKNOWN;
139
        }
140
    } else {
141
        // unknown error condition - display message
142
        // clear session vars
143
        foreach ($sKeyArray as $key) {
144
            $_SESSION[$key] = null;
145
            unset($_SESSION[$key]);
146
        }
147
        $err = _AM_XOOPSPARTNERS_ISSUES_STATUS_UNKNOWN;
148
    }
149 View Code Duplication
} else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
150
    // nothing in session so request new info
151
    $hdrs = array();
152
    $curl = curl_init($serviceUrl);
153
    curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => true,
154
        CURLOPT_HEADER         => true,
155
        CURLOPT_VERBOSE        => true,
156
        CURLOPT_TIMEOUT        => 5,
157
        CURLOPT_HTTPGET        => true,
158
        CURLOPT_USERAGENT      => "XOOPS-{$moduleDirName}",
159
        CURLOPT_HTTPHEADER     => array('Content-type:application/json'),
160
        CURLOPT_HEADERFUNCTION => 'xoopspartnersHandleHeaderLine')
161
    );
162
    // execute the session
163
    $curl_response = curl_exec($curl);
164
    // get the header size and finish off the session
165
    $hdrSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
166
    curl_close($curl);
167
168
    $hdrEtag = xoopspartnersGetHeaderFromArray('Etag: ', $hdrs);
169
    $_SESSION[$sKeyEtag]     = serialize(base64_encode($hdrEtag));
170
    $_SESSION[$sKeyHdrSize]  = serialize((int)$hdrSize);
171
    $_SESSION[$sKeyResponse] = serialize(base64_encode($curl_response));
172
173
}
174
$hdr        = substr($curl_response, 0, $hdrSize);
175
$rspSize    = strlen($curl_response) - $hdrSize;
176
$response   = substr($curl_response, - $rspSize);
177
$issuesObjs = json_decode($response); //get as objects
178
179
echo "    <br>\n"
180
   . "    <h4 class=\"odd\">" . _AM_XOOPSPARTNERS_ISSUES_OPEN . "</h4>\n"
181
   . "    <p class=\"even\">\n"
182
   . "    <table>\n"
183
   . "      <thead>\n"
184
   . "      <tr>\n"
185
   . "        <th class=\"center width10\">" . _AM_XOOPSPARTNERS_HELP_ISSUE . "</th>\n"
186
   . "        <th class=\"center width10\">" . _AM_XOOPSPARTNERS_HELP_DATE . "</th>\n"
187
   . "        <th class=\"center\">" . _AM_XOOPSPARTNERS_HELP_TITLE . "</th>\n"
188
   . "        <th class=\"center width10\">" . _AM_XOOPSPARTNERS_HELP_SUBMITTER . "</th>\n"
189
   . "      </tr>\n"
190
   . "      </thead>\n"
191
   . "      <tbody>\n";
192
193
$pullReqFound = false;
194
$suffix = '';
195
$cssClass = 'odd';
196
$i = 0;
197
if (!empty($issuesObjs)) {
198
    foreach ($issuesObjs as $issue) {
199
        if (isset($issue->pull_request)) {
200
            /** @internal {uncomment the following line if you don't want to see pull requests as issues}}}*/
201
//            continue; // github counts pull requests as open issues so ignore these
202
203
            $suffix = '*';
204
            $pullReqFound = true;
205
        } else {
206
            $suffix = '';
207
        }
208
209
        $dateTimeObj = DateTime::createFromFormat(DateTime::ISO8601, $issue->created_at);
210
        $dispDate    = $dateTimeObj->format('Y-m-d');
211
        ++$i; // issue count
212
213
        echo "      <tr>\n"
214
           . "        <td class=\"{$cssClass} center\">"
215
           .            "<a href=\"" . $issue->html_url . "\" target=\"_blank\">"
216
           .               (int)$issue->number . "{$suffix}</a>"
217
           .         "</td>\n"
218
           . "        <td class=\"{$cssClass} center\">{$dispDate}</td>\n"
219
           . "        <td class=\"{$cssClass} left\" style=\"padding-left: 2em;\">"
220
           .            htmlspecialchars($issue->title)
221
           .         "</td>\n"
222
           . "        <td class=\"{$cssClass} center\">"
223
           .            "<a href=\"" . htmlspecialchars($issue->user->html_url) . "\" "
224
           .              "target=\"_blank\">" . htmlspecialchars($issue->user->login) . "</a>"
225
           .         "</td>\n"
226
           . "      </tr>\n";
227
        $cssClass = ('odd' == $cssClass) ? 'even' : 'odd';
228
    }
229
}
230
231
if (!empty($err)) {
232
    echo "    <tr><td colspan=\"4\" class=\"{$cssClass} center bold italic\">"
233
       .              htmlspecialchars($err)
234
       .     "</td></tr>\n";
235
} elseif (0 == $i) { // no issues found
236
    echo "    <tr><td colspan=\"4\" class=\"{$cssClass} center bold italic\">"
237
       .        _AM_XOOPSPARTNERS_ISSUES_NONE
238
       .     "</td></tr>\n";
239
}
240
241
if ($pullReqFound) {
242
    echo "    <tfoot>\n"
243
        . "      <tr><td colspan=\"4\" class=\"left italic marg3 foot\">" . _AM_XOOPSPARTNERS_ISSUES_NOTE . "</td></tr>\n"
244
        . "    </tfoot>\n";
245
}
246
echo "    </tbody></table></p>\n";
247