~xibo-maintainers/xibo/tempel

« back to all changes in this revision

Viewing changes to lib/data/datasetdata.data.class.php

  • Committer: Dan Garner
  • Date: 2015-03-26 14:08:33 UTC
  • Revision ID: git-v1:70d14044444f8dc5d602b99890d59dea46d9470c
Moved web servable files to web folder

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<?php
 
2
/*
 
3
 * Xibo - Digital Signage - http://www.xibo.org.uk
 
4
 * Copyright (C) 2011-13 Daniel Garner
 
5
 *
 
6
 * This file is part of Xibo.
 
7
 *
 
8
 * Xibo is free software: you can redistribute it and/or modify
 
9
 * it under the terms of the GNU Affero General Public License as published by
 
10
 * the Free Software Foundation, either version 3 of the License, or
 
11
 * any later version.
 
12
 *
 
13
 * Xibo is distributed in the hope that it will be useful,
 
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
16
 * GNU Affero General Public License for more details.
 
17
 *
 
18
 * You should have received a copy of the GNU Affero General Public License
 
19
 * along with Xibo.  If not, see <http://www.gnu.org/licenses/>.
 
20
 */
 
21
use Xibo\Helper\Log;
 
22
 
 
23
defined('XIBO') or die("Sorry, you are not allowed to directly access this page.<br /> Please press the back button in your browser.");
 
24
 
 
25
class DataSetData extends Data
 
26
{
 
27
    private $updateWatermark;
 
28
 
 
29
    public function __construct() {
 
30
 
 
31
        $this->updateWatermark = true;
 
32
 
 
33
        parent::__construct();
 
34
    }
 
35
 
 
36
    /**
 
37
     * List all data for this dataset
 
38
     * @param int $dataSetId The DataSet ID
 
39
     */
 
40
    public function GetData($dataSetId) {
 
41
 
 
42
        if ($dataSetId == 0 || $dataSetId == '')
 
43
            return $this->SetError(25001, __('Missing dataSetId'));
 
44
 
 
45
        try {
 
46
            $dbh = \Xibo\Storage\PDOConnect::init();
 
47
        
 
48
            $sth = $dbh->prepare('SELECT datasetdata.DataSetColumnID, datasetdata.RowNumber, datasetdata.Value 
 
49
                  FROM datasetdata
 
50
                    INNER JOIN datasetcolumn
 
51
                    ON datasetcolumn.DataSetColumnID = datasetdata.DataSetColumnID
 
52
                 WHERE datasetcolumn.DataSetID = :dataset_id');
 
53
 
 
54
            $sth->execute(array('dataset_id' => $dataSetId));
 
55
 
 
56
            $results = $sth->fetchAll();
 
57
 
 
58
            // Check there are some columns returned
 
59
            if (count($results) <= 0)
 
60
                $this->ThrowError(__('No data'));
 
61
 
 
62
            $rows = array();
 
63
 
 
64
            foreach($results as $row) {
 
65
 
 
66
                $col['datasetcolumnid'] = \Xibo\Helper\Sanitize::int($row['DataSetColumnID']);
 
67
                $col['rownumber'] = \Xibo\Helper\Sanitize::int($row['RowNumber']);
 
68
                $col['value'] = \Xibo\Helper\Sanitize::string($row['Value']);
 
69
 
 
70
                $rows[] = $col;
 
71
            }
 
72
 
 
73
            Log::notice(sprintf('Returning %d columns.', count($rows)), 'DataSetColumn', 'GetData');
 
74
          
 
75
            return $rows;          
 
76
        }
 
77
        catch (Exception $e) {
 
78
            
 
79
            Log::error($e->getMessage());
 
80
        
 
81
            if (!$this->IsError())
 
82
                $this->SetError(1, __('Unknown Error'));
 
83
        
 
84
            return false;
 
85
        }
 
86
    }
 
87
 
 
88
    public function Add($dataSetColumnId, $rowNumber, $value)
 
89
    {
 
90
        if ($dataSetColumnId == 0 || $dataSetColumnId == '')
 
91
            return $this->SetError(25001, __('Missing dataSetColumnId'));
 
92
 
 
93
        if ($rowNumber == 0 || $rowNumber == '')
 
94
            return $this->SetError(25001, __('Missing rowNumber'));
 
95
 
 
96
        try {
 
97
            $dbh = \Xibo\Storage\PDOConnect::init();
 
98
 
 
99
            $SQL  = "INSERT INTO datasetdata (DataSetColumnID, RowNumber, Value) ";
 
100
            $SQL .= "    VALUES (:datasetcolumnid, :rownumber, :value) ";
 
101
            
 
102
            $sth = $dbh->prepare($SQL);
 
103
            $sth->execute(array(
 
104
                    'datasetcolumnid' => $dataSetColumnId,
 
105
                    'rownumber' => $rowNumber,
 
106
                    'value' => $value
 
107
               ));
 
108
 
 
109
            $id = $dbh->lastInsertId();
 
110
 
 
111
            // Update the Water Mark
 
112
            $this->UpdateWatermarkWithColumnId($dataSetColumnId);
 
113
 
 
114
            Log::notice('Complete', 'DataSetData', 'Add');
 
115
            
 
116
            return $id;
 
117
        }
 
118
        catch (Exception $e) {
 
119
            Log::error($e->getMessage());
 
120
            return $this->SetError(25005, __('Could not add DataSet Data'));
 
121
        }
 
122
    }
 
123
 
 
124
    public function Edit($dataSetColumnId, $rowNumber, $value)
 
125
    {
 
126
        if ($dataSetColumnId == 0 || $dataSetColumnId == '')
 
127
            return $this->SetError(25001, __('Missing dataSetColumnId'));
 
128
 
 
129
        if ($rowNumber == 0 || $rowNumber == '')
 
130
            return $this->SetError(25001, __('Missing rowNumber'));
 
131
 
 
132
        try {
 
133
            $dbh = \Xibo\Storage\PDOConnect::init();
 
134
 
 
135
            $SQL  = "UPDATE datasetdata SET Value = :value ";
 
136
            $SQL .= " WHERE DataSetColumnID = :datasetcolumnid AND RowNumber = :rownumber";
 
137
 
 
138
            $sth = $dbh->prepare($SQL);
 
139
            $sth->execute(array(
 
140
                    'datasetcolumnid' => $dataSetColumnId,
 
141
                    'rownumber' => $rowNumber,
 
142
                    'value' => $value
 
143
               ));
 
144
 
 
145
            $this->UpdateWatermarkWithColumnId($dataSetColumnId);
 
146
 
 
147
            Log::notice('Complete', 'DataSetData', 'Edit');
 
148
 
 
149
            return true;
 
150
        }
 
151
        catch (Exception $e) {
 
152
            Log::error($e->getMessage());
 
153
            return $this->SetError(25005, __('Could not edit DataSet Data'));
 
154
        }
 
155
    }
 
156
 
 
157
    public function Delete($dataSetColumnId, $rowNumber)
 
158
    {
 
159
        try {
 
160
            $dbh = \Xibo\Storage\PDOConnect::init();
 
161
 
 
162
            $SQL  = "DELETE FROM datasetdata ";
 
163
            $SQL .= " WHERE DataSetColumnID = :datasetcolumnid AND RowNumber = :rownumber";
 
164
 
 
165
            $sth = $dbh->prepare($SQL);
 
166
            $sth->execute(array(
 
167
                    'datasetcolumnid' => $dataSetColumnId,
 
168
                    'rownumber' => $rowNumber
 
169
               ));
 
170
 
 
171
            $this->UpdateWatermarkWithColumnId($dataSetColumnId);
 
172
 
 
173
            Log::notice('Complete', 'DataSetData', 'Delete');
 
174
 
 
175
            return true;
 
176
        }
 
177
        catch (Exception $e) {
 
178
            Log::error($e->getMessage());
 
179
            return $this->SetError(25005, __('Could not delete Data for Column/Row'));
 
180
        }
 
181
    }
 
182
 
 
183
    public function DeleteAll($dataSetId) {
 
184
 
 
185
        if ($dataSetId == 0 || $dataSetId == '')
 
186
            return $this->SetError(25001, __('Missing dataSetId'));
 
187
 
 
188
        try {
 
189
            $dbh = \Xibo\Storage\PDOConnect::init();
 
190
 
 
191
            $SQL  = "";
 
192
            $SQL .= "DELETE FROM datasetdata WHERE DataSetColumnId IN ( ";
 
193
            $SQL .= "   SELECT DataSetColumnID FROM datasetcolumn WHERE DataSetID = :datasetid ";
 
194
            $SQL .= "   )";
 
195
 
 
196
            $sth = $dbh->prepare($SQL);
 
197
            $sth->execute(array(
 
198
                    'datasetid' => $dataSetId
 
199
               ));
 
200
 
 
201
            $this->UpdateWatermark($dataSetId);
 
202
 
 
203
            return true;
 
204
        }
 
205
        catch (Exception $e) {
 
206
            Log::error($e->getMessage());
 
207
            return $this->SetError(25005, __('Could not delete Data for entire DataSet'));
 
208
        }
 
209
    }
 
210
 
 
211
    /**
 
212
     * Update the Water Mark to indicate the last data edit
 
213
     * @param int $dataSetColumnId The Data Set Column ID
 
214
     */
 
215
    private function UpdateWatermarkWithColumnId($dataSetColumnId) {
 
216
 
 
217
        if (!$this->updateWatermark)
 
218
            return;
 
219
 
 
220
        try {
 
221
            $dbh = \Xibo\Storage\PDOConnect::init();
 
222
        
 
223
            $sth = $dbh->prepare('SELECT DataSetID FROM `datasetcolumn` WHERE DataSetColumnID = :dataset_column_id');
 
224
            $sth->execute(array(
 
225
                    'dataset_column_id' => $dataSetColumnId
 
226
                ));
 
227
          
 
228
            $this->UpdateWatermark($sth->fetchColumn(0));
 
229
        }
 
230
        catch (Exception $e) {
 
231
            
 
232
            Log::error($e->getMessage());
 
233
        
 
234
            if (!$this->IsError())
 
235
                $this->SetError(1, __('Unknown Error'));
 
236
        
 
237
            return false;
 
238
        }
 
239
    }
 
240
 
 
241
    /**
 
242
     * Update the Water Mark to indicate the last data edit
 
243
     * @param int $dataSetId The Data Set ID to Update
 
244
     */
 
245
    private function UpdateWatermark($dataSetId) {
 
246
 
 
247
        if ($dataSetId == 0 || $dataSetId == '')
 
248
            return $this->SetError(25001, __('Missing dataSetId'));
 
249
        
 
250
        if (!$this->updateWatermark)
 
251
            return;
 
252
 
 
253
        Log::notice(sprintf('Updating water mark on DataSetId: %d', $dataSetId), 'DataSetData', 'UpdateWatermark');
 
254
 
 
255
        try {
 
256
            $dbh = \Xibo\Storage\PDOConnect::init();
 
257
        
 
258
            $sth = $dbh->prepare('UPDATE `dataset` SET LastDataEdit = :last_data_edit WHERE DataSetID = :dataset_id');
 
259
            $sth->execute(array(
 
260
                    'last_data_edit' => time(),
 
261
                    'dataset_id' => $dataSetId
 
262
                ));
 
263
 
 
264
            // Get affected Campaigns
 
265
 
 
266
            $dataSet = new DataSet($this->db);
 
267
            $campaigns = $dataSet->GetCampaignsForDataSet($dataSetId);
 
268
 
 
269
 
 
270
            $display = new Display($this->db);
 
271
 
 
272
            foreach ($campaigns as $campaignId) {
 
273
                // Assess all displays  
 
274
                $campaigns = $display->NotifyDisplays($campaignId);
 
275
            }
 
276
        }
 
277
        catch (Exception $e) {
 
278
            
 
279
            Log::error($e->getMessage());
 
280
        
 
281
            if (!$this->IsError())
 
282
                $this->SetError(1, __('Unknown Error'));
 
283
        
 
284
            return false;
 
285
        }
 
286
    }
 
287
 
 
288
    public function ImportCsv($dataSetId, $csvFile, $spreadSheetMapping, $overwrite = false, $ignoreFirstRow = true) {
 
289
 
 
290
        if ($dataSetId == 0 || $dataSetId == '')
 
291
            return $this->SetError(25001, __('Missing dataSetId'));
 
292
 
 
293
        if (!file_exists($csvFile))
 
294
            return $this->SetError(25001, __('CSV File does not exist'));
 
295
 
 
296
        if (!is_array($spreadSheetMapping) || count($spreadSheetMapping) <= 0)
 
297
            return $this->SetError(25001, __('Missing spreadSheetMapping'));
 
298
 
 
299
        Log::notice('spreadSheetMapping: ' . json_encode($spreadSheetMapping), 'DataSetData', 'ImportCsv');
 
300
        
 
301
        $this->updateWatermark = false;
 
302
 
 
303
        try {
 
304
            $dbh = \Xibo\Storage\PDOConnect::init();
 
305
 
 
306
            // Are we overwriting or appending?
 
307
            if ($overwrite) {
 
308
                // We need to delete all the old data and start from row 1
 
309
                if (!$this->DeleteAll($dataSetId))
 
310
                    return false;
 
311
                
 
312
                $rowNumber = 1;
 
313
            }
 
314
            else {
 
315
                // We need to get the MAX row number that currently exists in the data set
 
316
                $sth = $dbh->prepare('SELECT IFNULL(MAX(RowNumber), 0) AS RowNumber FROM datasetdata INNER JOIN datasetcolumn ON datasetcolumn.dataSetColumnId = datasetdata.DataSetColumnID WHERE datasetcolumn.DataSetID = :datasetid');
 
317
                $sth->execute(array(
 
318
                        'datasetid' => $dataSetId
 
319
                    ));
 
320
 
 
321
                if (!$row = $sth->fetch())
 
322
                    return $this->SetError(25005, __('Could not determine the Max row number'));
 
323
 
 
324
                $rowNumber = \Xibo\Helper\Sanitize::int($row['RowNumber']);
 
325
                $rowNumber++;
 
326
            }
 
327
 
 
328
            // Match the file content with the column mappings
 
329
 
 
330
            // Load the file
 
331
            ini_set('auto_detect_line_endings', true);
 
332
 
 
333
            $firstRow = true;
 
334
 
 
335
            $handle = fopen($csvFile, 'r');
 
336
            while (($data = fgetcsv($handle)) !== FALSE ) {
 
337
 
 
338
                // The CSV file might have headings, so ignore the first row.
 
339
                if ($firstRow) {
 
340
                    $firstRow = false;
 
341
 
 
342
                    if ($ignoreFirstRow)
 
343
                        continue;
 
344
                }
 
345
                
 
346
                for ($cell = 0; $cell < count($data); $cell++) {
 
347
                    
 
348
                    // Insert the data into the correct column
 
349
                    if (isset($spreadSheetMapping[$cell])) {
 
350
 
 
351
                        if (!$this->Add($spreadSheetMapping[$cell], $rowNumber, $data[$cell]))
 
352
                            return false;
 
353
                    }
 
354
                }
 
355
 
 
356
                // Move on to the next row
 
357
                $rowNumber++;
 
358
            }
 
359
 
 
360
            // Close the file
 
361
            fclose($handle);
 
362
 
 
363
            // Change the auto detect setting back
 
364
            ini_set('auto_detect_line_endings', false);
 
365
 
 
366
            // Delete the temporary file
 
367
            @unlink($csvFile);
 
368
 
 
369
            // TODO: Update list content definitions
 
370
 
 
371
            $this->UpdateWatermark($dataSetId);
 
372
 
 
373
            return true;
 
374
        }
 
375
        catch (Exception $e) {
 
376
 
 
377
            Log::error($e->getMessage());
 
378
 
 
379
            if (!$this->IsError())
 
380
                $this->SetError(25005, __('Unable to Import'));
 
381
 
 
382
            return false;
 
383
        }
 
384
    }
 
385
}
 
386
?>