PageRenderTime 57ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/core/DataTable.php

https://github.com/CodeYellowBV/piwik
PHP | 1637 lines | 754 code | 127 blank | 756 comment | 125 complexity | 3c7d86fe39dce9eef6ba72d1180d740c MD5 | raw file
Possible License(s): LGPL-3.0, JSON, MIT, GPL-3.0, LGPL-2.1, GPL-2.0, AGPL-1.0, BSD-2-Clause, BSD-3-Clause
  1. <?php
  2. /**
  3. * Piwik - free/libre analytics platform
  4. *
  5. * @link http://piwik.org
  6. * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  7. *
  8. */
  9. namespace Piwik;
  10. use Closure;
  11. use Exception;
  12. use Piwik\DataTable\DataTableInterface;
  13. use Piwik\DataTable\Manager;
  14. use Piwik\DataTable\Renderer\Html;
  15. use Piwik\DataTable\Row;
  16. use Piwik\DataTable\Row\DataTableSummaryRow;
  17. use Piwik\DataTable\Simple;
  18. use Piwik\DataTable\TableNotFoundException;
  19. use ReflectionClass;
  20. /**
  21. * @see Common::destroy()
  22. */
  23. require_once PIWIK_INCLUDE_PATH . '/core/Common.php';
  24. /**
  25. * The primary data structure used to store analytics data in Piwik.
  26. *
  27. * <a name="class-desc-the-basics"></a>
  28. * ### The Basics
  29. *
  30. * DataTables consist of rows and each row consists of columns. A column value can be
  31. * a numeric, a string or an array.
  32. *
  33. * Every row has an ID. The ID is either the index of the row or {@link ID_SUMMARY_ROW}.
  34. *
  35. * DataTables are hierarchical data structures. Each row can also contain an additional
  36. * nested sub-DataTable (commonly referred to as a 'subtable').
  37. *
  38. * Both DataTables and DataTable rows can hold **metadata**. _DataTable metadata_ is information
  39. * regarding all the data, such as the site or period that the data is for. _Row metadata_
  40. * is information regarding that row, such as a browser logo or website URL.
  41. *
  42. * Finally, all DataTables contain a special _summary_ row. This row, if it exists, is
  43. * always at the end of the DataTable.
  44. *
  45. * ### Populating DataTables
  46. *
  47. * Data can be added to DataTables in three different ways. You can either:
  48. *
  49. * 1. create rows one by one and add them through {@link addRow()} then truncate if desired,
  50. * 2. create an array of DataTable\Row instances or an array of arrays and add them using
  51. * {@link addRowsFromArray()} or {@link addRowsFromSimpleArray()}
  52. * then truncate if desired,
  53. * 3. or set the maximum number of allowed rows (with {@link setMaximumAllowedRows()})
  54. * and add rows one by one.
  55. *
  56. * If you want to eventually truncate your data (standard practice for all Piwik plugins),
  57. * the third method is the most memory efficient. It is, unfortunately, not always possible
  58. * to use since it requires that the data be sorted before adding.
  59. *
  60. * ### Manipulating DataTables
  61. *
  62. * There are two ways to manipulate a DataTable. You can either:
  63. *
  64. * 1. manually iterate through each row and manipulate the data,
  65. * 2. or you can use predefined filters.
  66. *
  67. * A filter is a class that has a 'filter' method which will manipulate a DataTable in
  68. * some way. There are several predefined Filters that allow you to do common things,
  69. * such as,
  70. *
  71. * - add a new column to each row,
  72. * - add new metadata to each row,
  73. * - modify an existing column value for each row,
  74. * - sort an entire DataTable,
  75. * - and more.
  76. *
  77. * Using these filters instead of writing your own code will increase code clarity and
  78. * reduce code redundancy. Additionally, filters have the advantage that they can be
  79. * applied to DataTable\Map instances. So you can visit every DataTable in a {@link DataTable\Map}
  80. * without having to write a recursive visiting function.
  81. *
  82. * All predefined filters exist in the **Piwik\DataTable\BaseFilter** namespace.
  83. *
  84. * _Note: For convenience, [anonymous functions](http://www.php.net/manual/en/functions.anonymous.php)
  85. * can be used as DataTable filters._
  86. *
  87. * ### Applying Filters
  88. *
  89. * Filters can be applied now (via {@link filter()}), or they can be applied later (via
  90. * {@link queueFilter()}).
  91. *
  92. * Filters that sort rows or manipulate the number of rows should be applied right away.
  93. * Non-essential, presentation filters should be queued.
  94. *
  95. * ### Learn more
  96. *
  97. * - See **{@link ArchiveProcessor}** to learn how DataTables are persisted.
  98. *
  99. * ### Examples
  100. *
  101. * **Populating a DataTable**
  102. *
  103. * // adding one row at a time
  104. * $dataTable = new DataTable();
  105. * $dataTable->addRow(new Row(array(
  106. * Row::COLUMNS => array('label' => 'thing1', 'nb_visits' => 1, 'nb_actions' => 1),
  107. * Row::METADATA => array('url' => 'http://thing1.com')
  108. * )));
  109. * $dataTable->addRow(new Row(array(
  110. * Row::COLUMNS => array('label' => 'thing2', 'nb_visits' => 2, 'nb_actions' => 2),
  111. * Row::METADATA => array('url' => 'http://thing2.com')
  112. * )));
  113. *
  114. * // using an array of rows
  115. * $dataTable = new DataTable();
  116. * $dataTable->addRowsFromArray(array(
  117. * array(
  118. * Row::COLUMNS => array('label' => 'thing1', 'nb_visits' => 1, 'nb_actions' => 1),
  119. * Row::METADATA => array('url' => 'http://thing1.com')
  120. * ),
  121. * array(
  122. * Row::COLUMNS => array('label' => 'thing2', 'nb_visits' => 2, 'nb_actions' => 2),
  123. * Row::METADATA => array('url' => 'http://thing2.com')
  124. * )
  125. * ));
  126. *
  127. * // using a "simple" array
  128. * $dataTable->addRowsFromSimpleArray(array(
  129. * array('label' => 'thing1', 'nb_visits' => 1, 'nb_actions' => 1),
  130. * array('label' => 'thing2', 'nb_visits' => 2, 'nb_actions' => 2)
  131. * ));
  132. *
  133. * **Getting & setting metadata**
  134. *
  135. * $dataTable = \Piwik\Plugins\Referrers\API::getInstance()->getSearchEngines($idSite = 1, $period = 'day', $date = '2007-07-24');
  136. * $oldPeriod = $dataTable->metadata['period'];
  137. * $dataTable->metadata['period'] = Period\Factory::build('week', Date::factory('2013-10-18'));
  138. *
  139. * **Serializing & unserializing**
  140. *
  141. * $maxRowsInTable = Config::getInstance()->General['datatable_archiving_maximum_rows_standard'];j
  142. *
  143. * $dataTable = // ... build by aggregating visits ...
  144. * $serializedData = $dataTable->getSerialized($maxRowsInTable, $maxRowsInSubtable = $maxRowsInTable,
  145. * $columnToSortBy = Metrics::INDEX_NB_VISITS);
  146. *
  147. * $serializedDataTable = $serializedData[0];
  148. * $serailizedSubTable = $serializedData[$idSubtable];
  149. *
  150. * **Filtering for an API method**
  151. *
  152. * public function getMyReport($idSite, $period, $date, $segment = false, $expanded = false)
  153. * {
  154. * $dataTable = Archive::getDataTableFromArchive('MyPlugin_MyReport', $idSite, $period, $date, $segment, $expanded);
  155. * $dataTable->filter('Sort', array(Metrics::INDEX_NB_VISITS, 'desc', $naturalSort = false, $expanded));
  156. * $dataTable->queueFilter('ReplaceColumnNames');
  157. * $dataTable->queueFilter('ColumnCallbackAddMetadata', array('label', 'url', __NAMESPACE__ . '\getUrlFromLabelForMyReport'));
  158. * return $dataTable;
  159. * }
  160. *
  161. *
  162. * @api
  163. */
  164. class DataTable implements DataTableInterface
  165. {
  166. const MAX_DEPTH_DEFAULT = 15;
  167. /** Name for metadata that describes when a report was archived. */
  168. const ARCHIVED_DATE_METADATA_NAME = 'archived_date';
  169. /** Name for metadata that describes which columns are empty and should not be shown. */
  170. const EMPTY_COLUMNS_METADATA_NAME = 'empty_column';
  171. /** Name for metadata that describes the number of rows that existed before the Limit filter was applied. */
  172. const TOTAL_ROWS_BEFORE_LIMIT_METADATA_NAME = 'total_rows_before_limit';
  173. /**
  174. * Name for metadata that describes how individual columns should be aggregated when {@link addDataTable()}
  175. * or {@link Piwik\DataTable\Row::sumRow()} is called.
  176. *
  177. * This metadata value must be an array that maps column names with valid operations. Valid aggregation operations are:
  178. *
  179. * - `'skip'`: do nothing
  180. * - `'max'`: does `max($column1, $column2)`
  181. * - `'min'`: does `min($column1, $column2)`
  182. * - `'sum'`: does `$column1 + $column2`
  183. *
  184. * See {@link addDataTable()} and {@link DataTable\Row::sumRow()} for more information.
  185. */
  186. const COLUMN_AGGREGATION_OPS_METADATA_NAME = 'column_aggregation_ops';
  187. /** The ID of the Summary Row. */
  188. const ID_SUMMARY_ROW = -1;
  189. /** The original label of the Summary Row. */
  190. const LABEL_SUMMARY_ROW = -1;
  191. /**
  192. * Maximum nesting level.
  193. */
  194. private static $maximumDepthLevelAllowed = self::MAX_DEPTH_DEFAULT;
  195. /**
  196. * Array of Row
  197. *
  198. * @var Row[]
  199. */
  200. protected $rows = array();
  201. /**
  202. * Id assigned to the DataTable, used to lookup the table using the DataTable_Manager
  203. *
  204. * @var int
  205. */
  206. protected $currentId;
  207. /**
  208. * Current depth level of this data table
  209. * 0 is the parent data table
  210. *
  211. * @var int
  212. */
  213. protected $depthLevel = 0;
  214. /**
  215. * This flag is set to false once we modify the table in a way that outdates the index
  216. *
  217. * @var bool
  218. */
  219. protected $indexNotUpToDate = true;
  220. /**
  221. * This flag sets the index to be rebuild whenever a new row is added,
  222. * as opposed to re-building the full index when getRowFromLabel is called.
  223. * This is to optimize and not rebuild the full Index in the case where we
  224. * add row, getRowFromLabel, addRow, getRowFromLabel thousands of times.
  225. *
  226. * @var bool
  227. */
  228. protected $rebuildIndexContinuously = false;
  229. /**
  230. * Column name of last time the table was sorted
  231. *
  232. * @var string
  233. */
  234. protected $tableSortedBy = false;
  235. /**
  236. * List of BaseFilter queued to this table
  237. *
  238. * @var array
  239. */
  240. protected $queuedFilters = array();
  241. /**
  242. * We keep track of the number of rows before applying the LIMIT filter that deletes some rows
  243. *
  244. * @var int
  245. */
  246. protected $rowsCountBeforeLimitFilter = 0;
  247. /**
  248. * Defaults to false for performance reasons (most of the time we don't need recursive sorting so we save a looping over the dataTable)
  249. *
  250. * @var bool
  251. */
  252. protected $enableRecursiveSort = false;
  253. /**
  254. * When the table and all subtables are loaded, this flag will be set to true to ensure filters are applied to all subtables
  255. *
  256. * @var bool
  257. */
  258. protected $enableRecursiveFilters = false;
  259. /**
  260. * @var array
  261. */
  262. protected $rowsIndexByLabel = array();
  263. /**
  264. * @var \Piwik\DataTable\Row
  265. */
  266. protected $summaryRow = null;
  267. /**
  268. * Table metadata. Read [this](#class-desc-the-basics) to learn more.
  269. *
  270. * Any data that describes the data held in the table's rows should go here.
  271. *
  272. * @var array
  273. */
  274. private $metadata = array();
  275. /**
  276. * Maximum number of rows allowed in this datatable (including the summary row).
  277. * If adding more rows is attempted, the extra rows get summed to the summary row.
  278. *
  279. * @var int
  280. */
  281. protected $maximumAllowedRows = 0;
  282. /**
  283. * Constructor. Creates an empty DataTable.
  284. */
  285. public function __construct()
  286. {
  287. // registers this instance to the manager
  288. $this->currentId = Manager::getInstance()->addTable($this);
  289. }
  290. /**
  291. * Destructor. Makes sure DataTable memory will be cleaned up.
  292. */
  293. public function __destruct()
  294. {
  295. static $depth = 0;
  296. // destruct can be called several times
  297. if ($depth < self::$maximumDepthLevelAllowed
  298. && isset($this->rows)
  299. ) {
  300. $depth++;
  301. foreach ($this->getRows() as $row) {
  302. Common::destroy($row);
  303. }
  304. unset($this->rows);
  305. Manager::getInstance()->setTableDeleted($this->getId());
  306. $depth--;
  307. }
  308. }
  309. /**
  310. * Sorts the DataTable rows using the supplied callback function.
  311. *
  312. * @param string $functionCallback A comparison callback compatible with {@link usort}.
  313. * @param string $columnSortedBy The column name `$functionCallback` sorts by. This is stored
  314. * so we can determine how the DataTable was sorted in the future.
  315. */
  316. public function sort($functionCallback, $columnSortedBy)
  317. {
  318. $this->indexNotUpToDate = true;
  319. $this->tableSortedBy = $columnSortedBy;
  320. usort($this->rows, $functionCallback);
  321. if ($this->enableRecursiveSort === true) {
  322. foreach ($this->getRows() as $row) {
  323. if (($idSubtable = $row->getIdSubDataTable()) !== null) {
  324. $table = Manager::getInstance()->getTable($idSubtable);
  325. $table->enableRecursiveSort();
  326. $table->sort($functionCallback, $columnSortedBy);
  327. }
  328. }
  329. }
  330. }
  331. /**
  332. * Returns the name of the column this table was sorted by (if any).
  333. *
  334. * See {@link sort()}.
  335. *
  336. * @return false|string The sorted column name or false if none.
  337. */
  338. public function getSortedByColumnName()
  339. {
  340. return $this->tableSortedBy;
  341. }
  342. /**
  343. * Enables recursive sorting. If this method is called {@link sort()} will also sort all
  344. * subtables.
  345. */
  346. public function enableRecursiveSort()
  347. {
  348. $this->enableRecursiveSort = true;
  349. }
  350. /**
  351. * Enables recursive filtering. If this method is called then the {@link filter()} method
  352. * will apply filters to every subtable in addition to this instance.
  353. */
  354. public function enableRecursiveFilters()
  355. {
  356. $this->enableRecursiveFilters = true;
  357. }
  358. /**
  359. * Applies a filter to this datatable.
  360. *
  361. * If {@link enableRecursiveFilters()} was called, the filter will be applied
  362. * to all subtables as well.
  363. *
  364. * @param string|Closure $className Class name, eg. `"Sort"` or "Piwik\DataTable\Filters\Sort"`. If no
  365. * namespace is supplied, `Piwik\DataTable\BaseFilter` is assumed. This parameter
  366. * can also be a closure that takes a DataTable as its first parameter.
  367. * @param array $parameters Array of extra parameters to pass to the filter.
  368. */
  369. public function filter($className, $parameters = array())
  370. {
  371. if ($className instanceof \Closure
  372. || is_array($className)
  373. ) {
  374. array_unshift($parameters, $this);
  375. call_user_func_array($className, $parameters);
  376. return;
  377. }
  378. if (!class_exists($className, true)) {
  379. $className = 'Piwik\DataTable\Filter\\' . $className;
  380. }
  381. $reflectionObj = new ReflectionClass($className);
  382. // the first parameter of a filter is the DataTable
  383. // we add the current datatable as the parameter
  384. $parameters = array_merge(array($this), $parameters);
  385. $filter = $reflectionObj->newInstanceArgs($parameters);
  386. $filter->enableRecursive($this->enableRecursiveFilters);
  387. $filter->filter($this);
  388. }
  389. /**
  390. * Adds a filter and a list of parameters to the list of queued filters. These filters will be
  391. * executed when {@link applyQueuedFilters()} is called.
  392. *
  393. * Filters that prettify the column values or don't need the full set of rows should be queued. This
  394. * way they will be run after the table is truncated which will result in better performance.
  395. *
  396. * @param string|Closure $className The class name of the filter, eg. `'Limit'`.
  397. * @param array $parameters The parameters to give to the filter, eg. `array($offset, $limit)` for the Limit filter.
  398. */
  399. public function queueFilter($className, $parameters = array())
  400. {
  401. if (!is_array($parameters)) {
  402. $parameters = array($parameters);
  403. }
  404. $this->queuedFilters[] = array('className' => $className, 'parameters' => $parameters);
  405. }
  406. /**
  407. * Applies all filters that were previously queued to the table. See {@link queueFilter()}
  408. * for more information.
  409. */
  410. public function applyQueuedFilters()
  411. {
  412. foreach ($this->queuedFilters as $filter) {
  413. $this->filter($filter['className'], $filter['parameters']);
  414. }
  415. $this->queuedFilters = array();
  416. }
  417. /**
  418. * Sums a DataTable to this one.
  419. *
  420. * This method will sum rows that have the same label. If a row is found in `$tableToSum` whose
  421. * label is not found in `$this`, the row will be added to `$this`.
  422. *
  423. * If the subtables for this table are loaded, they will be summed as well.
  424. *
  425. * Rows are summed together by summing individual columns. By default columns are summed by
  426. * adding one column value to another. Some columns cannot be aggregated this way. In these
  427. * cases, the {@link COLUMN_AGGREGATION_OPS_METADATA_NAME}
  428. * metadata can be used to specify a different type of operation.
  429. *
  430. * @param \Piwik\DataTable $tableToSum
  431. */
  432. public function addDataTable(DataTable $tableToSum, $doAggregateSubTables = true)
  433. {
  434. if($tableToSum instanceof Simple) {
  435. if($tableToSum->getRowsCount() > 1) {
  436. throw new Exception("Did not expect a Simple table with more than one row in addDataTable()");
  437. }
  438. $row = $tableToSum->getFirstRow();
  439. $this->aggregateRowFromSimpleTable($row);
  440. } else {
  441. foreach ($tableToSum->getRows() as $row) {
  442. $this->aggregateRowWithLabel($row, $doAggregateSubTables);
  443. }
  444. }
  445. }
  446. /**
  447. * Returns the Row whose `'label'` column is equal to `$label`.
  448. *
  449. * This method executes in constant time except for the first call which caches row
  450. * label => row ID mappings.
  451. *
  452. * @param string $label `'label'` column value to look for.
  453. * @return Row|false The row if found, `false` if otherwise.
  454. */
  455. public function getRowFromLabel($label)
  456. {
  457. $rowId = $this->getRowIdFromLabel($label);
  458. if ($rowId instanceof Row) {
  459. return $rowId;
  460. }
  461. if (is_int($rowId) && isset($this->rows[$rowId])) {
  462. return $this->rows[$rowId];
  463. }
  464. if ($rowId == self::ID_SUMMARY_ROW
  465. && !empty($this->summaryRow)
  466. ) {
  467. return $this->summaryRow;
  468. }
  469. return false;
  470. }
  471. /**
  472. * Returns the row id for the row whose `'label'` column is equal to `$label`.
  473. *
  474. * This method executes in constant time except for the first call which caches row
  475. * label => row ID mappings.
  476. *
  477. * @param string $label `'label'` column value to look for.
  478. * @return int The row ID.
  479. */
  480. public function getRowIdFromLabel($label)
  481. {
  482. $this->rebuildIndexContinuously = true;
  483. if ($this->indexNotUpToDate) {
  484. $this->rebuildIndex();
  485. }
  486. if ($label === self::LABEL_SUMMARY_ROW
  487. && !is_null($this->summaryRow)
  488. ) {
  489. return self::ID_SUMMARY_ROW;
  490. }
  491. $label = (string)$label;
  492. if (!isset($this->rowsIndexByLabel[$label])) {
  493. return false;
  494. }
  495. return $this->rowsIndexByLabel[$label];
  496. }
  497. /**
  498. * Returns an empty DataTable with the same metadata and queued filters as `$this` one.
  499. *
  500. * @param bool $keepFilters Whether to pass the queued filter list to the new DataTable or not.
  501. * @return DataTable
  502. */
  503. public function getEmptyClone($keepFilters = true)
  504. {
  505. $clone = new DataTable;
  506. if ($keepFilters) {
  507. $clone->queuedFilters = $this->queuedFilters;
  508. }
  509. $clone->metadata = $this->metadata;
  510. return $clone;
  511. }
  512. /**
  513. * Rebuilds the index used to lookup a row by label
  514. */
  515. private function rebuildIndex()
  516. {
  517. foreach ($this->getRows() as $id => $row) {
  518. $label = $row->getColumn('label');
  519. if ($label !== false) {
  520. $this->rowsIndexByLabel[$label] = $id;
  521. }
  522. }
  523. $this->indexNotUpToDate = false;
  524. }
  525. /**
  526. * Returns a row by ID. The ID is either the index of the row or {@link ID_SUMMARY_ROW}.
  527. *
  528. * @param int $id The row ID.
  529. * @return Row|false The Row or false if not found.
  530. */
  531. public function getRowFromId($id)
  532. {
  533. if (!isset($this->rows[$id])) {
  534. if ($id == self::ID_SUMMARY_ROW
  535. && !is_null($this->summaryRow)
  536. ) {
  537. return $this->summaryRow;
  538. }
  539. return false;
  540. }
  541. return $this->rows[$id];
  542. }
  543. /**
  544. * Returns the row that has a subtable with ID matching `$idSubtable`.
  545. *
  546. * @param int $idSubTable The subtable ID.
  547. * @return Row|false The row or false if not found
  548. */
  549. public function getRowFromIdSubDataTable($idSubTable)
  550. {
  551. $idSubTable = (int)$idSubTable;
  552. foreach ($this->rows as $row) {
  553. if ($row->getIdSubDataTable() === $idSubTable) {
  554. return $row;
  555. }
  556. }
  557. return false;
  558. }
  559. /**
  560. * Adds a row to this table.
  561. *
  562. * If {@link setMaximumAllowedRows()} was called and the current row count is
  563. * at the maximum, the new row will be summed to the summary row. If there is no summary row,
  564. * this row is set as the summary row.
  565. *
  566. * @param Row $row
  567. * @return Row `$row` or the summary row if we're at the maximum number of rows.
  568. */
  569. public function addRow(Row $row)
  570. {
  571. // if there is a upper limit on the number of allowed rows and the table is full,
  572. // add the new row to the summary row
  573. if ($this->maximumAllowedRows > 0
  574. && $this->getRowsCount() >= $this->maximumAllowedRows - 1
  575. ) {
  576. if ($this->summaryRow === null) // create the summary row if necessary
  577. {
  578. $columns = array('label' => self::LABEL_SUMMARY_ROW) + $row->getColumns();
  579. $this->addSummaryRow(new Row(array(Row::COLUMNS => $columns)));
  580. } else {
  581. $this->summaryRow->sumRow(
  582. $row, $enableCopyMetadata = false, $this->getMetadata(self::COLUMN_AGGREGATION_OPS_METADATA_NAME));
  583. }
  584. return $this->summaryRow;
  585. }
  586. $this->rows[] = $row;
  587. if (!$this->indexNotUpToDate
  588. && $this->rebuildIndexContinuously
  589. ) {
  590. $label = $row->getColumn('label');
  591. if ($label !== false) {
  592. $this->rowsIndexByLabel[$label] = count($this->rows) - 1;
  593. }
  594. }
  595. return $row;
  596. }
  597. /**
  598. * Sets the summary row.
  599. *
  600. * _Note: A DataTable can have only one summary row._
  601. *
  602. * @param Row $row
  603. * @return Row Returns `$row`.
  604. */
  605. public function addSummaryRow(Row $row)
  606. {
  607. $this->summaryRow = $row;
  608. // add summary row to index
  609. if (!$this->indexNotUpToDate
  610. && $this->rebuildIndexContinuously
  611. ) {
  612. $label = $row->getColumn('label');
  613. if ($label !== false) {
  614. $this->rowsIndexByLabel[$label] = self::ID_SUMMARY_ROW;
  615. }
  616. }
  617. return $row;
  618. }
  619. /**
  620. * Returns the DataTable ID.
  621. *
  622. * @return int
  623. */
  624. public function getId()
  625. {
  626. return $this->currentId;
  627. }
  628. /**
  629. * Adds a new row from an array.
  630. *
  631. * You can add row metadata with this method.
  632. *
  633. * @param array $row eg. `array(Row::COLUMNS => array('visits' => 13, 'test' => 'toto'),
  634. * Row::METADATA => array('mymetadata' => 'myvalue'))`
  635. */
  636. public function addRowFromArray($row)
  637. {
  638. $this->addRowsFromArray(array($row));
  639. }
  640. /**
  641. * Adds a new row a from an array of column values.
  642. *
  643. * Row metadata cannot be added with this method.
  644. *
  645. * @param array $row eg. `array('name' => 'google analytics', 'license' => 'commercial')`
  646. */
  647. public function addRowFromSimpleArray($row)
  648. {
  649. $this->addRowsFromSimpleArray(array($row));
  650. }
  651. /**
  652. * Returns the array of Rows.
  653. *
  654. * @return Row[]
  655. */
  656. public function getRows()
  657. {
  658. if (is_null($this->summaryRow)) {
  659. return $this->rows;
  660. } else {
  661. return $this->rows + array(self::ID_SUMMARY_ROW => $this->summaryRow);
  662. }
  663. }
  664. /**
  665. * Returns an array containing all column values for the requested column.
  666. *
  667. * @param string $name The column name.
  668. * @return array The array of column values.
  669. */
  670. public function getColumn($name)
  671. {
  672. $columnValues = array();
  673. foreach ($this->getRows() as $row) {
  674. $columnValues[] = $row->getColumn($name);
  675. }
  676. return $columnValues;
  677. }
  678. /**
  679. * Returns an array containing all column values of columns whose name starts with `$name`.
  680. *
  681. * @param $namePrefix The column name prefix.
  682. * @return array The array of column values.
  683. */
  684. public function getColumnsStartingWith($namePrefix)
  685. {
  686. $columnValues = array();
  687. foreach ($this->getRows() as $row) {
  688. $columns = $row->getColumns();
  689. foreach ($columns as $column => $value) {
  690. if (strpos($column, $namePrefix) === 0) {
  691. $columnValues[] = $row->getColumn($column);
  692. }
  693. }
  694. }
  695. return $columnValues;
  696. }
  697. /**
  698. * Returns the names of every column this DataTable contains. This method will return the
  699. * columns of the first row with data and will assume they occur in every other row as well.
  700. *
  701. *_ Note: If column names still use their in-database INDEX values (@see Metrics), they
  702. * will be converted to their string name in the array result._
  703. *
  704. * @return array Array of string column names.
  705. */
  706. public function getColumns()
  707. {
  708. $result = array();
  709. foreach ($this->getRows() as $row) {
  710. $columns = $row->getColumns();
  711. if (!empty($columns)) {
  712. $result = array_keys($columns);
  713. break;
  714. }
  715. }
  716. // make sure column names are not DB index values
  717. foreach ($result as &$column) {
  718. if (isset(Metrics::$mappingFromIdToName[$column])) {
  719. $column = Metrics::$mappingFromIdToName[$column];
  720. }
  721. }
  722. return $result;
  723. }
  724. /**
  725. * Returns an array containing the requested metadata value of each row.
  726. *
  727. * @param string $name The metadata column to return.
  728. * @return array
  729. */
  730. public function getRowsMetadata($name)
  731. {
  732. $metadataValues = array();
  733. foreach ($this->getRows() as $row) {
  734. $metadataValues[] = $row->getMetadata($name);
  735. }
  736. return $metadataValues;
  737. }
  738. /**
  739. * Returns the number of rows in the table including the summary row.
  740. *
  741. * @return int
  742. */
  743. public function getRowsCount()
  744. {
  745. if (is_null($this->summaryRow)) {
  746. return count($this->rows);
  747. } else {
  748. return count($this->rows) + 1;
  749. }
  750. }
  751. /**
  752. * Returns the first row of the DataTable.
  753. *
  754. * @return Row|false The first row or `false` if it cannot be found.
  755. */
  756. public function getFirstRow()
  757. {
  758. if (count($this->rows) == 0) {
  759. if (!is_null($this->summaryRow)) {
  760. return $this->summaryRow;
  761. }
  762. return false;
  763. }
  764. return reset($this->rows);
  765. }
  766. /**
  767. * Returns the last row of the DataTable. If there is a summary row, it
  768. * will always be considered the last row.
  769. *
  770. * @return Row|false The last row or `false` if it cannot be found.
  771. */
  772. public function getLastRow()
  773. {
  774. if (!is_null($this->summaryRow)) {
  775. return $this->summaryRow;
  776. }
  777. if (count($this->rows) == 0) {
  778. return false;
  779. }
  780. return end($this->rows);
  781. }
  782. /**
  783. * Returns the number of rows in the entire DataTable hierarchy. This is the number of rows in this DataTable
  784. * summed with the row count of each descendant subtable.
  785. *
  786. * @return int
  787. */
  788. public function getRowsCountRecursive()
  789. {
  790. $totalCount = 0;
  791. foreach ($this->rows as $row) {
  792. if (($idSubTable = $row->getIdSubDataTable()) !== null) {
  793. $subTable = Manager::getInstance()->getTable($idSubTable);
  794. $count = $subTable->getRowsCountRecursive();
  795. $totalCount += $count;
  796. }
  797. }
  798. $totalCount += $this->getRowsCount();
  799. return $totalCount;
  800. }
  801. /**
  802. * Delete a column by name in every row. This change is NOT applied recursively to all
  803. * subtables.
  804. *
  805. * @param string $name Column name to delete.
  806. */
  807. public function deleteColumn($name)
  808. {
  809. $this->deleteColumns(array($name));
  810. }
  811. public function __sleep()
  812. {
  813. return array('rows', 'summaryRow');
  814. }
  815. /**
  816. * Rename a column in every row. This change is applied recursively to all subtables.
  817. *
  818. * @param string $oldName Old column name.
  819. * @param string $newName New column name.
  820. */
  821. public function renameColumn($oldName, $newName, $doRenameColumnsOfSubTables = true)
  822. {
  823. foreach ($this->getRows() as $row) {
  824. $row->renameColumn($oldName, $newName);
  825. if($doRenameColumnsOfSubTables) {
  826. if (($idSubDataTable = $row->getIdSubDataTable()) !== null) {
  827. Manager::getInstance()->getTable($idSubDataTable)->renameColumn($oldName, $newName);
  828. }
  829. }
  830. }
  831. if (!is_null($this->summaryRow)) {
  832. $this->summaryRow->renameColumn($oldName, $newName);
  833. }
  834. }
  835. /**
  836. * Deletes several columns by name in every row.
  837. *
  838. * @param array $names List of column names to delete.
  839. * @param bool $deleteRecursiveInSubtables Whether to apply this change to all subtables or not.
  840. */
  841. public function deleteColumns($names, $deleteRecursiveInSubtables = false)
  842. {
  843. foreach ($this->getRows() as $row) {
  844. foreach ($names as $name) {
  845. $row->deleteColumn($name);
  846. }
  847. if (($idSubDataTable = $row->getIdSubDataTable()) !== null) {
  848. Manager::getInstance()->getTable($idSubDataTable)->deleteColumns($names, $deleteRecursiveInSubtables);
  849. }
  850. }
  851. if (!is_null($this->summaryRow)) {
  852. foreach ($names as $name) {
  853. $this->summaryRow->deleteColumn($name);
  854. }
  855. }
  856. }
  857. /**
  858. * Deletes a row by ID.
  859. *
  860. * @param int $id The row ID.
  861. * @throws Exception If the row `$id` cannot be found.
  862. */
  863. public function deleteRow($id)
  864. {
  865. if ($id === self::ID_SUMMARY_ROW) {
  866. $this->summaryRow = null;
  867. return;
  868. }
  869. if (!isset($this->rows[$id])) {
  870. throw new Exception("Trying to delete unknown row with idkey = $id");
  871. }
  872. unset($this->rows[$id]);
  873. }
  874. /**
  875. * Deletes rows from `$offset` to `$offset + $limit`.
  876. *
  877. * @param int $offset The offset to start deleting rows from.
  878. * @param int|null $limit The number of rows to delete. If `null` all rows after the offset
  879. * will be removed.
  880. * @return int The number of rows deleted.
  881. */
  882. public function deleteRowsOffset($offset, $limit = null)
  883. {
  884. if ($limit === 0) {
  885. return 0;
  886. }
  887. $count = $this->getRowsCount();
  888. if ($offset >= $count) {
  889. return 0;
  890. }
  891. // if we delete until the end, we delete the summary row as well
  892. if (is_null($limit)
  893. || $limit >= $count
  894. ) {
  895. $this->summaryRow = null;
  896. }
  897. if (is_null($limit)) {
  898. $spliced = array_splice($this->rows, $offset);
  899. } else {
  900. $spliced = array_splice($this->rows, $offset, $limit);
  901. }
  902. $countDeleted = count($spliced);
  903. return $countDeleted;
  904. }
  905. /**
  906. * Deletes a set of rows by ID.
  907. *
  908. * @param array $rowIds The list of row IDs to delete.
  909. * @throws Exception If a row ID cannot be found.
  910. */
  911. public function deleteRows(array $rowIds)
  912. {
  913. foreach ($rowIds as $key) {
  914. $this->deleteRow($key);
  915. }
  916. }
  917. /**
  918. * Returns a string representation of this DataTable for convenient viewing.
  919. *
  920. * _Note: This uses the **html** DataTable renderer._
  921. *
  922. * @return string
  923. */
  924. public function __toString()
  925. {
  926. $renderer = new Html();
  927. $renderer->setTable($this);
  928. return (string)$renderer;
  929. }
  930. /**
  931. * Returns true if both DataTable instances are exactly the same.
  932. *
  933. * DataTables are equal if they have the same number of rows, if
  934. * each row has a label that exists in the other table, and if each row
  935. * is equal to the row in the other table with the same label. The order
  936. * of rows is not important.
  937. *
  938. * @param \Piwik\DataTable $table1
  939. * @param \Piwik\DataTable $table2
  940. * @return bool
  941. */
  942. public static function isEqual(DataTable $table1, DataTable $table2)
  943. {
  944. $rows1 = $table1->getRows();
  945. $rows2 = $table2->getRows();
  946. $table1->rebuildIndex();
  947. $table2->rebuildIndex();
  948. if ($table1->getRowsCount() != $table2->getRowsCount()) {
  949. return false;
  950. }
  951. foreach ($rows1 as $row1) {
  952. $row2 = $table2->getRowFromLabel($row1->getColumn('label'));
  953. if ($row2 === false
  954. || !Row::isEqual($row1, $row2)
  955. ) {
  956. return false;
  957. }
  958. }
  959. return true;
  960. }
  961. /**
  962. * Serializes an entire DataTable hierarchy and returns the array of serialized DataTables.
  963. *
  964. * The first element in the returned array will be the serialized representation of this DataTable.
  965. * Every subsequent element will be a serialized subtable.
  966. *
  967. * This DataTable and subtables can optionally be truncated before being serialized. In most
  968. * cases where DataTables can become quite large, they should be truncated before being persisted
  969. * in an archive.
  970. *
  971. * The result of this method is intended for use with the {@link ArchiveProcessor::insertBlobRecord()} method.
  972. *
  973. * @throws Exception If infinite recursion detected. This will occur if a table's subtable is one of its parent tables.
  974. * @param int $maximumRowsInDataTable If not null, defines the maximum number of rows allowed in the serialized DataTable.
  975. * @param int $maximumRowsInSubDataTable If not null, defines the maximum number of rows allowed in serialized subtables.
  976. * @param string $columnToSortByBeforeTruncation The column to sort by before truncating, eg, `Metrics::INDEX_NB_VISITS`.
  977. * @return array The array of serialized DataTables:
  978. *
  979. * array(
  980. * // this DataTable (the root)
  981. * 0 => 'eghuighahgaueytae78yaet7yaetae',
  982. *
  983. * // a subtable
  984. * 1 => 'gaegae gh gwrh guiwh uigwhuige',
  985. *
  986. * // another subtable
  987. * 2 => 'gqegJHUIGHEQjkgneqjgnqeugUGEQHGUHQE',
  988. *
  989. * // etc.
  990. * );
  991. */
  992. public function getSerialized($maximumRowsInDataTable = null,
  993. $maximumRowsInSubDataTable = null,
  994. $columnToSortByBeforeTruncation = null)
  995. {
  996. static $depth = 0;
  997. if ($depth > self::$maximumDepthLevelAllowed) {
  998. $depth = 0;
  999. throw new Exception("Maximum recursion level of " . self::$maximumDepthLevelAllowed . " reached. Maybe you have set a DataTable\Row with an associated DataTable belonging already to one of its parent tables?");
  1000. }
  1001. if (!is_null($maximumRowsInDataTable)) {
  1002. $this->filter('Truncate',
  1003. array($maximumRowsInDataTable - 1,
  1004. DataTable::LABEL_SUMMARY_ROW,
  1005. $columnToSortByBeforeTruncation,
  1006. $filterRecursive = false)
  1007. );
  1008. }
  1009. // For each row, get the serialized row
  1010. // If it is associated to a sub table, get the serialized table recursively ;
  1011. // but returns all serialized tables and subtable in an array of 1 dimension
  1012. $aSerializedDataTable = array();
  1013. foreach ($this->rows as $row) {
  1014. if (($idSubTable = $row->getIdSubDataTable()) !== null) {
  1015. $subTable = null;
  1016. try {
  1017. $subTable = Manager::getInstance()->getTable($idSubTable);
  1018. } catch(TableNotFoundException $e) {
  1019. // This occurs is an unknown & random data issue. Catch Exception and remove subtable from the row.
  1020. $row->removeSubtable();
  1021. // Go to next row
  1022. continue;
  1023. }
  1024. $depth++;
  1025. $aSerializedDataTable = $aSerializedDataTable + $subTable->getSerialized($maximumRowsInSubDataTable, $maximumRowsInSubDataTable, $columnToSortByBeforeTruncation);
  1026. $depth--;
  1027. }
  1028. }
  1029. // we load the current Id of the DataTable
  1030. $forcedId = $this->getId();
  1031. // if the datatable is the parent we force the Id at 0 (this is part of the specification)
  1032. if ($depth == 0) {
  1033. $forcedId = 0;
  1034. }
  1035. // we then serialize the rows and store them in the serialized dataTable
  1036. $addToRows = array(self::ID_SUMMARY_ROW => $this->summaryRow);
  1037. $aSerializedDataTable[$forcedId] = serialize($this->rows + $addToRows);
  1038. foreach ($this->rows as &$row) {
  1039. $row->cleanPostSerialize();
  1040. }
  1041. return $aSerializedDataTable;
  1042. }
  1043. /**
  1044. * Adds a set of rows from a serialized DataTable string.
  1045. *
  1046. * See {@link serialize()}.
  1047. *
  1048. * _Note: This function will successfully load DataTables serialized by Piwik 1.X._
  1049. *
  1050. * @param string $stringSerialized A string with the format of a string in the array returned by
  1051. * {@link serialize()}.
  1052. * @throws Exception if `$stringSerialized` is invalid.
  1053. */
  1054. public function addRowsFromSerializedArray($stringSerialized)
  1055. {
  1056. require_once PIWIK_INCLUDE_PATH . "/core/DataTable/Bridges.php";
  1057. $serialized = unserialize($stringSerialized);
  1058. if ($serialized === false) {
  1059. throw new Exception("The unserialization has failed!");
  1060. }
  1061. $this->addRowsFromArray($serialized);
  1062. }
  1063. /**
  1064. * Adds multiple rows from an array.
  1065. *
  1066. * You can add row metadata with this method.
  1067. *
  1068. * @param array $array Array with the following structure
  1069. *
  1070. * array(
  1071. * // row1
  1072. * array(
  1073. * Row::COLUMNS => array( col1_name => value1, col2_name => value2, ...),
  1074. * Row::METADATA => array( metadata1_name => value1, ...), // see Row
  1075. * ),
  1076. * // row2
  1077. * array( ... ),
  1078. * )
  1079. */
  1080. public function addRowsFromArray($array)
  1081. {
  1082. foreach ($array as $id => $row) {
  1083. if (is_array($row)) {
  1084. $row = new Row($row);
  1085. }
  1086. if ($id == self::ID_SUMMARY_ROW) {
  1087. $this->summaryRow = $row;
  1088. } else {
  1089. $this->addRow($row);
  1090. }
  1091. }
  1092. }
  1093. /**
  1094. * Adds multiple rows from an array containing arrays of column values.
  1095. *
  1096. * Row metadata cannot be added with this method.
  1097. *
  1098. * @param array $array Array with the following structure:
  1099. *
  1100. * array(
  1101. * array( col1_name => valueA, col2_name => valueC, ...),
  1102. * array( col1_name => valueB, col2_name => valueD, ...),
  1103. * )
  1104. * @throws Exception if `$array` is in an incorrect format.
  1105. */
  1106. public function addRowsFromSimpleArray($array)
  1107. {
  1108. if (count($array) === 0) {
  1109. return;
  1110. }
  1111. // we define an exception we may throw if at one point we notice that we cannot handle the data structure
  1112. $e = new Exception(" Data structure returned is not convertible in the requested format." .
  1113. " Try to call this method with the parameters '&format=original&serialize=1'" .
  1114. "; you will get the original php data structure serialized." .
  1115. " The data structure looks like this: \n \$data = " . var_export($array, true) . "; ");
  1116. // first pass to see if the array has the structure
  1117. // array(col1_name => val1, col2_name => val2, etc.)
  1118. // with val* that are never arrays (only strings/numbers/bool/etc.)
  1119. // if we detect such a "simple" data structure we convert it to a row with the correct columns' names
  1120. $thisIsNotThatSimple = false;
  1121. foreach ($array as $columnValue) {
  1122. if (is_array($columnValue) || is_object($columnValue)) {
  1123. $thisIsNotThatSimple = true;
  1124. break;
  1125. }
  1126. }
  1127. if ($thisIsNotThatSimple === false) {
  1128. // case when the array is indexed by the default numeric index
  1129. if (array_keys($array) == array_keys(array_fill(0, count($array), true))) {
  1130. foreach ($array as $row) {
  1131. $this->addRow(new Row(array(Row::COLUMNS => array($row))));
  1132. }
  1133. } else {
  1134. $this->addRow(new Row(array(Row::COLUMNS => $array)));
  1135. }
  1136. // we have converted our simple array to one single row
  1137. // => we exit the method as the job is now finished
  1138. return;
  1139. }
  1140. foreach ($array as $key => $row) {
  1141. // stuff that looks like a line
  1142. if (is_array($row)) {
  1143. /**
  1144. * We make sure we can convert this PHP array without losing information.
  1145. * We are able to convert only simple php array (no strings keys, no sub arrays, etc.)
  1146. *
  1147. */
  1148. // if the key is a string it means that some information was contained in this key.
  1149. // it cannot be lost during the conversion. Because we are not able to handle properly
  1150. // this key, we throw an explicit exception.
  1151. if (is_string($key)) {
  1152. throw $e;
  1153. }
  1154. // if any of the sub elements of row is an array we cannot handle this data structure...
  1155. foreach ($row as $subRow) {
  1156. if (is_array($subRow)) {
  1157. throw $e;
  1158. }
  1159. }
  1160. $row = new Row(array(Row::COLUMNS => $row));
  1161. } // other (string, numbers...) => we build a line from this value
  1162. else {
  1163. $row = new Row(array(Row::COLUMNS => array($key => $row)));
  1164. }
  1165. $this->addRow($row);
  1166. }
  1167. }
  1168. /**
  1169. * Rewrites the input `$array`
  1170. *
  1171. * array (
  1172. * LABEL => array(col1 => X, col2 => Y),
  1173. * LABEL2 => array(col1 => X, col2 => Y),
  1174. * )
  1175. *
  1176. * to a DataTable with rows that look like:
  1177. *
  1178. * array (
  1179. * array( Row::COLUMNS => array('label' => LABEL, col1 => X, col2 => Y)),
  1180. * array( Row::COLUMNS => array('label' => LABEL2, col1 => X, col2 => Y)),
  1181. * )
  1182. *
  1183. * Will also convert arrays like:
  1184. *
  1185. * array (
  1186. * LABEL => X,
  1187. * LABEL2 => Y,
  1188. * )
  1189. *
  1190. * to:
  1191. *
  1192. * array (
  1193. * array( Row::COLUMNS => array('label' => LABEL, 'value' => X)),
  1194. * array( Row::COLUMNS => array('label' => LABEL2, 'value' => Y)),
  1195. * )
  1196. *
  1197. * @param array $array Indexed array, two formats supported, see above.
  1198. * @param array|null $subtablePerLabel An array mapping label values with DataTable instances to associate as a subtable.
  1199. * @return \Piwik\DataTable
  1200. */
  1201. public static function makeFromIndexedArray($array, $subtablePerLabel = null)
  1202. {
  1203. $table = new DataTable();
  1204. foreach ($array as $label => $row) {
  1205. $cleanRow = array();
  1206. // Support the case of an $array of single values
  1207. if (!is_array($row)) {
  1208. $row = array('value' => $row);
  1209. }
  1210. // Put the 'label' column first
  1211. $cleanRow[Row::COLUMNS] = array('label' => $label) + $row;
  1212. // Assign subtable if specified
  1213. if (isset($subtablePerLabel[$label])) {
  1214. $cleanRow[Row::DATATABLE_ASSOCIATED] = $subtablePerLabel[$label];
  1215. }
  1216. $table->addRow(new Row($cleanRow));
  1217. }
  1218. return $table;
  1219. }
  1220. /**
  1221. * Sets the maximum depth level to at least a certain value. If the current value is
  1222. * greater than `$atLeastLevel`, the maximum nesting level is not changed.
  1223. *
  1224. * The maximum depth level determines the maximum number of subtable levels in the
  1225. * DataTable tree. For example, if it is set to `2`, this DataTable is allowed to
  1226. * have subtables, but the subtables are not.
  1227. *
  1228. * @param int $atLeastLevel
  1229. */
  1230. public static function setMaximumDepthLevelAllowedAtLeast($atLeastLevel)
  1231. {
  1232. self::$maximumDepthLevelAllowed = max($atLeastLevel, self::$maximumDepthLevelAllowed);
  1233. if (self::$maximumDepthLevelAllowed < 1) {
  1234. self::$maximumDepthLevelAllowed = 1;
  1235. }
  1236. }
  1237. /**
  1238. * Returns metadata by name.
  1239. *
  1240. * @param string $name The metadata name.
  1241. * @return mixed|false The metadata value or `false` if it cannot be found.
  1242. */
  1243. public function getMetadata($name)
  1244. {
  1245. if (!isset($this->metadata[$name])) {
  1246. return false;
  1247. }
  1248. return $this->metadata[$name];
  1249. }
  1250. /**
  1251. * Sets a metadata value by name.
  1252. *
  1253. * @param string $name The metadata name.
  1254. * @param mixed $value
  1255. */
  1256. public function setMetadata($name, $value)
  1257. {
  1258. $this->metadata[$name] = $value;
  1259. }
  1260. /**
  1261. * Returns all table metadata.
  1262. *
  1263. * @return array
  1264. */
  1265. public function getAllTableMetadata()
  1266. {
  1267. return $this->metadata;
  1268. }
  1269. /**
  1270. * Sets several metadata values by name.
  1271. *
  1272. * @param array $values Array mapping metadata names with metadata values.
  1273. */
  1274. public function setMetadataValues($values)
  1275. {
  1276. foreach ($values as $name => $value) {
  1277. $this->metadata[$name] = $value;
  1278. }
  1279. }
  1280. /**
  1281. * Sets metadata, erasing existing values.
  1282. *
  1283. * @param array $values Array mapping metadata names with metadata values.
  1284. */
  1285. public function setAllTableMetadata($metadata)
  1286. {
  1287. $this->metadata = $metadata;
  1288. }
  1289. /**
  1290. * Sets the maximum number of rows allowed in this datatable (including the summary
  1291. * row). If adding more then the allowed number of rows is attempted, the extra
  1292. * rows are summed to the summary row.
  1293. *
  1294. * @param int $maximumAllowedRows If `0`, the maximum number of rows is unset.
  1295. */
  1296. public function setMaximumAllowedRows($maximumAllowedRows)
  1297. {
  1298. $this->maximumAllowedRows = $maximumAllowedRows;
  1299. }
  1300. /**
  1301. * Traverses a DataTable tree using an array of labels and returns the row
  1302. * it finds or `false` if it cannot find one. The number of path segments that
  1303. * were successfully walked is also returned.
  1304. *
  1305. * If `$missingRowColumns` is supplied, the specified path is created. When
  1306. * a subtable is encountered w/o the required label, a new row is created
  1307. * with the label, and a new subtable is added to the row.
  1308. *
  1309. * Read [http://en.wikipedia.org/wiki/Tree_(data_structure)#Traversal_methods](http://en.wikipedia.org/wiki/Tree_(data_structure)#Traversal_methods)
  1310. * for more information about tree walking.
  1311. *
  1312. * @param array $path The path to walk. An array of label values. The first element
  1313. * refers to a row in this DataTable, the second in a subtable of
  1314. * the first row, the third a subtable of the second row, etc.
  1315. * @param array|bool $missingRowColumns The default columns to use when creating new rows.
  1316. * If this parameter is supplied, new rows will be
  1317. * created for path labels that cannot be found.
  1318. * @param int $maxSubtableRows The maximum number of allowed rows in new subtables. New
  1319. * subtables are only created if `$missingRowColumns` is provided.
  1320. * @return array First element is the found row or `false`. Second element is
  1321. * the number of path segments walked. If a row is found, this
  1322. * will be == to `count($path)`. Otherwise, it will be the index
  1323. * of the path segment that we could not find.
  1324. */
  1325. public function walkPath($path, $missingRowColumns = false, $maxSubtableRows = 0)
  1326. {
  1327. $pathLength = count($path);
  1328. $table = $this;
  1329. $next = false;
  1330. for ($i = 0; $i < $pathLength; ++$i) {
  1331. $segment = $path[$i];
  1332. $next = $table->getRowFromLabel($segment);
  1333. if ($next === false) {
  1334. // if there is no table to advance to, and we're not adding missing rows, return false
  1335. if ($missingRowColumns === false) {
  1336. return array(false, $i);
  1337. } else // if we're adding missing rows, add a new row
  1338. {
  1339. $row = new DataTableSummaryRow();
  1340. $row->setColumns(array('label' => $segment) + $missingRowColumns);
  1341. $next = $table->addRow($row);
  1342. if ($next !== $row) // if the row wasn't added, the table is full
  1343. {
  1344. // Summary row, has no metadata
  1345. $next->deleteMetadata();
  1346. return array($next, $i);
  1347. }
  1348. }
  1349. }
  1350. $table = $next->getSubtable();
  1351. if ($table === false) {
  1352. // if the row has no table (and thus no child rows), and we're not adding
  1353. // missing rows, return false
  1354. if ($missingRowColumns === false) {
  1355. return array(false, $i);
  1356. } else if ($i != $pathLength - 1) // create subtable if missing, but only if not on the last segment
  1357. {
  1358. $table = new DataTable();
  1359. $table->setMaximumAllowedRows($maxSubtableRows);
  1360. $table->metadata[self::COLUMN_AGGREGATION_OPS_METADATA_NAME]
  1361. = $this->getMetadata(self::COLUMN_AGGREGATION_OPS_METADATA_NAME);
  1362. $next->setSubtable($table);
  1363. // Summary row, has no metadata
  1364. $next->deleteMetadata();
  1365. }
  1366. }
  1367. }
  1368. return array($next, $i);
  1369. }
  1370. /**
  1371. * Returns a new DataTable in which the rows of this table are replaced with the aggregatated rows of all its subtables.
  1372. *
  1373. * @param string|bool $labelColumn If supplied the label of the parent row will be added to
  1374. * a new column in each subtable row.
  1375. *
  1376. * If set to, `'label'` each subtable row's label will be prepended
  1377. * w/ the parent row's label. So `'child_label'` becomes
  1378. * `'parent_label - child_label'`.
  1379. * @param bool $useMetadataColumn If true and if `$labelColumn` is supplied, the parent row's
  1380. * label will be added as metadata and not a new column.
  1381. * @return \Piwik\DataTable
  1382. */
  1383. public function mergeSubtables($labelColumn = false, $useMetadataColumn = false)
  1384. {
  1385. $result = new DataTable();
  1386. foreach ($this->getRows() as $row) {
  1387. $subtable = $row->getSubtable();
  1388. if ($subtable !== false) {
  1389. $parentLabel = $row->getColumn('label');
  1390. // add a copy of each subtable row to the new datatable
  1391. foreach ($subtable->getRows() as $id => $subRow) {
  1392. $copy = clone $subRow;
  1393. // if the summary row, add it to the existing summary row (or add a new one)
  1394. if ($id == self::ID_SUMMARY_ROW) {
  1395. $existing = $result->getRowFromId(self::ID_SUMMARY_ROW);
  1396. if ($existing === false) {
  1397. $result->addSummaryRow($copy);
  1398. } else {
  1399. $existing->sumRow($copy, $copyMeta = true, $this->getMetadata(self::COLUMN_AGGREGATION_OPS_METADATA_NAME));
  1400. }
  1401. } else {
  1402. if ($labelColumn !== false) {
  1403. // if we're modifying the subtable's rows' label column, then we make
  1404. // sure to prepend the existing label w/ the parent row's label. otherwise
  1405. // we're just adding the parent row's label as a new column/metadata.
  1406. $newLabel = $parentLabel;
  1407. if ($labelColumn == 'label') {
  1408. $newLabel .= ' - ' . $copy->getColumn('label');
  1409. }
  1410. // modify the child row's label or add new column/metadata
  1411. if ($useMetadataColumn) {
  1412. $copy->setMetadata($labelColumn, $newLabel);
  1413. } else {
  1414. $copy->setColumn($labelColumn, $newLabel);
  1415. }
  1416. }
  1417. $result->addRow($copy);
  1418. }
  1419. }
  1420. }
  1421. }
  1422. return $result;
  1423. }
  1424. /**
  1425. * Returns a new DataTable created with data from a 'simple' array.
  1426. *
  1427. * See {@link addRowsFromSimpleArray()}.
  1428. *
  1429. * @param array $array
  1430. * @return \Piwik\DataTable
  1431. */
  1432. public static function makeFromSimpleArray($array)
  1433. {
  1434. $dataTable = new DataTable();
  1435. $dataTable->addRowsFromSimpleArray($array);
  1436. return $dataTable;
  1437. }
  1438. /**
  1439. * Creates a new DataTable instance from a serialized DataTable string.
  1440. *
  1441. * See {@link getSerialized()} and {@link addRowsFromSerializedArray()}
  1442. * for more information on DataTable serialization.
  1443. *
  1444. * @param string $data
  1445. * @return \Piwik\DataTable
  1446. */
  1447. public static function fromSerializedArray($data)
  1448. {
  1449. $result = new DataTable();
  1450. $result->addRowsFromSerializedArray($data);
  1451. return $result;
  1452. }
  1453. /**
  1454. * Aggregates the $row columns to this table.
  1455. *
  1456. * $row must have a column "label". The $row will be summed to this table's row with the same label.
  1457. *
  1458. * @param $row
  1459. * @throws \Exception
  1460. */
  1461. protected function aggregateRowWithLabel(Row $row, $doAggregateSubTables = true)
  1462. {
  1463. $labelToLookFor = $row->getColumn('label');
  1464. if ($labelToLookFor === false) {
  1465. throw new Exception("Label column not found in the table to add in addDataTable()");
  1466. }
  1467. $rowFound = $this->getRowFromLabel($labelToLookFor);
  1468. if ($rowFound === false) {
  1469. if ($labelToLookFor === self::LABEL_SUMMARY_ROW) {
  1470. $this->addSummaryRow($row);
  1471. } else {
  1472. $this->addRow($row);
  1473. }
  1474. } else {
  1475. $rowFound->sumRow($row, $copyMeta = true, $this->getMetadata(self::COLUMN_AGGREGATION_OPS_METADATA_NAME));
  1476. if($doAggregateSubTables) {
  1477. // if the row to add has a subtable whereas the current row doesn't
  1478. // we simply add it (cloning the subtable)
  1479. // if the row has the subtable already
  1480. // then we have to recursively sum the subtables
  1481. if (($idSubTable = $row->getIdSubDataTable()) !== null) {
  1482. $subTable = Manager::getInstance()->getTable($idSubTable);
  1483. $subTable->metadata[self::COLUMN_AGGREGATION_OPS_METADATA_NAME]
  1484. = $this->getMetadata(self::COLUMN_AGGREGATION_OPS_METADATA_NAME);
  1485. $rowFound->sumSubtable($subTable);
  1486. }
  1487. }
  1488. }
  1489. }
  1490. /**
  1491. * @param $row
  1492. */
  1493. protected function aggregateRowFromSimpleTable($row)
  1494. {
  1495. if ($row === false) {
  1496. return;
  1497. }
  1498. $thisRow = $this->getFirstRow();
  1499. if ($thisRow === false) {
  1500. $thisRow = new Row;
  1501. $this->addRow($thisRow);
  1502. }
  1503. $thisRow->sumRow($row, $copyMeta = true, $this->getMetadata(self::COLUMN_AGGREGATION_OPS_METADATA_NAME));
  1504. }
  1505. }