~xibo-maintainers/xibo/tempel

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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
<?php
/*
 * Xibo - Digital Signage - http://www.xibo.org.uk
 * Copyright (C) 2006-2014 Daniel Garner
 *
 * This file is part of Xibo.
 *
 * Xibo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version. 
 *
 * Xibo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Xibo.  If not, see <http://www.gnu.org/licenses/>.
 */
namespace Xibo\Controller;

use Xibo\Entity\User;
use Xibo\Helper\ApplicationState;
use Xibo\Helper\Help;
use Xibo\Helper\Log;
use Xibo\Helper\Theme;

defined('XIBO') or die("Sorry, you are not allowed to directly access this page.<br /> Please press the back button in your browser.");

class Module extends Base
{
    private $module;

    /**
     * Module constructor.
     * @param $db database
     * @param $user user
     */
    function __construct(database $db, user $user)
    {
        $this->db =& $db;
        $this->user =& $user;
    }

    function actionMenu()
    {
        return array(
            array('title' => __('Verify All'),
                'class' => 'XiboFormButton',
                'selected' => false,
                'link' => 'index.php?p=module&q=VerifyForm',
                'help' => __('Verify all modules have been installed correctly.'),
                'onclick' => ''
            )
        );
    }

    /**
     * Display the module page
     */
    function displayPage()
    {
        // Configure the theme
        $id = uniqid();
        Theme::Set('id', $id);
        Theme::Set('form_meta', '<input type="hidden" name="p" value="module"><input type="hidden" name="q" value="Grid">');
        Theme::Set('pager', ApplicationState::Pager($id));

        // Do we have any modules to install?!
        if (Config::GetSetting('MODULE_CONFIG_LOCKED_CHECKB') != 'Checked') {
            // Get a list of matching files in the modules folder
            $files = glob('modules/*.module.php');

            // Get a list of all currently installed modules
            try {
                $dbh = \Xibo\Storage\PDOConnect::init();

                $sth = $dbh->prepare("SELECT CONCAT('modules/', LOWER(Module), '.module.php') AS Module FROM `module`");
                $sth->execute();

                $rows = $sth->fetchAll();
                $installed = array();

                foreach ($rows as $row)
                    $installed[] = $row['Module'];
            } catch (Exception $e) {
                trigger_error(__('Cannot get installed modules'), E_USER_ERROR);
            }

            // Compare the two
            $to_install = array_diff($files, $installed);

            if (count($to_install) > 0) {
                Theme::Set('module_install_url', 'index.php?p=module&q=Install&module=');
                Theme::Set('to_install', $to_install);
                Theme::Set('prepend', Theme::RenderReturn('module_page_install_modules'));
            }
        }

        // Call to render the template
        Theme::Set('header_text', __('Modules'));
        Theme::Set('form_fields', array());
        $this->getState()->html .= Theme::RenderReturn('grid_render');
    }

    /**
     * A grid of modules
     */
    public function Grid()
    {

        $user = $this->getUser();
        $response = $this->getState();

        $SQL = '';
        $SQL .= 'SELECT ModuleID, ';
        $SQL .= '   Name, ';
        $SQL .= '   Enabled, ';
        $SQL .= '   Description, ';
        $SQL .= '   RegionSpecific, ';
        $SQL .= '   ValidExtensions, ';
        $SQL .= '   ImageUri, ';
        $SQL .= '   PreviewEnabled, ';
        $SQL .= '   assignable, ';
        $SQL .= '   settings ';
        $SQL .= '  FROM `module` ';
        $SQL .= ' ORDER BY Name ';

        if (!$modules = $db->GetArray($SQL)) {
            trigger_error($db->error());
            trigger_error(__('Unable to get the list of modules'), E_USER_ERROR);
        }

        $cols = array(
            array('name' => 'name', 'title' => __('Name')),
            array('name' => 'description', 'title' => __('Description')),
            array('name' => 'isregionspecific', 'title' => __('Library Media'), 'icons' => true),
            array('name' => 'validextensions', 'title' => __('Valid Extensions')),
            array('name' => 'imageuri', 'title' => __('Image Uri')),
            array('name' => 'preview_enabled', 'title' => __('Preview Enabled'), 'icons' => true),
            array('name' => 'assignable', 'title' => __('Assignable'), 'icons' => true, 'helpText' => __('Can this module be assigned to a Layout?')),
            array('name' => 'enabled', 'title' => __('Enabled'), 'icons' => true)
        );
        Theme::Set('table_cols', $cols);

        $rows = array();

        foreach ($modules as $module) {
            $row = array();
            $row['moduleid'] = \Xibo\Helper\Sanitize::int($module['ModuleID']);
            $row['name'] = \Xibo\Helper\Sanitize::string($module['Name']);
            $row['description'] = \Xibo\Helper\Sanitize::string($module['Description']);
            $row['isregionspecific'] = (\Xibo\Helper\Sanitize::int($module['RegionSpecific']) == 0) ? 1 : 0;
            $row['validextensions'] = \Xibo\Helper\Sanitize::string($module['ValidExtensions']);
            $row['imageuri'] = \Xibo\Helper\Sanitize::string($module['ImageUri']);
            $row['enabled'] = \Xibo\Helper\Sanitize::int($module['Enabled']);
            $row['preview_enabled'] = \Xibo\Helper\Sanitize::int($module['PreviewEnabled']);
            $row['assignable'] = \Xibo\Helper\Sanitize::int($module['assignable']);
            $row['settings'] = json_decode(Kit::ValidateParam($module['settings'], _HTMLSTRING), true);

            // Initialise array of buttons, because we might not have any
            $row['buttons'] = array();

            // If the module config is not locked, present some buttons
            if (Config::GetSetting('MODULE_CONFIG_LOCKED_CHECKB') != 'Checked') {

                // Edit button
                $row['buttons'][] = array(
                    'id' => 'module_button_edit',
                    'url' => 'index.php?p=module&q=EditForm&ModuleID=' . $row['moduleid'],
                    'text' => __('Edit')
                );
            }

            // Are there any buttons we need to provide as part of the module?
            if (isset($row['settings']['buttons'])) {
                foreach ($row['settings']['buttons'] as $button) {
                    $button['text'] = __($button['text']);
                    $row['buttons'][] = $button;
                }
            }

            $rows[] = $row;
        }

        Theme::Set('table_rows', $rows);

        $output = Theme::RenderReturn('table_render');

        $response->SetGridResponse($output);

    }

    /**
     * Edit Form
     */
    public function EditForm()
    {

        $user = $this->getUser();
        $response = $this->getState();
        $helpManager = new Help($db, $user);

        // Can we edit?
        if (Config::GetSetting('MODULE_CONFIG_LOCKED_CHECKB') == 'Checked')
            trigger_error(__('Module Config Locked'), E_USER_ERROR);

        $moduleId = \Xibo\Helper\Sanitize::getInt('ModuleID');

        // Pull the currently known info from the DB
        $SQL = '';
        $SQL .= 'SELECT ModuleID, ';
        $SQL .= '   Module, ';
        $SQL .= '   Name, ';
        $SQL .= '   Enabled, ';
        $SQL .= '   Description, ';
        $SQL .= '   RegionSpecific, ';
        $SQL .= '   ValidExtensions, ';
        $SQL .= '   ImageUri, ';
        $SQL .= '   PreviewEnabled ';
        $SQL .= '  FROM `module` ';
        $SQL .= ' WHERE ModuleID = %d ';

        $SQL = sprintf($SQL, $moduleId);

        if (!$row = $db->GetSingleRow($SQL)) {
            trigger_error($db->error());
            trigger_error(__('Error getting Module'));
        }

        $type = \Kit::ValidateParam($row['Module'], _WORD);

        // Set some information about the form
        Theme::Set('form_id', 'ModuleEditForm');
        Theme::Set('form_action', 'index.php?p=module&q=Edit');
        Theme::Set('form_meta', '<input type="hidden" name="ModuleID" value="' . $moduleId . '" /><input type="hidden" name="type" value="' . $type . '" />');

        $formFields = array();
        $formFields[] = FormManager::AddText('ValidExtensions', __('Valid Extensions'), \Xibo\Helper\Sanitize::string($row['ValidExtensions']),
            __('The Extensions allowed on files uploaded using this module. Comma Separated.'), 'e', '');

        $formFields[] = FormManager::AddText('ImageUri', __('Image Uri'), \Xibo\Helper\Sanitize::string($row['ImageUri']),
            __('The Image to display for this module. This should be a path relative to the root of the installation.'), 'i', '');

        $formFields[] = FormManager::AddCheckbox('PreviewEnabled', __('Preview Enabled?'),
            \Xibo\Helper\Sanitize::int($row['PreviewEnabled']), __('When PreviewEnabled users will be able to see a preview in the layout designer'),
            'p');

        $formFields[] = FormManager::AddCheckbox('Enabled', __('Enabled?'),
            \Xibo\Helper\Sanitize::int($row['Enabled']), __('When Enabled users will be able to add media using this module'),
            'b');

        // Set any module specific form fields
        $module = \Xibo\Factory\ModuleFactory::create($type);

        // Merge in the fields from the settings
        foreach ($module->ModuleSettingsForm() as $field)
            $formFields[] = $field;

        Theme::Set('form_fields', $formFields);

        $response->SetFormRequestResponse(NULL, __('Edit Module'), '350px', '325px');
        $response->AddButton(__('Help'), 'XiboHelpRender("' . $helpManager->Link('Module', 'Edit') . '")');
        $response->AddButton(__('Cancel'), 'XiboDialogClose()');
        $response->AddButton(__('Save'), '$("#ModuleEditForm").submit()');

    }

    public function Edit()
    {


        $response = $this->getState();

        // Can we edit?
        if (Config::GetSetting('MODULE_CONFIG_LOCKED_CHECKB') == 'Checked')
            trigger_error(__('Module Config Locked'), E_USER_ERROR);

        $moduleId = \Xibo\Helper\Sanitize::getInt('ModuleID');
        $type = \Kit::GetParam('type', _POST, _WORD);
        $validExtensions = \Kit::GetParam('ValidExtensions', _POST, _STRING, '');
        $imageUri = \Xibo\Helper\Sanitize::getString('ImageUri');
        $enabled = \Xibo\Helper\Sanitize::getCheckbox('Enabled');
        $previewEnabled = \Xibo\Helper\Sanitize::getCheckbox('PreviewEnabled');

        // Validation
        if ($moduleId == 0 || $moduleId == '')
            trigger_error(__('Module ID is missing'), E_USER_ERROR);

        if ($type == '')
            trigger_error(__('Type is missing'), E_USER_ERROR);

        if ($imageUri == '')
            trigger_error(__('Image Uri is a required field.'), E_USER_ERROR);

        // Process any module specific form fields
        $module = ModuleFactory::create($type, $this->db, $this->user);

        // Install Files for this module
        $module->InstallFiles();

        try {
            // Get the settings (may throw an exception)
            $settings = json_encode($module->ModuleSettings());

            $dbh = \Xibo\Storage\PDOConnect::init();

            $sth = $dbh->prepare('
                UPDATE `module` SET ImageUri = :image_url, ValidExtensions = :valid_extensions,
                    Enabled = :enabled, PreviewEnabled = :preview_enabled, settings = :settings
                 WHERE ModuleID = :module_id');

            $sth->execute(array(
                'image_url' => $imageUri,
                'valid_extensions' => $validExtensions,
                'enabled' => $enabled,
                'preview_enabled' => $previewEnabled,
                'settings' => $settings,
                'module_id' => $moduleId
            ));

            $response->SetFormSubmitResponse(__('Module Edited'), false);

        } catch (Exception $e) {

            Log::error($e->getMessage());

            if (!$this->IsError())
                $this->SetError(1, __('Unknown Error'));

            trigger_error(__('Unable to update module'), E_USER_ERROR);
        }
    }

    /**
     * Edit Form
     */
    public function VerifyForm()
    {
        $user = $this->getUser();
        $response = $this->getState();
        $helpManager = new Help(NULL, $user);

        // Set some information about the form
        Theme::Set('form_id', 'VerifyForm');
        Theme::Set('form_action', 'index.php?p=module&q=Verify');

        $formFields = array();
        $formFields[] = FormManager::AddMessage(__('Verify all modules have been installed correctly by reinstalling any module related files'));

        Theme::Set('form_fields', $formFields);

        $response->SetFormRequestResponse(NULL, __('Verify'), '350px', '325px');
        $response->AddButton(__('Help'), 'XiboHelpRender("' . $helpManager->Link('Module', 'Edit') . '")');
        $response->AddButton(__('Cancel'), 'XiboDialogClose()');
        $response->AddButton(__('Verify'), '$("#VerifyForm").submit()');

    }

    public function Verify()
    {


        $response = $this->getState();

        try {
            $dbh = \Xibo\Storage\PDOConnect::init();

            $dbh->exec('UPDATE `media` SET valid = 0 WHERE moduleSystemFile = 1');
        } catch (Exception $e) {

            Log::error($e->getMessage());

            if (!$this->IsError())
                $this->SetError(1, __('Unknown Error'));

            return false;
        }

        Media::installAllModuleFiles();

        $response->SetFormSubmitResponse(__('Verified'), false);

    }

    public function Install()
    {
        // Module file name
        $file = \Xibo\Helper\Sanitize::getString('module');

        if ($file == '')
            trigger_error(__('Unable to install module'), E_USER_ERROR);

        Log::notice('Request to install Module: ' . $file, 'module', 'Install');

        // Check that the file exists
        if (!file_exists($file))
            trigger_error(__('File does not exist'), E_USER_ERROR);

        // Make sure the file is in our list of expected module files
        $files = glob('modules/*.module.php');

        if (!in_array($file, $files))
            trigger_error(__('Not a module file'), E_USER_ERROR);

        // Load the file
        include_once($file);

        $type = str_replace('modules/', '', $file);
        $type = str_replace('.module.php', '', $type);

        // Load the module object inside the file
        if (!class_exists($type))
            trigger_error(__('Module file does not contain a class of the correct name'), E_USER_ERROR);

        try {
            Log::notice('Validation passed, installing module.', 'module', 'Install');
            $moduleObject = ModuleFactory::create($type, $this->db, $this->user);
            $moduleObject->InstallOrUpdate();
        } catch (Exception $e) {
            trigger_error(__('Unable to install module'), E_USER_ERROR);
        }

        Log::notice('Module Installed: ' . $file, 'module', 'Install');

        // Excellent... capital... success
        $response = $this->getState();
        $response->refresh = true;
        $response->refreshLocation = 'index.php?p=module';

    }

    /**
     * Execute a Module Action
     */
    public function Exec()
    {
        $requestedModule = \Kit::GetParam('mod', _REQUEST, _WORD);
        $requestedMethod = \Kit::GetParam('method', _REQUEST, _WORD);

        Log::Audit('Module Exec for ' . $requestedModule . ' with method ' . $requestedMethod);

        // Validate that GetResource calls have a region
        if ($requestedMethod == 'GetResource' && \Kit::GetParam('regionId', _REQUEST, _INT) == 0)
            die(__('Get Resource Call without a Region'));

        // Create a new module to handle this request
        $module = \Xibo\Factory\ModuleFactory::createForWidget(Kit::GetParam('mod', _REQUEST, _WORD), \Kit::GetParam('widgetId', _REQUEST, _INT), $this->user->userId, \Kit::GetParam('playlistId', _REQUEST, _INT), \Kit::GetParam('regionId', _REQUEST, _INT));

        // Authenticate access to this widget
        if (!$this->user->checkViewable($module->widget))
            die(__('Access Denied'));

        // Set the permissions for this module
        $module->setPermission($this->user->getPermission($module->widget));

        // Set the user - it is used in forms to return other entities
        $module->setUser($this->user);

        // What module has been requested?
        $response = null;
        $method = \Kit::GetParam('method', _REQUEST, _WORD);
        $raw = \Kit::GetParam('raw', _REQUEST, _WORD);

        if (method_exists($module, $method)) {
            $response = $module->$method();
        } else {
            // Set the error to display
            trigger_error(__('This Module does not exist'), E_USER_ERROR);
        }

        if ($raw == 'true') {
            echo $response;
            exit();
        } else {
            /* @var ApplicationState $response */

        }
    }
}