Welcome to mirror list, hosted at ThFree Co, Russian Federation.

IndexedBySite.php « Array « Archive « core - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1ac9ff682a995eecf5aa79012e139ad16f660c02 (plain)
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Piwik
 * @package Piwik
 */

/**
 * @package Piwik
 * @subpackage Piwik_Archive
 */
class Piwik_Archive_Array_IndexedBySite extends Piwik_Archive_Array
{
    /**
     * Used to cache the name of the table that holds the data this archive.
     *
     * This will only be used if the archives held by this instance are instances of
     * Piwik_Archive_Single.
     */
    private $tableName = null;

    /**
     * @param array $sites      array of siteIds
     * @param string $strPeriod  eg. 'day' 'week' etc.
     * @param string $strDate    A date range, eg. 'last10', 'previous5' or 'YYYY-MM-DD,YYYY-MM-DD'
     * @param Piwik_Segment $segment
     * @param string $_restrictSitesToLogin
     */
    function __construct($sites, $strPeriod, $strDate, Piwik_Segment $segment, $_restrictSitesToLogin)
    {
        foreach ($sites as $idSite) {
            $archive = Piwik_Archive::build($idSite, $strPeriod, $strDate, $segment, $_restrictSitesToLogin);
            $this->archives[$idSite] = $archive;
        }
        ksort($this->archives);
    }

    /**
     * @return string
     */
    protected function getIndexName()
    {
        return 'idSite';
    }

    /**
     * @param Piwik_Archive $archive
     * @return mixed
     */
    protected function getDataTableLabelValue($archive)
    {
        return $archive->getIdSite();
    }

    /**
     * Given a list of fields defining numeric values, it will return a Piwik_DataTable_Array
     * ordered by idsite
     *
     * @param array|string $fields  array( fieldName1, fieldName2, ...)  Names of the mysql table fields to load
     * @return Piwik_DataTable_Array
     */
    public function getDataTableFromNumeric($fields)
    {
        $tableArray = $this->getNewDataTableArray();
        if ($this->getFirstArchive() instanceof Piwik_Archive_Single) {
            $values = $this->getValues($fields);
            foreach ($this->archives as $idSite => $archive) {
                $table = $archive->makeDataTable($isSimple = true);
                if (array_key_exists($idSite, $values)) {
                    $table->addRowsFromArray($values[$idSite]);
                }
                $tableArray->addTable($table, $idSite);
            }
        } elseif ($this->getFirstArchive() instanceof Piwik_Archive_Array) {
            foreach ($this->archives as $idSite => $archive) {
                $tableArray->addTable($archive->getDataTableFromNumeric($fields), $idSite);
            }
        }

        return $tableArray;
    }

    /**
     * Returns the values of the requested fields
     *
     * @param array $fields
     * @return array
     */
    private function getValues($fields)
    {
        // Creating the default array, to ensure consistent order
        $defaultValues = array();
        foreach ($fields as $field) {
            $defaultValues[$field] = null;
        }

        $arrayValues = array();
        foreach ($this->loadValuesFromDB($fields) as $value) {
            if (!isset($arrayValues[$value['idsite']])) {
                $arrayValues[$value['idsite']] = $defaultValues;
            }
            $arrayValues[$value['idsite']][$value['name']] = $this->formatNumericValue($value['value']);
        }
        return $arrayValues;
    }

    /**
     * @param $fields
     * @return array|array  (one row in the array per row fetched in the DB)
     */
    private function loadValuesFromDB($fields)
    {
        $requestedMetrics = is_string($fields) ? array($fields) : $fields;
        $inNames = Piwik_Common::getSqlStringFieldsArray($fields);

        // get the archive ids
        if (!$this->getFirstArchive()->isArchivingDisabled()) {
            $archiveIds = $this->getArchiveIdsAfterLaunching($requestedMetrics);
        } else {
            $archiveIds = $this->getArchiveIdsWithoutLaunching($requestedMetrics);
        }

        $archiveIds = implode(', ', array_filter($archiveIds));

        // if no archive ids are found, avoid executing any SQL queries
        if (empty($archiveIds)) {
            return array();
        }

        // select archive data
        $sql = "SELECT value, name, idarchive, idsite
								FROM {$this->getNumericTableName()}
								WHERE idarchive IN ( $archiveIds )
									AND name IN ( $inNames )";

        return Piwik_FetchAll($sql, $fields);
    }

    /**
     * Returns the first archive in the list
     *
     * @return Piwik_Archive
     */
    private function getFirstArchive()
    {
        return reset($this->archives);
    }

    /**
     * Gets the archive id of every Single archive this archive holds. This method
     * will launch the archiving process if appropriate.
     *
     * @param array $metrics  The requested archive metrics.
     * @throws Exception
     * @return array
     */
    private function getArchiveIdsAfterLaunching($metrics)
    {
        // collect the individual report names for the requested metrics
        $reports = array();
        foreach ($metrics as $metric) {
            $report = Piwik_Archive_Single::getRequestedReportFor($metric);
            $reports[$report] = $metric;
        }

        // process archives for each individual report
        $archiveIds = array();
        foreach ($reports as $report => $metric) {
            // prepare archives (this will launch archiving when appropriate)
            foreach ($this->archives as $archive) {
                // NOTE: Piwik_Archive_Single expects a metric here, not a report
                $archive->setRequestedReport($metric);
                $archive->prepareArchive();
            }

            // collect archive ids for archives that have visits
            foreach ($this->archives as $archive) {
                if (!$archive->isThereSomeVisits) {
                    continue;
                }

                $archiveIds[] = $archive->getIdArchive();

                if ($this->getNumericTableName() != $archive->archiveProcessing->getTableArchiveNumericName()) {
                    throw new Exception("Piwik_Archive_Array_IndexedBySite::getDataTableFromNumeric() algorithm won't work if data is stored in different tables");
                }
            }
        }

        return $archiveIds;
    }

    /**
     * Gets the archive id of every Single archive this archive holds. This method
     * will not launch the archiving process.
     *
     * @param array $metrics  The requested archive metrics.
     * @return array
     */
    private function getArchiveIdsWithoutLaunching($metrics)
    {
        $firstArchive = $this->getFirstArchive();
        $segment = $firstArchive->getSegment();
        $period = $firstArchive->getPeriod();

        // the flags used to tell how the archiving process for a specific archive was completed,
        // if it was completed
        $doneFlags = array();
        foreach ($metrics as $metric) {
            $done = Piwik_ArchiveProcessing::getDoneStringFlagFor($segment, $period, $metric);
            $donePlugins = Piwik_ArchiveProcessing::getDoneStringFlagFor($segment, $period, $metric, true);

            $doneFlags[$done] = $done;
            $doneFlags[$donePlugins] = $donePlugins;
        }

        $allDoneFlags = "'" . implode("','", $doneFlags) . "'";

        // create the SQL to query every archive ID
        $nameCondition = "(name IN ($allDoneFlags)) AND
						  (value = '" . Piwik_ArchiveProcessing::DONE_OK . "' OR
						   value = '" . Piwik_ArchiveProcessing::DONE_OK_TEMPORARY . "')";

        $sql = "SELECT idsite,
		               MAX(idarchive) AS idarchive
		          FROM " . $this->getNumericTableName() . "
		         WHERE date1 = ?
		           AND date2 = ?
		           AND period = ?
		           AND $nameCondition
		           AND idsite IN (" . implode(',', array_keys($this->archives)) . ")
		      GROUP BY idsite";

        $bind = array($period->getDateStart()->toString('Y-m-d'),
                      $period->getDateEnd()->toString('Y-m-d'),
                      $period->getId());

        // execute the query and process the results.
        $archiveIds = array();
        foreach (Piwik_FetchAll($sql, $bind) as $row) {
            $archiveIds[] = $row['idarchive'];
        }

        return $archiveIds;
    }

    /**
     * Gets the name of the database table that holds the numeric archive data for
     * this archive.
     *
     * @return string
     */
    private function getNumericTableName()
    {
        if (is_null($this->tableName)) {
            $table = Piwik_ArchiveProcessing::makeNumericArchiveTable($this->getFirstArchive()->getPeriod());
            $this->tableName = $table->getTableName();
        }

        return $this->tableName;
    }
}