CMS_Page::getTemplate()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 0
cts 2
cp 0
crap 2
1
<?php
2
/**
3
 * Page
4
 *
5
 * Sp�rgsm�l:
6
 * ---------
7
 *
8
 * 0.
9
 * For komplicerede sider kan det m�ske v�re en ide at omskrive get() til
10
 * at den loader specifikke ting, n�r der bliver spurgt efter dem:
11
 *
12
 * Fx kunne stylesheet og navigation v�re en ting, der f�rst skulle loades, hvis der sp�rges.
13
 *
14
 * 1.
15
 * Hvordan f�r vi opbygget URLs fornuftigt - s� vi kan have:
16
 *
17
 * http://www.site.dk/artikler/myteeth/
18
 * http://www.site.dk/produkter/dimser/
19
 * http://www.site.dk/kundensegetbibliotektilsiden/identifier/
20
 *
21
 * Det kan m�ske v�re et eller andet med at smide de enkelte sider
22
 * i nogle kategorier? Men hvad s� med de sider, der ikke er i kategorier?
23
 * Vi skal have et eller andet der g�r det let at s�tte op?
24
 *
25
 * 2.
26
 * Hvis vi skal have en side med artikler med alle n�gleordene, der er brugt
27
 * p� en anden side. Hvordan skal vi s� oprette denne faste side?
28
 *
29
 * 3.
30
 * Der skal knyttes billeder til de enkelte sider, s� man kan bruge billeder p� sidelister.
31
 *
32
 * 4.
33
 * Rettigheder skal v�lges til de enkelte sider. Creative commons.
34
 * Man skal p� siteniveau og templateniveau kunne s�tte ens foretrukne licens.
35
 *
36
 * <!--Creative Commons License-->
37
 * <a rel="license" href="http://creativecommons.org/licenses/by-nd/2.5/dk/">
38
 *      <img alt="Creative Commons License" style="border-width: 0" src="http://creativecommons.org/images/public/somerights20.png"/></a>
39
 *      <br/>Dette v�rk er licensieret under en <a rel="license" href="http://creativecommons.org/licenses/by-nd/2.5/dk/">Creative Commons Navngivelse-Ingen bearbejdelser 2.5 Danmark Licens</a>.
40
 *  <!--/Creative Commons License-->
41
 *  <!-- <rdf:RDF xmlns="http://web.resource.org/cc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
42
 *  <Work rdf:about="">
43
 *      <license rdf:resource="http://creativecommons.org/licenses/by-nd/2.5/dk/" />
44
 *  <dc:type rdf:resource="http://purl.org/dc/dcmitype/Text" />
45
 *  </Work>
46
 *  <License rdf:about="http://creativecommons.org/licenses/by-nd/2.5/dk/"><permits rdf:resource="http://web.resource.org/cc/Reproduction"/><permits rdf:resource="http://web.resource.org/cc/Distribution"/><requires rdf:resource="http://web.resource.org/cc/Notice"/><requires rdf:resource="http://web.resource.org/cc/Attribution"/></License></rdf:RDF> -->
47
 *
48
 * Se eksempel p� /test/update.php
49
 *
50
 * @package Intraface_CMS
51
 * @author  Lars Olesen <[email protected]>
52
 * @since   1.0
53
 * @version 1.0
54
 *
55
 */
56
class CMS_Page extends Intraface_Standard
57
{
58
    public $id;
59
    public $kernel;
60
    public $position;
61
    public $error;
62
    private $dbquery;
63
64
    public $cmssite;
65
    public $template;
66
    public $navigation;
67
    public $message;
68
    public $cc_license;
69
70
    public $value;
71
    public $status = array(
72
        0 => 'draft',
73
        1 => 'published'
74
    );
75
76 7
    public function __construct($cmssite, $id = 0)
77
    {
78 7
        if (!is_object($cmssite)) {
79
             throw new Exception('CMS_Page::__construct needs CMS_Site');
80
        }
81
82 7
        $this->id         = (int)$id;
83 7
        $this->cmssite    =  $cmssite;
84 7
        $this->navigation = new CMS_Navigation($this);
85 7
        $this->template   = new CMS_Template($this->cmssite);
86 7
        $this->kernel     = $this->cmssite->kernel;
87 7
        $this->error      = new Intraface_Error();
88 7
        $this->value['active'] = 1;
89 7
        $this->value['status_key'] = 0;
90
        // $this->dbquery = $this->getDBQuery();
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
91
92
        // get settings
93 7
        $cms_module       = $this->kernel->module('cms');
94 7
        $this->cc_license = $cms_module->getSetting('cc_license');
95
96 7
        if ($this->id > 0) {
97
            $this->load();
98
        }
99 7
    }
100
101
    /**
102
     * Used by Keyword
103
     *
104
     * @see Keyword
105
     *
106
     * @return string
107
     */
108 1
    function identify()
109
    {
110 1
        return 'cms_page';
111
    }
112
113 1
    function getKernel()
114
    {
115 1
        return $this->kernel;
116
    }
117
118 3 View Code Duplication
    function getDBQuery()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
119
    {
120 3
        if ($this->dbquery) {
121 2
            return $this->dbquery;
122
        }
123 3
        return ($this->dbquery = new Intraface_DBQuery($this->kernel, 'cms_page', 'cms_page.intranet_id = '.$this->kernel->intranet->get('id').' AND cms_page.active = 1 AND site_id = ' . $this->cmssite->get('id')));
124
    }
125
126
    /**
127
     * Returns position object
128
     *
129
     * @param object $db database object
130
     * @return object Position
131
     */
132 1
    public function getPosition($db)
133
    {
134 1
        return new Ilib_Position($db, "cms_page", $this->id, "site_id=".$this->cmssite->get('id')." AND active = 1 AND type_key = 1", "position", "id");
0 ignored issues
show
Documentation introduced by
$db is of type object, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
135
    }
136
137
    /**
138
     * returns Template object
139
     *
140
     * @return object Template
141
     */
142
    public function getTemplate()
143
    {
144
        return $this->template;
145
    }
146
147
    function factory($kernel, $type, $value)
148
    {
149
        $gateway = new Intraface_modules_cms_PageGateway($kernel, new DB_Sql);
150
151
        switch ($type) {
152
            case 'id':
153
                return $gateway->findById($value);
154
                /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
155
                $db = new DB_Sql;
156
                $db->query("SELECT id, site_id FROM cms_page WHERE id = " . (int)$value . " AND intranet_id = " . $kernel->intranet->get('id'));
157
158
                if (!$db->nextRecord()) {
159
                    return false;
160
                }
161
                $site = new CMS_Site($kernel, $db->f('site_id'));
162
                $object = new CMS_Page($site, (int)$value);
163
                return $object;
164
                */
165
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
166
            case 'identifier':
167
                $value['identifier'] = safeToDb($value['identifier']);
168
                $value['identifier'] = strip_tags($value['identifier']);
169
                return $gateway->findBySiteIdAndIdentifier($value['site_id'], $value['identifier']);
170
171
                /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
51% 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...
172
                $db = new DB_Sql;
173
174
                if (!empty($value['identifier'])) {
175
                    $db->query("SELECT site_id, id FROM cms_page WHERE identifier = '" . $value['identifier'] . "' AND intranet_id = " . $kernel->intranet->get('id') . " AND active = 1 AND site_id = " . $value['site_id']);
176
                } else {
177
                    // choose the default page - vi skal lige have noget med publish og expire date her ogs�
178
                    $db->query("SELECT site_id, id FROM cms_page WHERE intranet_id = " . $kernel->intranet->get('id') . " AND active = 1 AND status_key = 1 AND site_id = " . $value['site_id'] . " ORDER BY position ASC LIMIT 1");
179
                }
180
                if (!$db->nextRecord()) {
181
                    $db->query("SELECT site_id, id FROM cms_page WHERE id = " . (int)$value['identifier'] . " AND intranet_id = " . $kernel->intranet->get('id') . " AND active = 1 AND site_id = " . $value['site_id']);
182
                    if (!$db->nextRecord()) {
183
                        return false;
184
                    }
185
                }
186
                return new CMS_Page(new CMS_Site($kernel, $db->f('site_id')), $db->f('id'));
187
                */
188
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
189
            default:
190
                throw new Exception('CMS_Page::factory unknown type');
191
                break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
192
        }
193
    }
194
195
196
    /**
197
     * Valideringsfunktion
198
     */
199 1
    function validate($var)
200
    {
201 1
        $validator = new Intraface_Validator($this->error);
202
203 1
        $validator->isString($var['title'], 'Error in title', '', '');
204
205 1
        if (!empty($var['navigation_name'])) {
206 1
            $validator->isString($var['navigation_name'], 'error in navigation_name - has to be a string', '', 'allow_empty');
207 1
        }
208
209 1
        $validator->isString($var['keywords'], 'error in keywords', '', 'allow_empty');
210 1
        $validator->isString($var['description'], 'error in description', '', 'allow_empty');
211
212 1
        $validator->isNumeric($var['allow_comments'], 'error in comments - allowed values are 0 and 1');
213 1
        $validator->isNumeric($var['hidden'], 'error in hidden - allowed values are 0 and 1');
214
215 1 View Code Duplication
        if (!Validate::string($var['identifier'], array('format' => VALIDATE_ALPHA . VALIDATE_NUM . '-_'))) {
216
            $this->error->set('error in unique page address. allowed values are a-z 1-9 _ -');
217
        }
218 1
        if (!$this->isIdentifierAvailable($var['identifier'])) {
219
            $this->error->set('the choosen unique page address is already used for another page, article or news. please select another one');
220
        }
221
222 1
        if ($this->error->isError()) {
223
            return false;
224
        }
225 1
        return true;
226
    }
227
228 1
    function isIdentifierAvailable($identifier)
229
    {
230 1
        $db = new DB_Sql;
231 1
        $db->query("SELECT * FROM cms_page WHERE site_id = " . $this->cmssite->get('id') . " AND identifier = '".$identifier."' AND active = 1 AND id != " . (int)$this->get('id'));
232 1
        return ($db->numRows() == 0);
233
    }
234
235
    /**
236
     * Vi skal have gemt positionen for siden ogs�
237
     *
238
     * Hvis date_publish ikke er sat, skal den bare tage dd.
239
     * Hvis date_expire ikke er sat, hvad skal den s� g�re?
240
     */
241 1
    function save($var)
242
    {
243 1
        $var = safeToDb($var);
244 1
        if (empty($var['allow_comments'])) {
245
            $var['allow_comments'] = 0;
246
        }
247 1
        if (empty($var['hidden'])) {
248
            $var['hidden'] = 0;
249
        }
250
251 1
        if (empty($var['keywords'])) {
252
            $var['keywords'] = '';
253
        }
254 1
        if (empty($var['description'])) {
255
            $var['description'] = '';
256
        }
257
258 1
        if (!isset($var['pic_id'])) {
259 1
            $var['pic_id'] = 0;
260 1
        }
261
262 1
        $type_key = array_search($var['page_type'], $this->getTypes());
263
264 1
        if (empty($var['date_publish'])) {
265 1
            $sql_publish = 'NOW()';
266 1
        } else {
267
            $sql_publish = "'".$var['date_publish']."'";
268
        }
269
270 1
        if (empty($var['identifier'])) {
271
            $var['identifier'] = md5(date('d-m-Y H:i:s') . $type_key . serialize($var));
272
        }
273
274 1
        settype($var['date_expire'], 'string');
275
276 1
        if (!$this->validate($var)) {
277
            return 0;
278
        }
279
280 1 View Code Duplication
        if ($this->id == 0) {
281 1
            $sql_type = "INSERT INTO ";
282 1
            $sql_end = ", date_created = NOW()";
283 1
        } else {
284
            $sql_type = "UPDATE ";
285
            $sql_end = ", date_updated = NOW() WHERE id = " . $this->id;
286
        }
287
288 1
        $sql_extra = '';
289
290 1
        if (!empty($var['navigation_name'])) {
291 1
            $sql_extra .= "navigation_name = '".$var['navigation_name']."', ";
292 1
        }
293 1
        if (isset($var['child_of_id'])) {
294
            $sql_extra .= "child_of_id = '".(int)$var['child_of_id']."', ";
295
        }
296
297
        // if the page is to updated
298
        $sql = $sql_type . " cms_page SET
299 1
            intranet_id = '".$this->kernel->intranet->get('id')."',
300 1
            user_id = '".$this->kernel->user->get('id')."',
301 1
            title = '" .$var['title']. "',
302 1
            keywords = '" .$var['keywords']. "',
303 1
            description = '".$var['description']."',
304 1
            date_publish = ".$sql_publish.",
305 1
            allow_comments = ".$var['allow_comments'].",
306 1
            hidden = ".$var['hidden'].",
307 1
            date_expire = '".$var['date_expire']."',
308 1
            type_key = ".(int)$type_key.",
309 1
            ".$sql_extra."
310
            date_updated = NOW(),
311 1
            site_id = '".(int)$this->cmssite->get('id')."',
312 1
            template_id = ".$var['template_id'].",
313 1
            pic_id = ".intval($var['pic_id']).",
314 1
            identifier = '".$var['identifier']."'" . $sql_end;
315
        // password = '".$var['password']."',
316 1
        $db = new DB_Sql;
317 1
        $db->query($sql);
318
319 1
        $need_to_add_keywords = false;
320
321 1
        if ($this->id == 0) {
322 1
            $this->id = $db->insertedId();
323 1
            $need_to_add_keywords = true;
324 1
        }
325 1
        $this->load();
326
327
328
        //position
329 1
        $db->query("SELECT position FROM cms_page WHERE id = " . $this->id);
330 1
        if ($db->nextRecord()) {
331 1
            if ($db->f('position') == 0 and count($this->getList($this->value['type']) > 0)) {
0 ignored issues
show
Unused Code introduced by
The call to CMS_Page::getList() has too many arguments starting with $this->value['type'].

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
332 1
                $next_pos = $this->getPosition(MDB2::singleton(DB_DSN))->getMaxPosition() + 1;
333 1
                $db->query("UPDATE cms_page SET position = " . $next_pos . " WHERE id = " . $this->id);
334 1
            }
335 1
        }
336
337 1
        if ($need_to_add_keywords) {
338 1
            $this->template->getKeywords();
339 1
            $keywords_to_add = $this->template->getKeywordAppender()->getConnectedKeywordsAsString();
340 1
            $string_appender = new Intraface_Keyword_StringAppender($this->getKeywords(), $this->getKeywordAppender());
341 1
            $string_appender->addKeywordsByString($keywords_to_add);
342 1
        }
343
344 1
        return $this->id;
345
    }
346
347
348
    /**
349
     * loads the content for a page
350
     *
351
     * @todo hvad skal den helt n�jagtig loade? - skal den fx loadde elementerne ogs�?
352
     * Hvis vi er inde i redigering, kan den loade alt, men hvis vi er ved weblogin, s
353
     * skal den kun kunne loade nogle sider.
354
     *
355
     * @return boolean
356
     */
357 4
    function load()
358
    {
359 4
        if ($this->id <= 0) {
360 3
            return false;
361
        }
362
363 1
        $sql_expire = '';
364 1
        $sql_publish = '';
365 1
        if (!is_object($this->kernel->user)) {
366
            $sql_expire = " AND (date_expire > NOW() OR date_expire = '0000-00-00 00:00:00')";
367
            $sql_publish = " AND date_publish < NOW() AND status_key > 0";
368
        }
369
370 1
        $sql = "SELECT *, DATE_FORMAT(date_publish, '%d-%m-%Y') AS date_publish_dk FROM cms_page WHERE intranet_id = ".$this->cmssite->kernel->intranet->get('id')." AND id = " .$this->id . $sql_expire . $sql_publish;
371
372 1
        $db = new DB_Sql();
373 1
        $db->query($sql);
374
375 1
        if (!$db->nextRecord()) {
376
            return false;
377
        }
378
379 1
        $this->value['id'] = $db->f('id');
380 1
        $this->value['active'] = $db->f('active');
381 1
        $this->value['site_id'] = $db->f('site_id');
382 1
        $this->value['type_key'] = $db->f('type_key');
383 1
        $types = $this->getTypes();
384 1
        $this->value['type'] = $types[$db->f('type_key')];
385 1
        $this->value['identifier'] = $db->f('identifier');
386 1
        if (empty($this->value['identifier'])) {
387
            $this->value['identifier'] = $db->f('id');
388
        }
389 1
        $this->value['url'] =  $this->cmssite->get('url') . $this->value['identifier'] . '/';
390 1
        $this->value['url_self'] =  $this->value['identifier'] . '/';
391
392 1
        $this->value['child_of_id'] = $db->f('child_of_id');
393 1
        $this->value['name'] = $db->f('title'); //  bruges til keywords - m�ske skulle vi have et felt ogs�, s� title var webrelateret?
394 1
        $this->value['title'] = $db->f('title');
395 1
        $this->value['navigation_name'] = $db->f('navigation_name');
396 1
        if (empty($this->value['navigation_name'])) {
397
            $this->value['navigation_name'] = $this->value['title'];
398
        }
399 1
        $this->value['description'] = $db->f('description');
400 1
        $this->value['keywords'] = $db->f('keywords');
401 1
        $this->value['date_created'] = $db->f('date_created');
402 1
        $this->value['date_updated'] = $db->f('date_updated');
403 1
        $this->value['date_publish_dk'] = $db->f('date_publish_dk');
404 1
        $this->value['date_publish'] = $db->f('date_publish');
405 1
        $this->value['date_expire'] = $db->f('date_expire');
406 1
        $this->value['status_key'] = $db->f('status_key');
407 1
        $this->value['status'] = $this->status[$db->f('status_key')];
408 1
        $this->value['pic_id'] = $db->f('pic_id');
409 1
        $this->value['allow_comments'] = $db->f('allow_comments');
410 1
        $this->value['hidden'] = $db->f('hidden');
411 1
        $this->value['cc_license'] = $this->cc_license[$this->cmssite->get('cc_license')];
412 1
        $this->value['site']['url'] = $this->cmssite->get('url');
413
414 1
        $this->template->id = $db->f('template_id');
415 1
        $this->template->load();
416
417 1
        $this->value['template_id'] = $db->f('template_id');
418 1
        $this->value['template_identifier'] = $this->template->get('identifier');
419
420 1
        if ($this->get('type') == 'page') {
421 1
            $i = 0;
422 1
            $page_tree[$i]['navigation_name'] = $this->get('navigation_name');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$page_tree was never initialized. Although not strictly required by PHP, it is generally a good practice to add $page_tree = 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...
423 1
            $page_tree[$i]['url'] = $this->get('url');
424 1
            $page_tree[$i]['url_self'] = $this->get('url_self');
425 1
            $page_tree[$i]['id'] = $this->get('id');
426
427 1
            $child_of_id = $this->get('child_of_id');
428 1
            while ($child_of_id != 0) {
429
                $i++;
430
431
                $db->query("SELECT child_of_id, navigation_name, title, id, identifier FROM cms_page WHERE intranet_id = ".$this->kernel->intranet->get('id')." AND active = 1 AND type_key = ".$this->get('type_key')." AND id = ".$child_of_id);
432
                if ($db->nextRecord()) {
433
                    $page_tree[$i]['navigation_name'] = $db->f('navigation_name');
434
                    if (empty($page_tree[$i]['navigation_name'])) {
435
                        $page_tree[$i]['navigation_name'] = $db->f('title');
436
                    }
437
                    $page_tree[$i]['url'] = $this->cmssite->get('url').$db->f('identifier').'/';
438
                    $page_tree[$i]['url_self'] = $db->f('identifier').'/';
439
                    $page_tree[$i]['id'] = $db->f('id');
440
                    $child_of_id = $db->f('child_of_id');
441
                } else {
442
                    $child_of_id = 0;
443
                }
444
445
                if ($i == 50) {
446
                    throw new Exception("The while loop is runing loose in CMS_Page::load");
447
                }
448
            }
449
450
            // Vi vender arrayet rundt, s� key kommer til at passe til level.
451 1
            $this->value['page_tree'] = array_reverse($page_tree);
452 1
        }
453
454 1
        return true;
455
    }
456
457
    /**
458
     * Checks whether the correct sections has been created on the page.
459
     * Maybe a bit ot much that it is checked each time
460
     */
461 1
    function getSections()
462
    {
463
        $template_sections = $this->template->getSections();
464
465
        foreach ($template_sections as $template_section) {
466
            $db = new DB_Sql;
467
            $db->query("SELECT id FROM cms_section WHERE intranet_id = ".$this->kernel->intranet->get('id')." AND page_id = ".$this->get('id')." AND site_id = ".$this->cmssite->get('id')." AND template_section_id = " . $template_section['id']);
468
469
            // opretter de sektioner der ikke er oprettet p� siden
470
            if (!$db->nextRecord()) {
471
                $section = CMS_Section::factory($this, 'type', $template_section['type']);
472
                $section->save(array('type_key' => $template_section['type_key'], 'template_section_id' => $template_section['id']));
473
            }
474
        }
475
476
        // man kan rende ind i det problem at en sektion er i overskud
477
        // jeg vil foresl�, at hvis userobjektet findes, s� tages den med og p� page.php
478
        // gives en mulighed for at slette den. Eksternt skal den ikke med
479
480
        $db = new DB_Sql;
481
        $db->query("SELECT cms_section.id FROM cms_section INNER JOIN cms_template_section ON cms_section.template_section_id = cms_template_section.id
482
            WHERE cms_section.intranet_id = ".$this->kernel->intranet->get('id')."
483
                AND cms_section.page_id = " . $this->id . " ORDER BY cms_template_section.position ASC");
484 1
        $i = 0;
485
        $section = array();
486
        while ($db->nextRecord()) {
487
            $section[$i] = CMS_Section::factory($this, 'cmspage_and_id', $db->f('id'));
488
            $i++;
489
        }
490
491 1
        return $section;
492
    }
493
494
    // @todo dette navn giver ikke nogen mening
495
    function collect()
496
    {
497
        $sections = $this->getSections();
498
        $page_sections = array();
499
        $i = 0;
500
        if (is_array($sections) and count($sections) > 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
501
            foreach ($sections as $key => $section) {
502
                $page_sections[$i] = $section->get();
503
                $i++;
504
            }
505
        }
506
        return $page_sections;
507
    }
508
509
    /**
510
     * Funktion til at udskrive elementerne
511
     *
512
513
    function display($type = '') {
514
        $elements = $this->getElements();
515
        $display = '';
516
517
518
        if (is_array($elements) AND count($elements) > 0) {
519
            foreach ($elements AS $key => $element) {
520
                $display .= $element->display($type);
521
            }
522
        }
523
524
525
        return $display;
526
    }
527
    */
528
    function getComments()
529
    {
530
        if (!$this->kernel->intranet->hasModuleAccess('contact')) {
531
            return '';
532
        }
533
534
        $this->kernel->useShared('comment');
535
536
        $i = 0;
0 ignored issues
show
Unused Code introduced by
$i 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...
537
        $messages = Comment::getList('cmspage', $this->kernel, $this->get('id'));
538
539
        return $messages;
540
    }
541
542
543 3
    function getList()
544
    {
545 3
        $gateway = new Intraface_modules_cms_PageGateway($this->kernel, new DB_Sql);
546 3
        $gateway->setDBQuery($this->getDBQuery());
547
548
        /**
549
         * @todo: $this (Page) should not be added to the method, but this is the
550
         * only way to be able to generate submenu as it works now.
551
         */
552 3
        return $gateway->findAllBySite($this->cmssite, $this);
553
554
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
555
        $pages = array();
556
557
        if ($this->getDBQuery()->checkFilter('type') && $this->getDBQuery()->getFilter('page') == 'all') {
558
            // no condition isset
559
            // $sql_type = "";
560
        } else {
561
            // with int it will never be a fake searcy
562
            $type = $this->getDBQuery()->getFilter('type');
563
            if ($type == '') {
564
                $type = 'page'; // Standard
565
            }
566
567
            if ($type != 'all') {
568
                $type_key = array_search($type, $this->getTypes());
569
                if ($type_key === false) {
570
                    throw new Exception("Invalid type '".$type."' set with CMS_PAGE::dbquery::setFilter('type') in CMS_Page::getList");
571
                }
572
573
                $this->getDBQuery()->setCondition("type_key = ".$type_key);
574
            }
575
        }
576
577
578
        // hvis en henter siderne uden for systemet
579
        $sql_expire = '';
580
        $sql_publish = '';
581
        // @todo This need to be corrected
582
        if (!is_object($this->kernel->user)) {
583
            $this->getDBQuery()->setCondition("(date_expire > NOW() OR date_expire = '0000-00-00 00:00:00') AND (date_publish < NOW() AND status_key > 0 AND hidden = 0)");
584
        }
585
586
        switch ($this->getDBQuery()->getFilter('type')) {
587
            case 'page':
588
                $this->getDBQuery()->setSorting("position ASC");
589
            break;
590
            case 'news':
591
                $this->getDBQuery()->setSorting("date_publish DESC");
592
            break;
593
            case 'article':
594
                $this->getDBQuery()->setSorting("position, date_publish DESC");
595
            break;
596
            default:
597
                $this->getDBQuery()->setSorting("date_publish DESC");
598
            break;
599
        }
600
601
        // rekursiv funktion til at vise siderne
602
        $pages = array();
603
        $go = true;
604
        $n = 0; // level
605
        // $o = 0; //
606
        $i = 0; // page counter
607
        // $level = 1;
608
        $cmspage = array();
609
        $cmspage[0] = new DB_Sql;
610
611
        // Benyttes til undersider.
612
        $dbquery_original = clone $this->getDBQuery();
613
        $dbquery_original->storeResult('','', 'toplevel'); // sikre at der ikke bliver gemt ved undermenuer.
614
615
616
        $keywords = $this->getDBQuery()->getKeyword();
617
        if (isset($keywords) && is_array($keywords) && count($keywords) > 0 && $type == 'page') {
618
            // If we are looking for pages, and there is keywords, we probaly want from more than one level
619
            // So we add nothing about level to condition.
620
621
        } elseif ($this->getDBQuery()->checkFilter('level') && $type == 'page') { // $level == 'sublevel' &&
622
623
            // Til at finde hele menuen p� valgt level.
624
            $page_tree = $this->get('page_tree');
625
            $level = (int)$this->getDBQuery()->getFilter('level');
626
            if (isset($page_tree[$level - 1]) && is_array($page_tree[$level - 1])) {
627
                $child_of_id = $page_tree[$level - 1]['id'];
628
            } else {
629
                $child_of_id = 0;
630
            }
631
632
            $this->getDBQuery()->setCondition('child_of_id = '.$child_of_id);
633
            // $cmspage[0]->query("SELECT *, DATE_FORMAT(date_publish, '%d-%m-%Y') AS date_publish_dk FROM cms_page WHERE active=1 AND child_of_id = ".$this->id. $sql_expire . $sql_publish . " ORDER BY id");
634
635
        } else {
636
            $this->getDBQuery()->setCondition('child_of_id = 0');
637
            // $cmspage[0]->query("SELECT *, DATE_FORMAT(date_publish, '%d-%m-%Y') AS date_publish_dk FROM cms_page WHERE ".$sql_type." site_id = " . $this->cmssite->get('id') . " AND child_of_id = 0 AND active = 1 " . $sql_expire . $sql_publish . $sql_order);
638
        }
639
640
        $cmspage[0] = $this->getDBQuery()->getRecordset("cms_page.id, title, identifier, status_key, navigation_name, date_publish, child_of_id, pic_id, description, DATE_FORMAT(date_publish, '%d-%m-%Y') AS date_publish_dk", '', false); //
641
642
        while(TRUE) {
643
            while($cmspage[$n]->nextRecord()) {
644
645
                $pages[$i]['id'] = $cmspage[$n]->f('id');
646
647
                $pages[$i]['title'] = $cmspage[$n]->f('title');
648
                $pages[$i]['identifier'] = $cmspage[$n]->f('identifier');
649
                $pages[$i]['navigation_name'] = $cmspage[$n]->f('navigation_name');
650
                $pages[$i]['date_publish_dk'] = $cmspage[$n]->f('date_publish_dk');
651
                $pages[$i]['date_publish'] = $cmspage[$n]->f('date_publish');
652
                $pages[$i]['child_of_id'] = $cmspage[$n]->f('child_of_id');
653
                $pages[$i]['level'] = $n;
654
655
                if (empty($pages[$i]['identifier'])) {
656
                    $pages[$i]['identifier'] = $pages[$i]['id'];
657
                }
658
                if (empty($pages[$i]['navigation_name'])) {
659
                    $pages[$i]['navigation_name'] = $pages[$i]['title'];
660
                }
661
662
                $pages[$i]['status'] = $this->status[$cmspage[$n]->f('status_key')];
663
664
                // @todo hvad er det her til
665
                $pages[$i]['new_status'] = 'published';
666
                if ($pages[$i]['status'] == 'published') {
667
                    $pages[$i]['new_status'] = 'draft';
668
                }
669
                // hertil slut
670
671
                // denne b�r laves om til picture - og s� f�r man alle nyttige oplysninger ud
672
                $pages[$i]['pic_id'] = $cmspage[$n]->f('pic_id');
673
                $pages[$i]['picture'] = $this->getPicture($cmspage[$n]->f('pic_id'));
674
675
                //$pages[$i]['picture'] = $cmspage[$n]->f('pic_id');
676
                $pages[$i]['description'] = $cmspage[$n]->f('description');
677
678
                // til google sitemaps
679
                // sp�rgsm�let er om vi ikke skal starte et objekt op for hver pages
680
681
                $pages[$i]['url'] = $this->cmssite->get('url') . $pages[$i]['identifier'] . '/';
682
                $pages[$i]['url_self'] = $pages[$i]['identifier'] . '/';
683
                $pages[$i]['changefreq'] = 'weekly';
684
                $pages[$i]['priority'] = 0.5;
685
686
                $i++;
687
                // $o = $n + 1;
688
689
                if ($this->getDBQuery()->getFilter('type') == 'page' AND $this->getDBQuery()->getFilter('level') == 'alllevels') {
690
                    $dbquery[$n + 1] = clone $dbquery_original;
691
                    $dbquery[$n + 1]->setCondition("child_of_id = ".$cmspage[$n]->f("id"));
692
                    $cmspage[$n + 1] = $dbquery[$n + 1]->getRecordset("id, title, identifier, navigation_name, date_publish, child_of_id, pic_id, status_key, description, DATE_FORMAT(date_publish, '%d-%m-%Y') AS date_publish_dk", '', false);
693
694
                    // if (!array_key_exists($n + 1, $cmspage) OR !is_object($cmspage[$n + 1])) {
695
                    //  $cmspage[$n + 1] = new DB_Sql;
696
                    //}
697
                    // $cmspage[$n + 1]->query("SELECT *, DATE_FORMAT(date_publish, '%d-%m-%Y') AS date_publish_dk FROM cms_page WHERE active=1 AND child_of_id = ".$cmspage[$n]->f("id"). $sql_expire . $sql_publish . " ORDER BY id");
698
699
                    if ($cmspage[$n + 1]->numRows() != 0) {
700
                        $n++;
701
                        continue;
702
                    }
703
                }
704
705
            }
706
707
            if ($n == 0) {
708
                break;
709
            }
710
711
            $n--;
712
        }
713
714
        return $pages;
715
		*/
716
    }
717
718 View Code Duplication
    function getPicture($pic_id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
719
    {
720
        $shared_filehandler = $this->kernel->useModule('filemanager');
721
        $shared_filehandler->includeFile('AppendFile.php');
722
723
                $tmp_filehandler = new FileHandler($this->kernel, $pic_id);
724
                $this->value['picture']['id']                   = $pic_id;
725
                $this->value['picture']['original']['icon_uri'] = $tmp_filehandler->get('icon_uri');
726
                $this->value['picture']['original']['name']     = $tmp_filehandler->get('file_name');
727
                $this->value['picture']['original']['width']    = $tmp_filehandler->get('width');
728
                $this->value['picture']['original']['height']   = $tmp_filehandler->get('height');
729
                $this->value['picture']['original']['file_uri'] = $tmp_filehandler->get('file_uri');
730
731
        if ($tmp_filehandler->get('is_image')) {
732
            $tmp_filehandler->createInstance();
733
            $instances = $tmp_filehandler->instance->getList('include_hidden');
734
            foreach ($instances as $instance) {
735
                $this->value['picture'][$instance['name']]['file_uri'] = $instance['file_uri'];
736
                $this->value['picture'][$instance['name']]['name']     = $instance['name'];
737
                $this->value['picture'][$instance['name']]['width']    = $instance['width'];
738
                $this->value['picture'][$instance['name']]['height']   = $instance['height'];
739
            }
740
        }
741
742
            return $this->value['picture'];
743
    }
744
745
    /**
746
     * @todo is this still used after the introduction of publish and unpublish
747
     */
748 1
    function setStatus($status)
749
    {
750 1
        if (empty($status)) {
751
            $status = 'draft';
752
        }
753 1
        if (!in_array($status, $this->status)) {
754
            return false;
755
        }
756 1
        $db = new DB_Sql;
757 1
        $db->query("UPDATE cms_page SET status_key = " . array_search($status, $this->status) . " WHERE id = " . $this->id . " AND intranet_id = " . $this->cmssite->kernel->intranet->get('id'));
758 1
        $this->value['status_key'] = array_search($status, $this->status);
759 1
        return true;
760
    }
761
762
    function isLocked()
763
    {
764
        return 0;
765
    }
766
767 1
    function getKeywords()
768
    {
769 1
        return ($this->keywords = new Keyword($this));
0 ignored issues
show
Bug introduced by
The property keywords does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
770
    }
771
772 1
    function getKeywordAppender()
773
    {
774 1
        return new Intraface_Keyword_Appender($this);
775
    }
776
777
    /**
778
     *
779
     * Funktionen skal tjekke alle siderne igennem for at se, om der findes undersider -
780
     * ellers vil de forsvinde fra oversigten.
781
     */
782 1
    function delete()
783
    {
784 1
        $db = new DB_Sql();
785 1
        $db2 = new DB_Sql;
0 ignored issues
show
Unused Code introduced by
$db2 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...
786
          // egentlig skuille denne m�ske v�re rekursiv?
787
788
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% 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...
789
        // I am not quite sure what this one is suppossed to do - see the next one instead.
790
        $sql = "SELECT * FROM cms_page WHERE child_of_id=" . $this->id . " AND site_id = " . $this->cmssite->get('id');
791
        $db->query($sql);
792
        while($db->nextRecord()) {
793
            $db2->query('UPDATE cms_page SET child_of_id = '.$db->f('child_of_id').' WHERE child_of_id = ' . $this->id . ' AND site_id = ' . $this->cmssite->get('id'));
794
        }
795
        */
796
797
        // WE move all subpages to a level under - this also works on recursive sites.
798
        // @todo: BUT it can be a mess and the position of the pages is not corrected
799 1
        $db->query('UPDATE cms_page SET child_of_id = '.intval($this->get('child_of_id')).' WHERE child_of_id = '.intval($this->id));
800
801 1
        $sql = "UPDATE cms_page SET active = 0 WHERE id=" . $this->id . " AND site_id = ".$this->cmssite->get('id');
802 1
        $db->query($sql);
803 1
        $this->value['active'] = 0;
804 1
        $this->load();
805 1
        return true;
806
    }
807
808 1
    function getId()
809
    {
810 1
        return $this->id;
811
    }
812
813
    /**
814
     * Returns the possible page types
815
     *
816
     * @return array possible page types
817
     */
818 1
    public function getTypes()
819
    {
820 1
        return Intraface_modules_cms_PageGateway::getTypes();
821
    }
822
823
    /**
824
     * Returns the possible page types but with a binary index
825
     *
826
     * @return array possible page types with binary index
827
     */
828
    public static function getTypesWithBinaryIndex()
829
    {
830
        return Intraface_modules_cms_PageGateway::getTypesWithBinaryIndex();
831
    }
832
833
    /**
834
     * Returns the possible page types in plural
835
     *
836
     * @return array page types in plural
837
     */
838
    public static function getTypesPlural()
839
    {
840
        return array(
841
            'page' => 'pages',
842
            'article' => 'articles',
843
            'news' => 'news');
844
    }
845
846 2
    function isPublished()
847
    {
848 2
        return ($this->get('status_key') == 1);
849
    }
850
851 1
    function getStatus()
852
    {
853 1
        return $this->status[$this->value['status_key']];
854
    }
855
856 2
    function publish()
857
    {
858 2
        $db = new DB_Sql;
859 2
        $db->query("UPDATE cms_page SET status_key = " . array_search('published', $this->status) . " WHERE id = " . $this->id . " AND intranet_id = " . $this->cmssite->kernel->intranet->get('id'));
860 2
        $this->value['status_key'] = 1;
861 2
        $this->load();
862 2
        return true;
863
    }
864
865 1
    function unpublish()
866
    {
867 1
        $db = new DB_Sql;
868 1
        $db->query("UPDATE cms_page SET status_key = " . array_search('draft', $this->status) . " WHERE id = " . $this->id . " AND intranet_id = " . $this->cmssite->kernel->intranet->get('id'));
869 1
        $this->value['status_key'] = 0;
870 1
        $this->load();
871 1
        return true;
872
    }
873
874 1
    function isActive()
875
    {
876 1
        return ($this->value['active'] == 1);
877
    }
878
}
879