Example #1
1
        <script src="theme/default/libraries/colors/colors.min.js"></script>
        <script src="theme/default/js/xibo-cms.js"></script>
    	<script src="theme/default/js/xibo-forms.js"></script>
    	<script src="theme/default/js/xibo-layout-designer.js"></script>
    	<script src="theme/default/js/xibo-preview-timeline.js"></script>
    	<script src="theme/default/js/xibo-calendar.js"></script>
    	<script src="theme/default/js/xibo-datasets.js"></script>
        <script type="text/javascript">
        var translations = <?php 
echo Theme::Get('translations') == '' ? '{}' : Theme::Get('translations');
?>
;
        var language = "<?php 
echo TranslationEngine::GetJsLocale();
?>
";
        var dateFormat = "<?php 
echo Config::GetSetting('DATE_FORMAT', 'Y-m-d h:i');
?>
";
        var calendarType = "<?php 
echo Config::GetSetting('CALENDAR_TYPE');
?>
";
        var calendarLanguage = "<?php 
echo strlen(TranslationEngine::GetJsLocale() <= 2) ? TranslationEngine::GetJsLocale() . '-' . strtoupper(TranslationEngine::GetJsLocale()) : TranslationEngine::GetJsLocale();
?>
";
        </script>
	</body>
</html>
Example #2
0
 private function processActions()
 {
     if (Config::GetSetting('DEFAULTS_IMPORTED') == 0) {
         $layout = new Layout();
         $layout->importFolder('theme' . DIRECTORY_SEPARATOR . Theme::ThemeFolder() . DIRECTORY_SEPARATOR . 'layouts');
         Config::ChangeSetting('DEFAULTS_IMPORTED', 1);
     }
 }
 /**
  * Gets and Sets the Local 
  * @return 
  */
 public static function InitLocale()
 {
     $localeDir = 'locale';
     $default = Config::GetSetting('DEFAULT_LANGUAGE');
     global $transEngine;
     global $stream;
     //Debug::LogEntry('audit', 'IN', 'TranslationEngine', 'InitLocal');
     // Try to get the local firstly from _REQUEST (post then get)
     $lang = Kit::GetParam('lang', _REQUEST, _WORD, '');
     // Build an array of supported languages
     $supportedLangs = scandir($localeDir);
     if ($lang != '') {
         // Set the language
         Debug::LogEntry('audit', 'Set the Language from REQUEST [' . $lang . ']', 'TranslationEngine', 'InitLocal');
         // Is this language supported?
         // if not just use the default (eb_GB).
         if (!in_array($lang . '.mo', $supportedLangs)) {
             trigger_error(sprintf('Language not supported. %s', $lang));
             // Use the default language instead.
             $lang = $default;
         }
     } else {
         $langs = Kit::GetParam('HTTP_ACCEPT_LANGUAGE', $_SERVER, _STRING);
         if ($langs != '') {
             //Debug::LogEntry('audit', ' HTTP_ACCEPT_LANGUAGE [' . $langs . ']', 'TranslationEngine', 'InitLocal');
             $langs = explode(',', $langs);
             foreach ($langs as $lang) {
                 // Remove any quality rating (as we aren't interested)
                 $rawLang = explode(';', $lang);
                 $lang = str_replace("-", "_", $rawLang[0]);
                 if (in_array($lang . '.mo', $supportedLangs)) {
                     //Debug::LogEntry('audit', 'Obtained the Language from HTTP_ACCEPT_LANGUAGE [' . $lang . ']', 'TranslationEngine', 'InitLocal');
                     break;
                 }
                 // Set lang as the default
                 $lang = $default;
             }
         } else {
             $lang = $default;
         }
     }
     // We have the language
     //Debug::LogEntry('audit', 'Creating new file streamer for '. $localeDir . '/' . $lang . '.mo', 'TranslationEngine', 'InitLocal');
     if (!($stream = new CachedFileReader($localeDir . '/' . $lang . '.mo'))) {
         trigger_error('Unable to translate this language');
         $transEngine = false;
         return;
     }
     $transEngine = new gettext_reader($stream);
 }
Example #4
0
 private function request($latitude, $longitude, $time = null, $options = array())
 {
     $request_url = self::API_ENDPOINT . '[APIKEY]' . '/' . $latitude . ',' . $longitude . (is_null($time) ? '' : ',' . $time);
     if (!empty($options)) {
         $request_url .= '?' . http_build_query($options);
     }
     \Debug::Audit('Calling API with: ' . $request_url);
     $request_url = str_replace('[APIKEY]', $this->api_key, $request_url);
     $httpOptions = array(CURLOPT_TIMEOUT => 20, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_USERAGENT => 'Xibo Digital Signage', CURLOPT_HEADER => false, CURLINFO_HEADER_OUT => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_URL => $request_url);
     // Proxy support
     if (\Config::GetSetting('PROXY_HOST') != '' && !\Config::isProxyException($request_url)) {
         $httpOptions[CURLOPT_PROXY] = \Config::GetSetting('PROXY_HOST');
         $httpOptions[CURLOPT_PROXYPORT] = \Config::GetSetting('PROXY_PORT');
         if (\Config::GetSetting('PROXY_AUTH') != '') {
             $httpOptions[CURLOPT_PROXYUSERPWD] = \Config::GetSetting('PROXY_AUTH');
         }
     }
     $curl = curl_init();
     curl_setopt_array($curl, $httpOptions);
     $result = curl_exec($curl);
     // Get the response headers
     $outHeaders = curl_getinfo($curl);
     if ($outHeaders['http_code'] == 0) {
         // Unable to connect
         \Debug::Error('Unable to reach Forecast API. No Host Found (HTTP Code 0). Curl Error = ' . curl_error($curl));
         return false;
     } else {
         if ($outHeaders['http_code'] != 200) {
             \Debug::Error('ForecastIO API returned ' . $outHeaders['http_code'] . ' status. Unable to proceed. Headers = ' . var_export($outHeaders, true));
             // See if we can parse the error.
             $body = json_decode($result);
             \Debug::Error('ForecastIO Error: ' . (isset($body->errors[0]) ? $body->errors[0]->message : 'Unknown Error'));
             return false;
         }
     }
     // Parse out header and body
     $body = json_decode($result);
     return $body;
 }
Example #5
0
 public function __construct(user $user, $theme = NULL)
 {
     // Store some things for the Theme engine to use
     $this->user =& $user;
     $this->help = new HelpManager();
     $this->dateManager = new DateManager();
     // What is the currently selected theme?
     $globalTheme = $theme == NULL ? Config::GetSetting('GLOBAL_THEME_NAME', 'default') : $theme;
     // Is this theme valid?
     if (!is_dir('theme/' . $globalTheme)) {
         throw new Exception(__('The theme "%s" does not exist', $globalTheme));
     }
     // Store the theme name for later
     $this->name = $globalTheme;
     // Get config
     if (!file_exists('theme/' . $this->name . '/config.php')) {
         throw new Exception(__('The theme "%s" config file does not exist', $globalTheme));
     }
     require 'theme/' . $this->name . '/config.php';
     $this->config = $config;
     self::$instance = $this;
 }
Example #6
0
 public function __construct(database $db, user $user)
 {
     // Store some things for the Theme engine to use
     $this->db =& $db;
     $this->user =& $user;
     $this->help = new HelpManager($db, $user);
     $this->dateManager = new DateManager($db);
     // TODO: Perhaps we also allow the user to configure their own theme for their session?
     // What is the currently selected theme?
     $globalTheme = Config::GetSetting('GLOBAL_THEME_NAME');
     // Is this theme valid?
     if (!is_dir('theme/' . $globalTheme)) {
         throw new Exception(__('The theme "%s" does not exist', $globalTheme));
     }
     // Store the theme name for later
     $this->name = $globalTheme;
     // Get config
     if (!file_exists('theme/' . $this->name . '/config.php')) {
         throw new Exception(__('The theme "%s" config file does not exist', $globalTheme));
     }
     require_once 'theme/' . $this->name . '/config.php';
     $this->config = $config;
     self::$instance = $this;
 }
Example #7
0
        header("Location: {$redirect}");
        exit;
    }
}
// What is the production mode of the server?
if (Config::GetSetting('SERVER_MODE') == 'Test') {
    ini_set('display_errors', 1);
}
// Debugging?
if (Debug::getLevel(Config::GetSetting('audit')) == 10) {
    error_reporting(E_ALL);
}
// Setup the translations for gettext
TranslationEngine::InitLocale();
// Create login control system
require_once 'modules/' . Config::GetSetting("userModule");
// Page variable set? Otherwise default to index
$page = Kit::GetParam('p', _REQUEST, _WORD, 'index');
$function = Kit::GetParam('q', _REQUEST, _WORD);
// Does the version in the DB match the version of the code?
// If not then we need to run an upgrade. Change the page variable to upgrade
if (DBVERSION != WEBSITE_VERSION && !($page == 'index' && $function == 'login' || $page == 'error')) {
    require_once 'install/upgradestep.class.php';
    $page = 'upgrade';
    if (Kit::GetParam('includes', _POST, _BOOL)) {
        $upgradeFrom = Kit::GetParam('upgradeFrom', _POST, _INT);
        $upgradeTo = Kit::GetParam('upgradeTo', _POST, _INT);
        for ($i = $upgradeFrom + 1; $i <= $upgradeTo; $i++) {
            if (file_exists('install/database/' . $i . '.php')) {
                include_once 'install/database/' . $i . '.php';
            }
Example #8
0
 /**
  * Return file based media items to the browser for Download/Preview
  * @return
  * @param $download Boolean
  */
 public function ReturnFile($fileName = '')
 {
     // Return the raw flash file with appropriate headers
     $library = Config::GetSetting("LIBRARY_LOCATION");
     # If we weren't passed in a filename then use the default
     if ($fileName == '') {
         $fileName = $library . $this->storedAs;
     }
     $download = Kit::GetParam('download', _REQUEST, _BOOLEAN, false);
     $downloadFromLibrary = Kit::GetParam('downloadFromLibrary', _REQUEST, _BOOLEAN, false);
     $size = filesize($fileName);
     if ($download) {
         header('Content-Type: application/octet-stream');
         header("Content-Transfer-Encoding: Binary");
         header("Content-disposition: attachment; filename=\"" . ($downloadFromLibrary ? $this->originalFilename : basename($fileName)) . "\"");
     } else {
         $fi = new finfo(FILEINFO_MIME_TYPE);
         $mime = $fi->file($fileName);
         header("Content-Type: {$mime}");
     }
     //Output a header
     header('Pragma: public');
     header('Cache-Control: max-age=86400');
     header('Expires: ' . gmdate('D, d M Y H:i:s \\G\\M\\T', time() + 86400));
     header('Content-Length: ' . $size);
     // Send via Apache X-Sendfile header?
     if (Config::GetSetting('SENDFILE_MODE') == 'Apache') {
         header("X-Sendfile: {$fileName}");
         exit;
     }
     // Send via Nginx X-Accel-Redirect?
     if (Config::GetSetting('SENDFILE_MODE') == 'Nginx') {
         header("X-Accel-Redirect: /download/" . basename($fileName));
         exit;
     }
     // Return the file with PHP
     // Disable any buffering to prevent OOM errors.
     @ob_end_clean();
     readfile($fileName);
 }
Example #9
0
 /**
  * Get Resource
  */
 public function GetResource($displayId = 0)
 {
     $proportional = Kit::GetParam('proportional', _GET, _BOOL, true);
     $thumb = Kit::GetParam('thumb', _GET, _BOOL, false);
     $dynamic = isset($_REQUEST['dynamic']);
     $file = $this->storedAs;
     $width = intval(Kit::GetParam('width', _REQUEST, _DOUBLE, 80));
     $height = intval(Kit::GetParam('height', _REQUEST, _DOUBLE, 80));
     // File upload directory.. get this from the settings object
     $library = Config::GetSetting("LIBRARY_LOCATION");
     $fileName = $library . $file;
     Debug::Audit(sprintf('Image Request %dx%d %s. Thumb: %s', $width, $height, $fileName, $thumb));
     // If we are a thumb request then output the cached thumbnail
     if ($thumb) {
         $fileName = $library . sprintf('tn_%dx%d_%s', $width, $height, $file);
         // If the thumbnail doesn't exist then create one
         if (!file_exists($fileName)) {
             Debug::LogEntry('audit', 'File doesnt exist, creating a thumbnail for ' . $fileName);
             if (!($info = getimagesize($library . $file))) {
                 die($library . $file . ' is not an image');
             }
             ResizeImage($library . $file, $fileName, $width, $height, $proportional, 'file');
         }
     }
     // Get the info for this new temporary file
     if (!($info = getimagesize($fileName))) {
         $fileName = 'theme/default/img/forms/filenotfound.png';
         $this->ReturnFile($fileName);
         exit;
     }
     if ($dynamic && !$thumb && $info[2]) {
         $width = intval(Kit::GetParam('width', _REQUEST, _DOUBLE, 80));
         $height = intval(Kit::GetParam('height', _REQUEST, _DOUBLE, 80));
         // dynamically create an image of the correct size - used for previews
         ResizeImage($fileName, '', $width, $height, $proportional, 'browser');
         exit;
     }
     if (!file_exists($fileName)) {
         //not sure
         Debug::LogEntry('audit', "Cant find: {$uid}", 'module', 'GetResource');
         $fileName = 'theme/default/img/forms/filenotfound.png';
     }
     $this->ReturnFile($fileName);
     exit;
 }
Example #10
0
 public function Import()
 {
     $db =& $this->db;
     $response = new ResponseManager();
     // What are we importing?
     $template = Kit::GetParam('template', _POST, _STRING, 'false');
     $template = $template == 'true';
     $layout = Kit::GetParam('layout', _POST, _STRING);
     $replaceExisting = Kit::GetParam('replaceExisting', _POST, _CHECKBOX);
     $importTags = Kit::GetParam('importTags', _POST, _CHECKBOX, !$template);
     // File data
     $tmpName = Kit::GetParam('hidFileID', _POST, _STRING);
     if ($tmpName == '') {
         trigger_error(__('Please ensure you have picked a file and it has finished uploading'), E_USER_ERROR);
     }
     // File name and extension (orignial name)
     $fileName = Kit::GetParam('txtFileName', _POST, _STRING);
     $fileName = basename($fileName);
     $ext = strtolower(substr(strrchr($fileName, "."), 1));
     // File upload directory.. get this from the settings object
     $fileLocation = Config::GetSetting('LIBRARY_LOCATION') . 'temp/' . $tmpName;
     Kit::ClassLoader('layout');
     $layoutObject = new Layout($this->db);
     if (!$layoutObject->Import($fileLocation, $layout, $this->user->userid, $template, $replaceExisting, $importTags)) {
         trigger_error($layoutObject->GetErrorMessage(), E_USER_ERROR);
     }
     $response->SetFormSubmitResponse(__('Layout Imported'));
     $response->Respond();
 }
Example #11
0
 /**
  * Tests the supplied password against the password policy
  * @param <type> $password
  */
 public function TestPasswordAgainstPolicy($password)
 {
     // Check password complexity
     $policy = Config::GetSetting('USER_PASSWORD_POLICY');
     if ($policy != '') {
         $policyError = Config::GetSetting('USER_PASSWORD_ERROR');
         $policyError = $policyError == '' ? __('Your password does not meet the required complexity') : $policyError;
         if (!preg_match($policy, $password, $matches)) {
             return $this->SetError(26001, $policyError);
         }
     }
     return true;
 }
Example #12
0
 * Xibo - Digital Signage - http://www.xibo.org.uk
 * Copyright (C) 2010 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/>.
 *
 *
 * OAuth-php include file.
 * Here we setup the XRDS header and initialize OAuth.
 */
defined('XIBO') or die("Sorry, you are not allowed to directly access this page.<br /> Please press the back button in your browser.");
if (Debug::getLevel(Config::GetSetting('audit')) == 10) {
    DEFINE('OAUTH_LOG_REQUEST', true);
}
// Output a discovery header
header('X-XRDS-Location:' . $serviceLocation . '/service.php?xrds');
require_once '3rdparty/oauth-php/library/OAuthServer.php';
require_once '3rdparty/oauth-php/library/OAuthStore.php';
OAuthStore::instance('PDO', array('conn' => PDOConnect::init()));
Example #13
0
 function displayPage()
 {
     // Get some data for a bandwidth chart
     try {
         $dbh = PDOConnect::init();
         $sth = $dbh->prepare('SELECT MONTHNAME(FROM_UNIXTIME(month)) AS month, IFNULL(SUM(Size), 0) AS size FROM `bandwidth` WHERE month > :month GROUP BY MONTHNAME(FROM_UNIXTIME(month)) ORDER BY MIN(month);');
         $sth->execute(array('month' => time() - 86400 * 365));
         $results = $sth->fetchAll();
         $points = array();
         foreach ($results as $row) {
             $points['data'][] = array($row['month'], (double) $row['size'] / 1024 / 1024 / 1024);
         }
         $points['label'] = __('GB');
         $output = array();
         $output['points'][] = $points;
         // Some config options
         $output['config']['series']['bars']['show'] = true;
         $output['config']['series']['bars']['barWidth'] = 0.6;
         $output['config']['series']['bars']['align'] = "center";
         $output['config']['xaxis']['mode'] = "categories";
         $output['config']['xaxis']['tickLength'] = 0;
         // Monthly bandwidth - optionally tested against limits
         $xmdsLimit = Config::GetSetting('MONTHLY_XMDS_TRANSFER_LIMIT_KB');
         if ($xmdsLimit > 0) {
             // Convert to MB
             $xmdsLimit = $xmdsLimit / 1024 / 1024;
             // Plot as a line
             $markings = array();
             $markings[] = array('color' => '#FF0000', 'lineWidth' => 2, 'yaxis' => array('from' => $xmdsLimit, 'to' => $xmdsLimit));
             $output['config']['grid']['markings'] = $markings;
         }
         // Set the data
         Theme::Set('bandwidth-widget', json_encode($output));
         // We would also like a library usage pie chart!
         $libraryLimit = Config::GetSetting('LIBRARY_SIZE_LIMIT_KB');
         // Library Size in Bytes
         $sth = $dbh->prepare('SELECT IFNULL(SUM(FileSize), 0) AS SumSize FROM media;');
         $sth->execute();
         $librarySize = $sth->fetchColumn();
         // Pie chart
         $output = array();
         $output['points'][] = array('label' => 'Used', 'data' => (double) $librarySize);
         if ($libraryLimit > 0) {
             $libraryLimit = $libraryLimit * 1024;
             $output['points'][] = array('label' => 'Available', 'data' => (double) $libraryLimit - $librarySize);
         }
         $output['config']['series']['pie']['show'] = true;
         $output['config']['legend']['show'] = false;
         Theme::Set('library-widget', json_encode($output));
         // Also a display widget
         $sort_order = array('display');
         $displays = $this->user->DisplayList($sort_order);
         $rows = array();
         if (is_array($displays) && count($displays) > 0) {
             // Output a table showing the displays
             foreach ($displays as $row) {
                 $row['licensed'] = $row['licensed'] == 1 ? 'icon-ok' : 'icon-remove';
                 $row['loggedin'] = $row['loggedin'] == 1 ? 'icon-ok' : 'icon-remove';
                 $row['mediainventorystatus'] = $row['mediainventorystatus'] == 1 ? 'success' : ($row['mediainventorystatus'] == 2 ? 'error' : 'warning');
                 // Assign this to the table row
                 $rows[] = $row;
             }
         }
         Theme::Set('display-widget-rows', $rows);
     } catch (Exception $e) {
         Debug::LogEntry('error', $e->getMessage());
         // Show the error in place of the bandwidth chart
         Theme::Set('widget-error', 'Unable to get widget details');
     }
     // Do we have an embedded widget?
     Theme::Set('embedded-widget', html_entity_decode(Config::GetSetting('EMBEDDED_STATUS_WIDGET')));
     // Render the Theme and output
     Theme::Render('status_dashboard');
 }
Example #14
0
 private function getForecastData($displayId)
 {
     $defaultLat = Config::GetSetting('DEFAULT_LAT');
     $defaultLong = Config::GetSetting('DEFAULT_LONG');
     if ($this->GetOption('useDisplayLocation') == 1) {
         // Use the display ID or the default.
         if ($displayId != 0) {
             $display = new Display();
             $display->displayId = $displayId;
             $display->Load();
             $defaultLat = $display->latitude;
             $defaultLong = $display->longitude;
         }
     } else {
         $defaultLat = $this->GetOption('latitude', $defaultLat);
         $defaultLong = $this->GetOption('longitude', $defaultLong);
     }
     $apiKey = $this->GetSetting('apiKey');
     if ($apiKey == '') {
         die(__('Incorrectly configured module'));
     }
     // Query the API and Dump the Results.
     $forecast = new Forecast($apiKey);
     $apiOptions = array('units' => $this->GetOption('units', 'auto'), 'lang' => $this->GetOption('lang', 'en'), 'exclude' => 'flags,minutely,hourly');
     $key = md5($defaultLat . $defaultLong . 'null' . implode('.', $apiOptions));
     if (!Cache::has($key)) {
         Debug::LogEntry('audit', 'Getting Forecast from the API', $this->type, __FUNCTION__);
         if (!($data = $forecast->get($defaultLat, $defaultLong, null, $apiOptions))) {
             return false;
         }
         // If the response is empty, cache it for less time
         $cacheDuration = $this->GetSetting('cachePeriod');
         // Cache
         Cache::put($key, $data, $cacheDuration);
     } else {
         Debug::LogEntry('audit', 'Getting Forecast from the Cache with key: ' . $key, $this->type, __FUNCTION__);
         $data = Cache::get($key);
     }
     //Debug::Audit('Data: ' . var_export($data, true));
     // Icon Mappings
     $icons = array('unmapped' => 'wi-alien', 'clear-day' => 'wi-day-sunny', 'clear-night' => 'wi-night-clear', 'rain' => 'wi-rain', 'snow' => 'wi-snow', 'sleet' => 'wi-hail', 'wind' => 'wi-windy', 'fog' => 'wi-fog', 'cloudy' => 'wi-cloudy', 'partly-cloudy-day' => 'wi-day-cloudy', 'partly-cloudy-night' => 'wi-night-partly-cloudy');
     // Temperature Unit Mappings
     $temperatureUnit = '';
     foreach ($this->unitsAvailable() as $unit) {
         if ($unit['id'] == $this->GetOption('units', 'auto')) {
             $temperatureUnit = $unit['tempUnit'];
             break;
         }
     }
     // Are we set to only show daytime weather conditions?
     if ($this->GetOption('dayConditionsOnly') == 1) {
         if ($data->currently->icon == 'partly-cloudy-night') {
             $data->currently->icon = 'clear-day';
         }
     }
     $data->currently->wicon = isset($icons[$data->currently->icon]) ? $icons[$data->currently->icon] : $icons['unmapped'];
     $data->currently->temperatureFloor = isset($data->currently->temperature) ? floor($data->currently->temperature) : '--';
     $data->currently->summary = isset($data->currently->summary) ? $data->currently->summary : '--';
     $data->currently->weekSummary = isset($data->daily->summary) ? $data->daily->summary : '--';
     $data->currently->temperatureUnit = $temperatureUnit;
     // Convert a stdObject to an array
     $data = json_decode(json_encode($data), true);
     // Process the icon for each day
     for ($i = 0; $i < 7; $i++) {
         // Are we set to only show daytime weather conditions?
         if ($this->GetOption('dayConditionsOnly') == 1) {
             if ($data['daily']['data'][$i]['icon'] == 'partly-cloudy-night') {
                 $data['daily']['data'][$i]['icon'] = 'clear-day';
             }
         }
         $data['daily']['data'][$i]['wicon'] = isset($icons[$data['daily']['data'][$i]['icon']]) ? $icons[$data['daily']['data'][$i]['icon']] : $icons['unmapped'];
         $data['daily']['data'][$i]['temperatureMaxFloor'] = isset($data['daily']['data'][$i]['temperatureMax']) ? floor($data['daily']['data'][$i]['temperatureMax']) : '--';
         $data['daily']['data'][$i]['temperatureMinFloor'] = isset($data['daily']['data'][$i]['temperatureMin']) ? floor($data['daily']['data'][$i]['temperatureMin']) : '--';
         $data['daily']['data'][$i]['temperatureFloor'] = $data['daily']['data'][$i]['temperatureMinFloor'] != '--' && $data['daily']['data'][$i]['temperatureMaxFloor'] != '--' ? floor(($data['daily']['data'][$i]['temperatureMinFloor'] + $data['daily']['data'][$i]['temperatureMaxFloor']) / 2) : '--';
         $data['daily']['data'][$i]['temperatureUnit'] = $temperatureUnit;
     }
     return $data;
 }
Example #15
0
 if (Config::GetSetting("MAINTENANCE_STAT_MAXAGE") != 0 && Kit::GetParam('quick', _REQUEST, _INT) != 1) {
     $maxage = date("Y-m-d H:i:s", time() - 86400 * Kit::ValidateParam(Config::GetSetting("MAINTENANCE_STAT_MAXAGE"), _INT));
     try {
         $dbh = PDOConnect::init();
         $sth = $dbh->prepare('DELETE FROM `stat` WHERE statDate < :maxage');
         $sth->execute(array('maxage' => $maxage));
         print __('Done.');
     } catch (Exception $e) {
         Debug::LogEntry('error', $e->getMessage());
     }
 } else {
     print "-&gt;" . __("Disabled") . "<br/>\n";
 }
 flush();
 // Validate Display Licence Slots
 $maxDisplays = Config::GetSetting('MAX_LICENSED_DISPLAYS');
 if ($maxDisplays > 0) {
     print '<h1>' . __('Licence Slot Validation') . '</h1>';
     // Get a list of all displays
     try {
         $dbh = PDOConnect::init();
         $sth = $dbh->prepare('SELECT displayId, display FROM `display` WHERE licensed = 1 ORDER BY lastAccessed');
         $sth->execute();
         $displays = $sth->fetchAll(PDO::FETCH_ASSOC);
         if (count($displays) > $maxDisplays) {
             // :(
             // We need to un-licence some displays
             $difference = count($displays) - $maxDisplays;
             $update = $dbh->prepare('UPDATE `display` SET licensed = 0 WHERE displayId = :displayId');
             foreach ($displays as $display) {
                 // If we are down to 0 difference, then stop
Example #16
0
 public function Edit()
 {
     // Check the token
     if (!Kit::CheckToken()) {
         trigger_error(__('Sorry the form has expired. Please refresh.'), E_USER_ERROR);
     }
     $db =& $this->db;
     $response = new ResponseManager();
     // Can we edit?
     if (Config::GetSetting('MODULE_CONFIG_LOCKED_CHECKB') == 'Checked') {
         trigger_error(__('Module Config Locked'), E_USER_ERROR);
     }
     $moduleId = Kit::GetParam('ModuleID', _POST, _INT);
     $type = Kit::GetParam('type', _POST, _WORD);
     $validExtensions = Kit::GetParam('ValidExtensions', _POST, _STRING, '');
     $imageUri = Kit::GetParam('ImageUri', _POST, _STRING);
     $enabled = Kit::GetParam('Enabled', _POST, _CHECKBOX);
     $previewEnabled = Kit::GetParam('PreviewEnabled', _POST, _CHECKBOX);
     // 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 = 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);
         $response->Respond();
     } catch (Exception $e) {
         Debug::LogEntry('error', $e->getMessage());
         if (!$this->IsError()) {
             $this->SetError(1, __('Unknown Error'));
         }
         trigger_error(__('Unable to update module'), E_USER_ERROR);
     }
 }
Example #17
0
 /**
  * Gets a Unix Timestamp from a textual date time string
  * @param string $date
  * @return int
  */
 public static function getTimestampFromString($date)
 {
     $timestamp = strtotime($date);
     // If we are Jalali, then we want to convert from Jalali back to Gregorian. Otherwise assume input is already Gregorian.
     if (Config::GetSetting('CALENDAR_TYPE') == 'Jalali') {
         // Split the time stamp into its component parts and pass it to the conversion.
         $date = trim($date);
         $split = stripos($date, ' ') > 0 ? explode(' ', $date) : array($date, '');
         $dateSplit = explode('-', $split[0]);
         $date = jDateTime::toGregorian($dateSplit[0], $dateSplit[1], $dateSplit[2]);
         //Debug::Audit('Converted to Gregorian from Jalali: ' . var_export($date, true));
         // Convert that back into a date using strtotime - the date is now Gregorian
         $timestamp = strtotime($date[0] . '-' . $date[1] . '-' . $date[2] . ' ' . $split[1]);
     }
     return $timestamp;
 }
Example #18
0
 public function ScheduleNowForm()
 {
     $db =& $this->db;
     $user =& $this->user;
     $response = new ResponseManager();
     $date = time();
     // We might have a layout id, or a display id
     $campaignId = Kit::GetParam('CampaignID', _GET, _INT, 0);
     $displayGroupIds = Kit::GetParam('displayGroupId', _GET, _ARRAY);
     Theme::Set('form_id', 'ScheduleNowForm');
     Theme::Set('form_action', 'index.php?p=schedule&q=ScheduleNow');
     $formFields = array();
     // Generate a list of layouts.
     $layouts = $user->CampaignList(NULL, false, false);
     $optionGroups = array(array('id' => 'campaign', 'label' => __('Campaigns')), array('id' => 'layout', 'label' => __('Layouts')));
     $layoutOptions = array();
     $campaignOptions = array();
     foreach ($layouts as $layout) {
         if ($layout['islayoutspecific'] == 1) {
             $layoutOptions[] = array('id' => $layout['campaignid'], 'value' => $layout['campaign']);
         } else {
             $campaignOptions[] = array('id' => $layout['campaignid'], 'value' => $layout['campaign']);
         }
     }
     $formFields[] = FormManager::AddCombo('CampaignID', __('Layout'), $campaignId, array('campaign' => $campaignOptions, 'layout' => $layoutOptions), 'id', 'value', __('Please select a Layout or Campaign for this Event to show'), 'l', '', true, '', '', '', $optionGroups);
     $formFields[] = FormManager::AddText('hours', __('Hours'), NULL, __('Hours this event should be scheduled for'), 'h', '');
     $formFields[] = FormManager::AddText('minutes', __('Minutes'), NULL, __('Minutes this event should be scheduled for'), 'h', '');
     $formFields[] = FormManager::AddText('seconds', __('Seconds'), NULL, __('Seconds this event should be scheduled for'), 'h', '');
     // List of Display Groups
     $optionGroups = array(array('id' => 'group', 'label' => __('Groups')), array('id' => 'display', 'label' => __('Displays')));
     $groups = array();
     $displays = array();
     $scheduleWithView = Config::GetSetting('SCHEDULE_WITH_VIEW_PERMISSION') == 'Yes';
     foreach ($this->user->DisplayGroupList(-1) as $display) {
         // Can schedule with view, but no view permissions
         if ($scheduleWithView && $display['view'] != 1) {
             continue;
         }
         // Can't schedule with view, but no edit permissions
         if (!$scheduleWithView && $display['edit'] != 1) {
             continue;
         }
         $display['checked_text'] = in_array($display['displaygroupid'], $displayGroupIds) ? ' selected' : '';
         if ($display['isdisplayspecific'] == 1) {
             $displays[] = $display;
         } else {
             $groups[] = $display;
         }
     }
     $formFields[] = FormManager::AddMultiCombo('DisplayGroupIDs[]', __('Display'), $displayGroupIds, array('group' => $groups, 'display' => $displays), 'displaygroupid', 'displaygroup', __('Please select one or more displays / groups for this event to be shown on.'), 'd', '', true, '', '', '', $optionGroups, array(array('name' => 'data-live-search', 'value' => "true"), array('name' => 'data-selected-text-format', 'value' => "count > 4")));
     $formFields[] = FormManager::AddNumber('DisplayOrder', __('Display Order'), 0, __('Should this event have an order?'), 'o', '');
     $formFields[] = FormManager::AddCheckbox('is_priority', __('Priority?'), NULL, __('Sets whether or not this event has priority. If set the event will be show in preference to other events.'), 'p');
     Theme::Set('form_fields', $formFields);
     $response->SetFormRequestResponse(NULL, __('Schedule Now'), '700px', '400px');
     $response->callBack = 'setupScheduleNowForm';
     $response->AddButton(__('Help'), "XiboHelpRender('index.php?p=help&q=Display&Topic=Schedule&Category=ScheduleNow')");
     $response->AddButton(__('Cancel'), 'XiboDialogClose()');
     $response->AddButton(__('Save'), '$("#ScheduleNowForm").submit()');
     $response->Respond();
 }
Example #19
0
 public function Boot()
 {
     global $db;
     // On upgrade, fix all of the layouts, excluding the default
     $campaign = new Campaign($db);
     $SQL = "SELECT LayoutID, Layout, UserID FROM layout WHERE layout <> 'Default Layout'";
     $layouts = $db->GetArray($SQL);
     // Create a campaign record for all of the layouts that currently exist
     foreach ($layouts as $layout) {
         $layoutId = $layout['LayoutID'];
         $campaignId = $campaign->Add($layout['Layout'], 1, $layout['UserID']);
         $campaign->Link($campaignId, $layoutId, 1);
         // Update Security
         $SQL = "INSERT INTO lkcampaigngroup (CampaignID, GroupID, View, Edit, Del) ";
         $SQL .= " SELECT '{$campaignId}', GroupID, View, Edit, Del ";
         $SQL .= "  FROM lklayoutgroup ";
         $SQL .= " WHERE lklayoutgroup.LayoutID = {$layoutId}";
         $db->query($SQL);
         // Update Events
         $db->query("UPDATE schedule SET layoutid = '{$campaignId}' WHERE layoutid = '{$layoutId}'");
         $db->query("UPDATE schedule_detail SET layoutid = '{$campaignId}' WHERE layoutid = '{$layoutId}'");
     }
     // Also run a script to tidy up orphaned media in the library
     $library = Config::GetSetting('LIBRARY_LOCATION');
     $library = rtrim($library, '/') . '/';
     // Dump the files in the temp folder
     foreach (scandir($library . 'temp') as $item) {
         if ($item == '.' || $item == '..') {
             continue;
         }
         unlink($library . 'temp' . DIRECTORY_SEPARATOR . $item);
     }
     // Have commented this block out, as am not 100% convinced that it doesn't
     // delete things it shouldn't
     //
     // Get a list of all media files
     //        foreach(scandir($library) as $file)
     //        {
     //            if ($file == '.' || $file == '..')
     //                continue;
     //
     //            if (is_dir($library . $file))
     //                continue;
     //
     //            $rowCount = $db->GetCountOfRows("SELECT * FROM media WHERE storedAs = '" . $file . "'");
     //
     //            // For each media file, check to see if the file still exists in the library
     //            if ($rowCount == 0)
     //            {
     //                // If not, delete it
     //                unlink($library . $file);
     //
     //                if (file_exists($library . 'tn_' . $file))
     //                {
     //                    unlink($library . 'tn_' . $file);
     //                }
     //
     //                if (file_exists($library . 'bg_' . $file))
     //                {
     //                    unlink($library . 'bg_' . $file);
     //                }
     //            }
     //        }
     return true;
 }
Example #20
0
 /**
  * End point for jQuery file uploader
  */
 public function JqueryFileUpload()
 {
     $db =& $this->db;
     require_once "3rdparty/jquery-file-upload/UploadHandler.php";
     $type = Kit::GetParam('type', _REQUEST, _WORD);
     Kit::ClassLoader('file');
     $fileObject = new File($db);
     $libraryFolder = Config::GetSetting('LIBRARY_LOCATION');
     // Make sure the library exists
     $fileObject->EnsureLibraryExists();
     // Get Valid Extensions
     Kit::ClassLoader('media');
     $media = new Media($db);
     $validExt = $media->ValidExtensions($type);
     $options = array('upload_dir' => $libraryFolder . 'temp/', 'download_via_php' => true, 'script_url' => Kit::GetXiboRoot() . '?p=content&q=JqueryFileUpload', 'upload_url' => Kit::GetXiboRoot() . '?p=content&q=JqueryFileUpload', 'image_versions' => array(), 'accept_file_types' => '/\\.' . implode('|', $validExt) . '$/i');
     // Hand off to the Upload Handler provided by jquery-file-upload
     $handler = new UploadHandler($db, $this->user, $options);
     // Must commit if in a transaction
     try {
         $dbh = PDOConnect::init();
         $dbh->commit();
     } catch (Exception $e) {
         Debug::LogEntry('audit', 'Unable to commit/rollBack');
     }
     // Must prevent from continuing (framework will try to issue a response)
     exit;
 }
Example #21
0
 function forgotten()
 {
     //Called by a submit to the Forgotten Details form
     //	Checks the validity of the data provided, and emails a new password to the user
     $db =& $this->db;
     $username = Kit::GetParam('f_username', _POST, _USERNAME);
     $email = Kit::GetParam('f_email', _POST, _STRING);
     $return = "index.php";
     if ($username == "" || $email == "") {
         setMessage("Username and Email address need to be filled in");
         return $return;
     }
     //send the email
     $from = Config::GetSetting("mail_from");
     if ($from == "") {
         setMessage("Email is not set up, please contact your IT manager");
         return $return;
     }
     //check the user details
     $SQL = sprintf("SELECT userid FROM user WHERE username = '******' AND email = '%s'", $db->escape_string($username), $db->escape_string($email));
     if (!($results = $db->query($SQL))) {
         trigger_error($db->error);
         trigger_error("Can not get the user information", E_USER_ERROR);
     }
     if ($db->num_rows($results) < 0 || $db->num_rows($results) > 1) {
         setMessage("The details you entered are incorrect.");
         return $return;
     }
     $row = $db->get_row($results);
     $userid = Kit::ValidateParam($row[0], _INT);
     //user ID for the user that wants a new password
     $password_plain = $this->random_word(8);
     //generate a new password
     $password = md5($password_plain);
     //update the password
     $SQL = sprintf("UPDATE user SET UserPassword = '******' WHERE userid = %d", $db->escape_string($password), $userid);
     if (!$db->query($SQL)) {
         trigger_error($db->error());
         trigger_error("Unable to send new password", E_USER_ERROR);
     }
     $headers = "From: {$from}" . "\r\n" . "Reply-To: {$from}" . "\r\n" . "X-Mailer: PHP/" . phpversion();
     if (!@mail($email, "Xibo: New Password request for {$username}", "Your new password is {$password_plain} \n  . You may now login with these details.", $headers)) {
         setMessage("Email is not set up, please contact your IT manager");
         return $return;
     }
     setMessage("New Password Sent to your email address");
     return $return;
 }
Example #22
0
 public static function IssueStsHeaderIfNecessary()
 {
     if (Config::GetSetting('ISSUE_STS', 0) == 1) {
         header("strict-transport-security: max-age=" . Config::GetSetting('STS_TTL', 600));
     }
 }
Example #23
0
 public function Edit()
 {
     // Check the token
     if (!Kit::CheckToken()) {
         trigger_error('Token does not match', E_USER_ERROR);
     }
     $db =& $this->db;
     $response = new ResponseManager();
     // Can we edit?
     if (Config::GetSetting('MODULE_CONFIG_LOCKED_CHECKB') == 'Checked') {
         trigger_error(__('Module Config Locked'), E_USER_ERROR);
     }
     $moduleId = Kit::GetParam('ModuleID', _POST, _INT);
     $validExtensions = Kit::GetParam('ValidExtensions', _POST, _STRING, '');
     $imageUri = Kit::GetParam('ImageUri', _POST, _STRING);
     $enabled = Kit::GetParam('Enabled', _POST, _CHECKBOX);
     $previewEnabled = Kit::GetParam('PreviewEnabled', _POST, _CHECKBOX);
     // Validation
     if ($moduleId == 0 || $moduleId == '') {
         trigger_error(__('Module ID is missing'), E_USER_ERROR);
     }
     if ($imageUri == '') {
         trigger_error(__('Image Uri is a required field.'), E_USER_ERROR);
     }
     // Deal with the Edit
     $SQL = "UPDATE `module` SET ImageUri = '%s', ValidExtensions = '%s', Enabled = %d, PreviewEnabled = %d WHERE ModuleID = %d";
     $SQL = sprintf($SQL, $db->escape_string($imageUri), $db->escape_string($validExtensions), $enabled, $previewEnabled, $moduleId);
     if (!$db->query($SQL)) {
         trigger_error($db->error());
         trigger_error(__('Unable to update module'), E_USER_ERROR);
     }
     $response->SetFormSubmitResponse(__('Module Edited'), false);
     $response->Respond();
 }
Example #24
0
 protected function getTwitterFeed($displayId = 0, $isPreview = true)
 {
     if (!extension_loaded('curl')) {
         trigger_error(__('cURL extension is required for Twitter'));
         return false;
     }
     // Do we need to add a geoCode?
     $geoCode = '';
     $distance = $this->GetOption('tweetDistance');
     if ($distance != 0) {
         // Use the display ID or the default.
         if ($displayId != 0) {
             // Look up the lat/long
             $display = new Display();
             $display->displayId = $displayId;
             $display->Load();
             $defaultLat = $display->latitude;
             $defaultLong = $display->longitude;
         } else {
             $defaultLat = Config::GetSetting('DEFAULT_LAT');
             $defaultLong = Config::GetSetting('DEFAULT_LONG');
         }
         // Built the geoCode string.
         $geoCode = implode(',', array($defaultLat, $defaultLong, $distance)) . 'mi';
     }
     // Connect to twitter and get the twitter feed.
     $key = md5($this->GetOption('searchTerm') . $this->GetOption('resultType') . $this->GetOption('tweetCount', 15) . $geoCode);
     if (!Cache::has($key) || Cache::get($key) == '') {
         Debug::Audit('Querying API for ' . $this->GetOption('searchTerm'));
         // We need to search for it
         if (!($token = $this->getToken())) {
             return false;
         }
         // We have the token, make a tweet
         if (!($data = $this->searchApi($token, $this->GetOption('searchTerm'), $this->GetOption('resultType'), $geoCode, $this->GetOption('tweetCount', 15)))) {
             return false;
         }
         // Cache it
         Cache::put($key, $data, $this->GetSetting('cachePeriod'));
     } else {
         Debug::Audit('Served from Cache');
         $data = Cache::get($key);
     }
     Debug::Audit(var_export(json_encode($data), true));
     // Get the template
     $template = $this->GetRawNode('template');
     // Parse the text template
     $matches = '';
     preg_match_all('/\\[.*?\\]/', $template, $matches);
     // Build an array to return
     $return = array();
     // Media Object to get profile images
     $media = new Media();
     $layout = new Layout();
     // Expiry time for any media that is downloaded
     $expires = time() + $this->GetSetting('cachePeriodImages') * 60 * 60;
     // Remove URL setting
     $removeUrls = $this->GetOption('removeUrls', 1);
     // If we have nothing to show, display a no tweets message.
     if (count($data->statuses) <= 0) {
         // Create ourselves an empty tweet so that the rest of the code can continue as normal
         $user = new stdClass();
         $user->name = '';
         $user->screen_name = '';
         $user->profile_image_url = '';
         $tweet = new stdClass();
         $tweet->text = $this->GetOption('noTweetsMessage', __('There are no tweets to display'));
         $tweet->created_at = date("Y-m-d H:i:s");
         $tweet->user = $user;
         // Append to our statuses
         $data->statuses[] = $tweet;
     }
     // This should return the formatted items.
     foreach ($data->statuses as $tweet) {
         // Substitute for all matches in the template
         $rowString = $template;
         foreach ($matches[0] as $sub) {
             // Always clear the stored template replacement
             $replace = '';
             // Maybe make this more generic?
             switch ($sub) {
                 case '[Tweet]':
                     // Get the tweet text to operate on
                     $tweetText = $tweet->text;
                     // Replace URLs with their display_url before removal
                     if (isset($tweet->entities->urls)) {
                         foreach ($tweet->entities->urls as $url) {
                             $tweetText = str_replace($url->url, $url->display_url, $tweetText);
                         }
                     }
                     // Handle URL removal if requested
                     if ($removeUrls == 1) {
                         $tweetText = preg_replace("((https?|ftp|gopher|telnet|file|notes|ms-help):((\\/\\/)|(\\\\))+[\\w\\d:#\\@%\\/;\$()~_?\\+-=\\\\.&]*)", '', $tweetText);
                     }
                     $replace = emoji_unified_to_html($tweetText);
                     break;
                 case '[User]':
                     $replace = $tweet->user->name;
                     break;
                 case '[ScreenName]':
                     $replace = $tweet->user->screen_name;
                     break;
                 case '[Date]':
                     $replace = date($this->GetOption('dateFormat', Config::GetSetting('DATE_FORMAT')), DateManager::getDateFromGregorianString($tweet->created_at));
                     break;
                 case '[ProfileImage]':
                     // Grab the profile image
                     if ($tweet->user->profile_image_url != '') {
                         $file = $media->addModuleFileFromUrl($tweet->user->profile_image_url, 'twitter_' . $tweet->user->id, $expires);
                         // Tag this layout with this file
                         $layout->AddLk($this->layoutid, 'module', $file['mediaId']);
                         $replace = $isPreview ? '<img src="index.php?p=module&mod=image&q=Exec&method=GetResource&mediaid=' . $file['mediaId'] . '" />' : '<img src="' . $file['storedAs'] . '" />';
                     }
                     break;
                 case '[Photo]':
                     // See if there are any photos associated with this tweet.
                     if (isset($tweet->entities->media) && count($tweet->entities->media) > 0) {
                         // Only take the first one
                         $photoUrl = $tweet->entities->media[0]->media_url;
                         if ($photoUrl != '') {
                             $file = $media->addModuleFileFromUrl($photoUrl, 'twitter_photo_' . $tweet->user->id . '_' . $tweet->entities->media[0]->id_str, $expires);
                             $replace = $isPreview ? '<img src="index.php?p=module&mod=image&q=Exec&method=GetResource&mediaid=' . $file['mediaId'] . '" />' : '<img src="' . $file['storedAs'] . '" />';
                             // Tag this layout with this file
                             $layout->AddLk($this->layoutid, 'module', $file['mediaId']);
                         }
                     }
                     break;
                 default:
                     $replace = '';
             }
             $rowString = str_replace($sub, $replace, $rowString);
         }
         // Substitute the replacement we have found (it might be '')
         $return[] = $rowString;
     }
     // Return the data array
     return $return;
 }
Example #25
0
     if (method_exists($oauth, $method)) {
         $oauth->{$method}();
     } else {
         $serviceResponse->ErrorServerError('Unknown Request.');
     }
     break;
 case 'rest':
     $serviceResponse->StartTransaction();
     // OAuth authorization.
     if (OAuthRequestVerifier::requestIsSigned()) {
         try {
             $request = new OAuthRequestVerifier();
             $userID = $request->verify();
             if ($userID) {
                 // Create the login control system.
                 $userClass = Config::GetSetting('userModule');
                 $userClass = explode('.', $userClass);
                 Kit::ClassLoader($userClass[0]);
                 // Create a user.
                 $user = new User($db);
                 // Log this user in.
                 if (!$user->LoginServices($userID)) {
                     $serviceResponse->ErrorServerError('Unknown User.');
                 }
             } else {
                 $serviceResponse->ErrorServerError('No user id.');
             }
         } catch (OAuthException $e) {
             $serviceResponse->ErrorServerError('Request signed but Unauthorized.');
         }
     } else {
Example #26
0
 /**
  * Export a layout.
  * @param [type] $layoutId [description]
  */
 function Export($layoutId)
 {
     if ($layoutId == 0 || $layoutId == '') {
         return $this->SetError(__('Must provide layoutId'));
     }
     $config = new Config();
     if (!$config->CheckZip()) {
         return $this->SetError(__('Zip is not enabled on this server'));
     }
     $libraryPath = Config::GetSetting('LIBRARY_LOCATION');
     try {
         $dbh = PDOConnect::init();
         $sth = $dbh->prepare('
             SELECT layout, description, backgroundImageId, xml
               FROM layout
              WHERE layoutid = :layoutid');
         $sth->execute(array('layoutid' => $layoutId));
         if (!($row = $sth->fetch())) {
             $this->ThrowError(__('Layout not found.'));
         }
         // Open a ZIP file with the same name as the layout
         File::EnsureLibraryExists();
         $zip = new ZipArchive();
         $fileName = $libraryPath . 'temp/export_' . Kit::ValidateParam($row['layout'], _FILENAME) . '.zip';
         $result = $zip->open($fileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
         if ($result !== true) {
             $this->ThrowError(__('Can\'t create ZIP. Error Code: ' . $result));
         }
         // Add layout information to the ZIP
         $layout = array('layout' => Kit::ValidateParam($row['layout'], _STRING), 'description' => Kit::ValidateParam($row['description'], _STRING));
         $zip->addFromString('layout.json', json_encode($layout));
         // Add the layout XLF
         $xml = $row['xml'];
         $zip->addFromString('layout.xml', $xml);
         $params = array('layoutid' => $layoutId, 'excludeType' => 'module');
         $SQL = ' 
             SELECT media.mediaid, media.name, media.storedAs, originalFileName, type, duration
               FROM `media` 
                 INNER JOIN `lklayoutmedia`
                 ON lklayoutmedia.mediaid = media.mediaid
              WHERE lklayoutmedia.layoutid = :layoutid
                AND media.type <> :excludeType
             ';
         // Add the media to the ZIP
         $mediaSth = $dbh->prepare($SQL);
         $mediaSth->execute($params);
         $mappings = array();
         foreach ($mediaSth->fetchAll() as $media) {
             $mediaFilePath = $libraryPath . $media['storedAs'];
             $zip->addFile($mediaFilePath, 'library/' . $media['originalFileName']);
             $mappings[] = array('file' => $media['originalFileName'], 'mediaid' => $media['mediaid'], 'name' => $media['name'], 'type' => $media['type'], 'duration' => $media['duration'], 'background' => $media['mediaid'] == $row['backgroundImageId'] ? 1 : 0);
         }
         // Add the mappings file to the ZIP
         $zip->addFromString('mapping.json', json_encode($mappings));
         $zip->close();
         // Uncomment only if you are having permission issues
         // chmod($fileName, 0777);
         // Push file back to browser
         if (ini_get('zlib.output_compression')) {
             ini_set('zlib.output_compression', 'Off');
         }
         $size = filesize($fileName);
         header('Content-Type: application/octet-stream');
         header("Content-Transfer-Encoding: Binary");
         header("Content-disposition: attachment; filename=\"" . basename($fileName) . "\"");
         //Output a header
         header('Pragma: public');
         header('Cache-Control: max-age=86400');
         header('Expires: ' . gmdate('D, d M Y H:i:s \\G\\M\\T', time() + 86400));
         header('Content-Length: ' . $size);
         // Send via Apache X-Sendfile header?
         if (Config::GetSetting('SENDFILE_MODE') == 'Apache') {
             header("X-Sendfile: {$fileName}");
             exit;
         }
         // Send via Nginx X-Accel-Redirect?
         if (Config::GetSetting('SENDFILE_MODE') == 'Nginx') {
             header("X-Accel-Redirect: /download/temp/" . basename($fileName));
             exit;
         }
         // Return the file with PHP
         // Disable any buffering to prevent OOM errors.
         @ob_end_clean();
         @ob_end_flush();
         readfile($fileName);
         exit;
     } catch (Exception $e) {
         Debug::LogEntry('error', $e->getMessage());
         if (!$this->IsError()) {
             $this->SetError(1, __('Unknown Error'));
         }
         return false;
     }
 }
Example #27
0
 public function __construct($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false)
 {
     if (class_exists('idna_convert')) {
         $idn = new idna_convert();
         $parsed = SimplePie_Misc::parse_url($url);
         $url = SimplePie_Misc::compress_parse_url($parsed['scheme'], $idn->encode($parsed['authority']), $parsed['path'], $parsed['query'], $parsed['fragment']);
     }
     $this->url = $url;
     $this->useragent = $useragent;
     if (preg_match('/^http(s)?:\\/\\//i', $url)) {
         if ($useragent === null) {
             $useragent = ini_get('user_agent');
             $this->useragent = $useragent;
         }
         if (!is_array($headers)) {
             $headers = array();
         }
         if (!$force_fsockopen && function_exists('curl_exec')) {
             $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_CURL;
             $fp = curl_init();
             $headers2 = array();
             foreach ($headers as $key => $value) {
                 $headers2[] = "{$key}: {$value}";
             }
             if (version_compare(SimplePie_Misc::get_curl_version(), '7.10.5', '>=')) {
                 curl_setopt($fp, CURLOPT_ENCODING, '');
             }
             curl_setopt($fp, CURLOPT_URL, $url);
             curl_setopt($fp, CURLOPT_HEADER, 1);
             curl_setopt($fp, CURLOPT_RETURNTRANSFER, 1);
             curl_setopt($fp, CURLOPT_TIMEOUT, $timeout);
             curl_setopt($fp, CURLOPT_CONNECTTIMEOUT, $timeout);
             curl_setopt($fp, CURLOPT_REFERER, $url);
             curl_setopt($fp, CURLOPT_USERAGENT, $useragent);
             curl_setopt($fp, CURLOPT_HTTPHEADER, $headers2);
             if (!ini_get('open_basedir') && !ini_get('safe_mode') && version_compare(SimplePie_Misc::get_curl_version(), '7.15.2', '>=')) {
                 curl_setopt($fp, CURLOPT_FOLLOWLOCATION, 1);
                 curl_setopt($fp, CURLOPT_MAXREDIRS, $redirects);
             }
             // Dan Garner PATCH
             if (Config::GetSetting('PROXY_HOST') != '' && !Config::isProxyException($url)) {
                 curl_setopt($fp, CURLOPT_PROXY, Config::GetSetting('PROXY_HOST'));
                 curl_setopt($fp, CURLOPT_PROXYPORT, Config::GetSetting('PROXY_PORT'));
                 if (Config::GetSetting('PROXY_AUTH') != '') {
                     curl_setopt($fp, CURLOPT_PROXYUSERPWD, Config::GetSetting('PROXY_AUTH'));
                 }
             }
             $this->headers = curl_exec($fp);
             if (curl_errno($fp) === 23 || curl_errno($fp) === 61) {
                 curl_setopt($fp, CURLOPT_ENCODING, 'none');
                 $this->headers = curl_exec($fp);
             }
             if (curl_errno($fp)) {
                 $this->error = 'cURL error ' . curl_errno($fp) . ': ' . curl_error($fp);
                 $this->success = false;
             } else {
                 $info = curl_getinfo($fp);
                 curl_close($fp);
                 // Remove headers from redirects
                 $this->headers = explode("\r\n\r\n", $this->headers, $info['redirect_count'] + 1);
                 $this->headers = array_pop($this->headers);
                 // DG: Patch to strip double headers for HTTPS Proxies (they add headers without incrementing redirect count)
                 $this->headers = SimplePie_HTTP_Parser::strip_double_headers($this->headers);
                 //Debug::Audit('Headers: ' . var_export($this->headers, true));
                 $parser = new SimplePie_HTTP_Parser($this->headers);
                 if ($parser->parse()) {
                     $this->headers = $parser->headers;
                     $this->body = $parser->body;
                     $this->status_code = $parser->status_code;
                     if ((in_array($this->status_code, array(300, 301, 302, 303, 307)) || $this->status_code > 307 && $this->status_code < 400) && isset($this->headers['location']) && $this->redirects < $redirects) {
                         $this->redirects++;
                         $location = SimplePie_Misc::absolutize_url($this->headers['location'], $url);
                         return $this->__construct($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen);
                     }
                 }
             }
         } else {
             $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_FSOCKOPEN;
             $url_parts = parse_url($url);
             $socket_host = $url_parts['host'];
             if (isset($url_parts['scheme']) && strtolower($url_parts['scheme']) === 'https') {
                 $socket_host = "ssl://{$url_parts['host']}";
                 $url_parts['port'] = 443;
             }
             if (!isset($url_parts['port'])) {
                 $url_parts['port'] = 80;
             }
             $fp = @fsockopen($socket_host, $url_parts['port'], $errno, $errstr, $timeout);
             if (!$fp) {
                 $this->error = 'fsockopen error: ' . $errstr;
                 $this->success = false;
             } else {
                 stream_set_timeout($fp, $timeout);
                 if (isset($url_parts['path'])) {
                     if (isset($url_parts['query'])) {
                         $get = "{$url_parts['path']}?{$url_parts['query']}";
                     } else {
                         $get = $url_parts['path'];
                     }
                 } else {
                     $get = '/';
                 }
                 $out = "GET {$get} HTTP/1.1\r\n";
                 $out .= "Host: {$url_parts['host']}\r\n";
                 $out .= "User-Agent: {$useragent}\r\n";
                 if (extension_loaded('zlib')) {
                     $out .= "Accept-Encoding: x-gzip,gzip,deflate\r\n";
                 }
                 if (isset($url_parts['user']) && isset($url_parts['pass'])) {
                     $out .= "Authorization: Basic " . base64_encode("{$url_parts['user']}:{$url_parts['pass']}") . "\r\n";
                 }
                 foreach ($headers as $key => $value) {
                     $out .= "{$key}: {$value}\r\n";
                 }
                 $out .= "Connection: Close\r\n\r\n";
                 fwrite($fp, $out);
                 $info = stream_get_meta_data($fp);
                 $this->headers = '';
                 while (!$info['eof'] && !$info['timed_out']) {
                     $this->headers .= fread($fp, 1160);
                     $info = stream_get_meta_data($fp);
                 }
                 if (!$info['timed_out']) {
                     $parser = new SimplePie_HTTP_Parser($this->headers);
                     if ($parser->parse()) {
                         $this->headers = $parser->headers;
                         $this->body = $parser->body;
                         $this->status_code = $parser->status_code;
                         if ((in_array($this->status_code, array(300, 301, 302, 303, 307)) || $this->status_code > 307 && $this->status_code < 400) && isset($this->headers['location']) && $this->redirects < $redirects) {
                             $this->redirects++;
                             $location = SimplePie_Misc::absolutize_url($this->headers['location'], $url);
                             return $this->__construct($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen);
                         }
                         if (isset($this->headers['content-encoding'])) {
                             // Hey, we act dumb elsewhere, so let's do that here too
                             switch (strtolower(trim($this->headers['content-encoding'], "\t\n\r "))) {
                                 case 'gzip':
                                 case 'x-gzip':
                                     $decoder = new SimplePie_gzdecode($this->body);
                                     if (!$decoder->parse()) {
                                         $this->error = 'Unable to decode HTTP "gzip" stream';
                                         $this->success = false;
                                     } else {
                                         $this->body = $decoder->data;
                                     }
                                     break;
                                 case 'deflate':
                                     if (($decompressed = gzinflate($this->body)) !== false) {
                                         $this->body = $decompressed;
                                     } else {
                                         if (($decompressed = gzuncompress($this->body)) !== false) {
                                             $this->body = $decompressed;
                                         } else {
                                             if (function_exists('gzdecode') && ($decompressed = gzdecode($this->body)) !== false) {
                                                 $this->body = $decompressed;
                                             } else {
                                                 $this->error = 'Unable to decode HTTP "deflate" stream';
                                                 $this->success = false;
                                             }
                                         }
                                     }
                                     break;
                                 default:
                                     $this->error = 'Unknown content coding';
                                     $this->success = false;
                             }
                         }
                     }
                 } else {
                     $this->error = 'fsocket timed out';
                     $this->success = false;
                 }
                 fclose($fp);
             }
         }
     } else {
         $this->method = SIMPLEPIE_FILE_SOURCE_LOCAL | SIMPLEPIE_FILE_SOURCE_FILE_GET_CONTENTS;
         if (!($this->body = file_get_contents($url))) {
             $this->error = 'file_get_contents could not read the file';
             $this->success = false;
         }
     }
 }
Example #28
0
 /**
  * Tidies up the library
  */
 public function tidyLibrary()
 {
     $response = new ResponseManager();
     if (Config::GetSetting('SETTING_LIBRARY_TIDY_ENABLED') != 1) {
         trigger_error(__('Sorry this function is disabled.'), E_USER_ERROR);
     }
     $media = new Media();
     if (!$media->deleteUnusedForUser($this->user->userid)) {
         trigger_error($media->GetErrorMessage(), E_USER_ERROR);
     }
     $response->SetFormSubmitResponse(__('Library Tidy Complete'));
     $response->Respond();
 }
Example #29
0
 public function ScreenShot()
 {
     $displayId = Kit::GetParam('DisplayId', _GET, _INT);
     // Output an image if present, otherwise not found image.
     $file = 'screenshots/' . $displayId . '_screenshot.jpg';
     // File upload directory.. get this from the settings object
     $library = Config::GetSetting("LIBRARY_LOCATION");
     $fileName = $library . $file;
     if (!file_exists($fileName)) {
         $fileName = Theme::ImageUrl('forms/filenotfound.gif');
     }
     $size = filesize($fileName);
     $fi = new finfo(FILEINFO_MIME_TYPE);
     $mime = $fi->file($fileName);
     header("Content-Type: {$mime}");
     //Output a header
     header('Cache-Control: no-cache, must-revalidate');
     header('Content-Length: ' . $size);
     // Return the file with PHP
     // Disable any buffering to prevent OOM errors.
     @ob_end_clean();
     @ob_end_flush();
     readfile($fileName);
 }
Example #30
0
 /**
  * Adds a module file. 
  * Module files are hidden from the UI and supplementary files that will be used
  * by the module that added them.
  * @param string  $file  The path to the file that needs adding
  * @param int[Optional] $expires Expiry time in seconds - default 0
  * @param boolean[Optional] $moduleSystemFile Is this a system file - default true
  * @param boolean[Optional] $force Whether to force an update to the file or not
  * @return array Media File Added
  */
 public function addModuleFile($file, $expires = 0, $moduleSystemFile = true, $force = false)
 {
     try {
         $name = basename($file);
         $media = $this->moduleFileExists($name);
         //Debug::Audit('Module File: ' . var_export($media, true));
         $dbh = PDOConnect::init();
         // Do we need to update this module file (meaning, is it out of date)
         // Why might it be out of date?
         //  - an upgrade might of invalidated it
         // How can we tell?
         // - valid flag on the media
         if ($media !== false && $media['valid'] == 0) {
             Debug::Audit('Media not valid, forcing update.');
             $force = true;
         }
         // Force will be set by now.
         if (!$force && $media !== false) {
             // Nibble on the update date
             $sth = $dbh->prepare('UPDATE `media` SET expires = :expires WHERE mediaId = :mediaId');
             $sth->execute(array('mediaId' => $media['mediaId'], 'expires' => $expires));
             // Need to return the media object
             return $media;
         }
         $libraryFolder = Config::GetSetting('LIBRARY_LOCATION');
         // Get the name
         $storedAs = $libraryFolder . $name;
         Debug::Audit('Updating: ' . $name);
         // Now copy the file
         if (!@copy($file, $storedAs)) {
             $this->ThrowError(15, 'Error storing file.');
         }
         // Calculate the MD5 and the file size
         $md5 = md5_file($storedAs);
         $fileSize = filesize($storedAs);
         if ($media !== false) {
             $SQL = "UPDATE `media` SET md5 = :md5, filesize = :filesize, expires = :expires, moduleSystemFile = :moduleSystemFile WHERE mediaId = :mediaId ";
             $sth = $dbh->prepare($SQL);
             $sth->execute(array('mediaId' => $media['mediaId'], 'filesize' => $fileSize, 'md5' => $md5, 'expires' => $expires, 'moduleSystemFile' => $moduleSystemFile));
             // Update the media array for returning
             $media['expires'] = $expires;
         } else {
             // All OK to insert this record
             $SQL = "INSERT INTO media (name, type, duration, originalFilename, userID, retired, moduleSystemFile, storedAs, FileSize, MD5, expires) ";
             $SQL .= "VALUES (:name, :type, :duration, :originalfilename, 1, :retired, :moduleSystemFile, :storedas, :filesize, :md5, :expires) ";
             $sth = $dbh->prepare($SQL);
             $sth->execute(array('name' => $name, 'type' => 'module', 'duration' => 10, 'originalfilename' => $name, 'retired' => 0, 'storedas' => $name, 'filesize' => $fileSize, 'md5' => $md5, 'moduleSystemFile' => $moduleSystemFile ? 1 : 0, 'expires' => $expires));
             $media = array('mediaId' => $dbh->lastInsertId(), 'storedAs' => $name, 'expires' => $expires);
         }
         // Add to the cache
         $this->_moduleFiles[$name] = $media;
         return $media;
     } catch (Exception $e) {
         Debug::LogEntry('error', $e->getMessage(), get_class(), __FUNCTION__);
         if (!$this->IsError()) {
             $this->SetError(1, __('Unknown Error'));
         }
         return false;
     }
 }