File: Model.php

package info (click to toggle)
matomo 5.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 95,068 kB
  • sloc: php: 289,425; xml: 127,249; javascript: 112,130; python: 202; sh: 178; makefile: 20; sql: 10
file content (232 lines) | stat: -rw-r--r-- 6,549 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
<?php

/**
 * Matomo - free/libre analytics platform
 *
 * @link    https://matomo.org
 * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik\Changes;

use Piwik\Log\LoggerInterface;
use Piwik\Piwik;
use Piwik\Common;
use Piwik\Date;
use Piwik\Db;
use Piwik\Tracker\Db\DbException;
use Piwik\Updater\Migration;
use Piwik\Container\StaticContainer;
use Piwik\Plugin\Manager as PluginManager;

/**
 * Change model class
 *
 * Handle all data access operations for changes
 *
 */
class Model
{
    public const NO_CHANGES_EXIST = 0;
    public const CHANGES_EXIST = 1;
    public const NEW_CHANGES_EXIST = 2;

    /**
     * @var Db\AdapterInterface
     */
    private $db;

    /** @var array */
    private $changeItems = null;

    public function __construct()
    {
        $this->db = Db::get();
    }

    /**
     * Add any new changes for a plugin to the changes table
     *
     *
     * @throws \Exception
     */
    public function addChanges(string $pluginName): void
    {
        $pluginManager = PluginManager::getInstance();

        if (
            $pluginManager &&
            $pluginManager->isValidPluginName($pluginName) &&
            $pluginManager->isPluginInFilesystem($pluginName) &&
            $pluginManager->isPluginActivated($pluginName)
        ) {
            $plugin = $pluginManager->loadPlugin($pluginName);
            if (!$plugin) {
                return;
            }

            $changes = $plugin->getChanges();
            foreach ($changes as $change) {
                $this->addChange($pluginName, $change);
            }
        }
    }

    /**
     * Remove all changes for a plugin
     *
     */
    public function removeChanges(string $pluginName): void
    {
        $table = Common::prefixTable('changes');

        try {
            $this->db->query("DELETE FROM `" . $table . "` WHERE plugin_name = ?", [$pluginName]);
        } catch (\Exception $e) {
            if (Db::get()->isErrNo($e, Migration\Db::ERROR_CODE_TABLE_NOT_EXISTS)) {
                return;
            }
            throw $e;
        }
    }

    /**
     * Add a change item to the database table
     *
     * @param array  $change
     */
    public function addChange(string $pluginName, array $change): void
    {
        if (!isset($change['version']) || !isset($change['title']) || !isset($change['description'])) {
            StaticContainer::get(LoggerInterface::class)->warning(
                "Change item for plugin {plugin} missing version, title or description fields - ignored",
                ['plugin' => $pluginName]
            );
            return;
        }

        $table = Common::prefixTable('changes');

        $fields = ['created_time', 'plugin_name', 'version', 'title', 'description'];
        $params = [Date::now()->getDatetime(), $pluginName, $change['version'], $change['title'], $change['description']];

        if (isset($change['link_name']) && isset($change['link'])) {
            $fields[] = 'link_name';
            $fields[] = 'link';
            $params[] = $change['link_name'];
            $params[] = $change['link'];
        }

        $insertSql = 'INSERT IGNORE INTO ' . $table . ' (' . implode(',', $fields) . ') 
                      VALUES (' . Common::getSqlStringFieldsArray($params) . ')';

        try {
            $this->db->query($insertSql, $params);
        } catch (\Exception $e) {
            if (Db::get()->isErrNo($e, Migration\Db::ERROR_CODE_TABLE_NOT_EXISTS)) {
                return;
            }
            throw $e;
        }
    }

    /**
     * Check if any changes items exist
     *
     * @param int|null $newerThanId     Only count new changes as having a key > than this sequential key
     *
     */
    public function doChangesExist(?int $newerThanId = null): int
    {
        $changeItems = $this->getChangeItems();

        $all = 0;
        $new = 0;
        foreach ($changeItems as $c) {
            $all++;
            if ($newerThanId === null || (isset($c['idchange']) && $c['idchange'] > $newerThanId)) {
                $new++;
            }
        }

        if ($all === 0) {
            return self::NO_CHANGES_EXIST;
        } elseif ($all > 0 && $new === 0) {
            return self::CHANGES_EXIST;
        } else {
            return self::NEW_CHANGES_EXIST;
        }
    }

    /**
     * Get count of new changes
     *
     * @param int|null $newerThanId     Only count new changes as having a key > than this sequential key
     *
     */
    public function getNewChangesCount(?int $newerThanId = null): int
    {
        $changes = $this->getChangeItems();
        $new = 0;
        foreach ($changes as $c) {
            if ($newerThanId === null || (isset($c['idchange']) && $c['idchange'] > $newerThanId)) {
                $new++;
            }
        }
        return $new;
    }

    /**
     * Return an array of change items for the last 6 months from the changes table
     *
     * @return array
     * @throws DbException
     */
    public function getChangeItems(): array
    {

        if ($this->changeItems !== null) {
            return $this->changeItems;
        }

        $table = Common::prefixTable('changes');
        $selectSql = "SELECT * FROM `" . $table . "` WHERE title IS NOT NULL AND created_time > ? ORDER BY idchange DESC";

        try {
            $changes = $this->db->fetchAll($selectSql, [Date::now()->subMonth(6)]);
        } catch (\Exception $e) {
            if (Db::get()->isErrNo($e, Migration\Db::ERROR_CODE_TABLE_NOT_EXISTS)) {
                return [];
            }
            throw $e;
        }

        array_walk($changes, function (&$change) {
            $change['idchange'] = (int) $change['idchange'];
        });

        /**
         * Event triggered before changes are displayed
         *
         * Can be used to filter out unwanted changes
         *
         * **Example**
         *
         *     Piwik::addAction('Changes.filterChanges', function ($changes) {
         *         foreach ($changes as $k => $c) {
         *             // Hide changes for the CoreHome plugin
         *             if (isset($c['plugin_name']) && $c['plugin_name'] == 'CoreHome') {
         *                  unset($changes[$k]);
         *             }
         *         }
         *     });
         *
         * @param array &$changes
         */
        Piwik::postEvent('Changes.filterChanges', array(&$changes));

        $this->changeItems = $changes;

        return $this->changeItems;
    }
}