Failed Conditions
Branch master (215e8c)
by Johannes
04:26
created

edittopic.php ➔ add_image()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 42
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 27
nc 5
nop 1
dl 0
loc 42
rs 6.7272
c 0
b 0
f 0
1
<?php
1 ignored issue
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 159 and the first side effect is on line 3.

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
include_once '../../includes/easyparliament/init.php';
4
5
$this_page = 'admin_edittopic';
6
7
$topics = new \MySociety\TheyWorkForYou\Topics();
8
9
$PAGE->page_start();
10
$PAGE->stripe_start();
11
12
$slug = get_http_var('id');
13
if ($slug) {
14
  $topic = $topics->getTopic($slug);
15
} else {
16
  $topic = new \MySociety\TheyWorkForYou\Topic();
17
}
18
19
$action = get_http_var('action');
20
switch ($action) {
21
    case 'add':
22
      $success = add_topic($topic);
23
      break;
24
    case 'update':
25
      $success = update_topic($topic);
26
      break;
27
    case 'setimage':
28
      $success = add_image($topic);
29
      break;
30
    case 'addcontent':
31
      $success = add_content($topic);
32
      break;
33
    case 'deletecontent':
34
      $success = delete_content($topic);
35
      break;
36
    case 'addpolicysets':
37
      $success = add_policy_sets($topic);
38
      break;
39
    case 'addpolicies':
40
      $success = add_policies($topic);
41
      break;
42
    default:
43
      $success = NULL;
44
}
45
46
if (!is_null($success)) {
47
    if ($success) {
48
        $out = "<h4>Update successful</h4>";
49
    } else {
50
        $out = "<h4>Failed to update Topic</h4>";
51
    }
52
    print $out;
53
}
54
55
?>
56
57
  <h2><?= $topic->title() ?></h2>
58
    <div id="adminbody" class="topic">
59
        <form action="edittopic.php" method="post">
60
          <input type="hidden" name="action" value="update">
61
          <input type="hidden" name="id" value="<?= $topic->slug() ?>">
62
          <label for="title">Title</label> <input id="title" name="title" value="<?= $topic->title() ?>">
63
64
          <label for="search_string">Search string</label> <input id="search_string" name="search_string" value="<?= $topic->search_string() ?>">
65
66
          <p>
67
           <input type="checkbox" value="1" id="front_page" name="front_page" <?= $topic->onFrontPage() ? 'checked' : '' ?>> <label class="inline" for="front_page">Show on Front Page</label>
68
          </p>
69
70
          <label for="description">Description</label>
71
          <textarea id="description" rows="5" name="description"><?= $topic->description() ?></textarea>
72
73
          <p>
74
          <input type="submit" value="Save">
75
          </p>
76
        </form>
77
78
        <h3>Set Image</h3>
79
        <form enctype="multipart/form-data" action="edittopic.php" method="post">
80
          <input type="hidden" name="action" value="setimage">
81
          <input type="hidden" name="id" value="<?= $topic->slug() ?>">
82
          <?php if ($topic->image()) { ?>
83
            <p>
84
              <img src="<?= $topic->image_url() ?>" height="100">
85
            </p>
86
87
            <p>
88
              <input type="submit" value="Delete">
89
            </p>
90
          <?php } ?>
91
          <input type="file" value="Image" name="topic_image" id="image">
92
          <p>
93
          <input type="submit" value="Update">
94
          </p>
95
        </form>
96
97
98
        <h3>Related Content</h3>
99
        <ul>
100
          <?php foreach ($topic->getContent() as $content) { ?>
101
          <li><a href="<?= $content['href'] ?>"><?= $content['title'] ?></a>
102
              <form class="inline" action="edittopic.php" method="post">
103
                  <input type="hidden" name="action" value="deletecontent">
104
                  <input type="hidden" name="id" value="<?= $topic->slug() ?>">
105
                  <input type="hidden" name="content" value="<?= $content['id'] ?>">
106
                  <input type="submit" value="Delete">
107
              </form>
108
          </li>
109
          <?php } ?>
110
        </ul>
111
112
        <form action="edittopic.php" method="post">
113
            <input type="hidden" name="action" value="addcontent">
114
            <input type="hidden" name="id" value="<?= $topic->slug() ?>">
115
            <p>
116
            <label for="content_url">URL</label> <input id="content_url" name="content_url">
117
            <input type="submit" value="Add">
118
            </p>
119
        </form>
120
121
        <h3>Related Policy Sets</h3>
122
        <form action="edittopic.php" method="post">
123
            <input type="hidden" name="action" value="addpolicysets">
124
            <input type="hidden" name="id" value="<?= $topic->slug() ?>">
125
            <select name="sets[]" multiple>
126
              <option value="">None</option>
127
            <?php
128
              $policies = new \MySociety\TheyWorkForYou\Policies;
129
              $set_descriptions = $policies->getSetDescriptions();
130
              $related_sets = $topic->getPolicySets();
131
              foreach ($set_descriptions as $set => $description) { ?>
132
              <option value="<?= $set ?>" <?= in_array($set, $related_sets) ? 'selected' : '' ?>><?= $description ?></option>
133
            <?php } ?>
134
            <input type="submit" value="Update">
135
            </select>
136
        </form>
137
138
        <h3>Related Policies</h3>
139
140
        <form action="edittopic.php" method="post">
141
            <input type="hidden" name="action" value="addpolicies">
142
            <input type="hidden" name="id" value="<?= $topic->slug() ?>">
143
            <select name="policies[]" multiple>
144
              <option value="">None</option>
145
            <?php
146
              $policies = new \MySociety\TheyWorkForYou\Policies;
147
              $all_policies = $policies->getPolicies();
148
              $related_policies = $topic->getPolicies();
149
              foreach ($all_policies as $number => $description) { ?>
150
              <option value="<?= $number ?>" <?= in_array($number, $related_policies) ? 'selected' : '' ?>><?= $description ?></option>
151
            <?php } ?>
152
153
            </select>
154
            <input type="submit" value="Update">
155
        </form>
156
    </div>
157
<?php
158
159
function add_topic($topic) {
160
    $topic->set_title(get_http_var('title'));
161
    $topic->set_description(get_http_var('description'));
162
163
    $slug = strtolower(preg_replace('/ /', '-', $topic->title()));
164
    $slug = preg_replace('/^the-/', '', $slug);
165
    $topic->set_slug($slug);
166
    return $topic->save();
167
}
168
169
function update_topic($topic) {
170
    $topic->set_title(get_http_var('title'));
171
    $topic->set_description(get_http_var('description'));
172
    $topic->set_front_page(get_http_var('front_page'));
173
    $topic->set_search_string(get_http_var('search_string'));
174
    return $topic->save();
175
}
176
177
function add_content($topic) {
178
    $gid = \MySociety\TheyWorkForYou\Utility\Hansard::get_gid_from_url(get_http_var('content_url'));
179
180
    return $topic->addContent($gid);
181
}
182
183
function add_image($topic) {
0 ignored issues
show
Coding Style introduced by
add_image uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
184
    // do some sanity checks on the file
185
    $file_info = $_FILES['topic_image'];
186
187
    if (
188
        !isset($file_info['error']) ||
189
        is_array($file_info['error']) ||
190
        $file_info['error'] != UPLOAD_ERR_OK
191
    ) {
192
        return false;
193
    }
194
195
    $finfo = new finfo(FILEINFO_MIME_TYPE);
196
    $mime_info = $finfo->file($file_info['tmp_name']);
197
    $ext = array_search(
198
        $mime_info,
199
        array(
200
            'jpg' => 'image/jpeg',
201
            'png' => 'image/png'
202
        ),
203
        true
204
    );
205
206
    if ($ext === false) {
207
        return false;
208
    }
209
210
    $outfile = sprintf('%s.%s', $topic->slug(), $ext);
211
    $topic->set_image($outfile);
212
    try {
213
        $image_saved = move_uploaded_file(
214
            $file_info['tmp_name'],
215
            $topic->image_path()
216
        );
217
     } catch (ErrorException $e) {
218
        return false;
219
     }
220
221
    if ($image_saved) {
222
        return $topic->save();
223
    }
224
}
225
226
function delete_content($topic) {
227
    $epobject_id = get_http_var('content');
228
229
    return $topic->deleteContent($epobject_id);
230
}
231
232
function add_policy_sets($topic) {
233
    $sets = get_http_var('sets');
234
235
    if ($sets[0] == '' && count($sets) == 1) {
236
        $sets = array();
237
    }
238
239
    return $topic->addPolicySets($sets);
240
}
241
242
function add_policies($topic) {
243
    $policies = get_http_var('policies');
244
245
    if ($sets[0] == '' && count($sets) == 1) {
0 ignored issues
show
Bug introduced by
The variable $sets seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
246
        $sets = array();
0 ignored issues
show
Unused Code introduced by
$sets is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
247
    }
248
249
    return $topic->addPolicies($policies);
250
}
251
252
$menu = $PAGE->admin_menu();
253
254
$PAGE->stripe_end(array(
255
    array(
256
        'type'    => 'html',
257
        'content' => $menu
258
    )
259
));
260
261
$PAGE->page_end();
262