Example #1
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;
 }
 function displayPage()
 {
     // Set up some suffixes
     $suffixes = array('bytes', 'k', 'M', 'G', 'T');
     // Get some data for a bandwidth chart
     try {
         $dbh = PDOConnect::init();
         $sth = $dbh->prepare('SELECT FROM_UNIXTIME(month) AS month, IFNULL(SUM(Size), 0) AS size FROM `bandwidth` WHERE month > :month GROUP BY FROM_UNIXTIME(month) ORDER BY MIN(month);');
         $sth->execute(array('month' => time() - 86400 * 365));
         $results = $sth->fetchAll();
         // Monthly bandwidth - optionally tested against limits
         $xmdsLimit = Config::GetSetting('MONTHLY_XMDS_TRANSFER_LIMIT_KB');
         $maxSize = 0;
         foreach ($results as $row) {
             $maxSize = $row['size'] > $maxSize ? $row['size'] : $maxSize;
         }
         // Decide what our units are going to be, based on the size
         $base = $maxSize == 0 ? 0 : floor(log($maxSize) / log(1024));
         if ($xmdsLimit > 0) {
             // Convert to appropriate size (xmds limit is in KB)
             $xmdsLimit = $xmdsLimit * 1024 / pow(1024, $base);
             Theme::Set('xmdsLimit', $xmdsLimit . ' ' . $suffixes[$base]);
         }
         $output = array();
         foreach ($results as $row) {
             $size = (double) $row['size'] / pow(1024, $base);
             $remaining = $xmdsLimit - $size;
             $output[] = array('label' => DateManager::getLocalDate(DateManager::getDateFromGregorianString($row['month']), 'F'), 'value' => round($size, 2), 'limit' => round($remaining, 2));
         }
         // What if we are empty?
         if (count($output) == 0) {
             $output[] = array('label' => DateManager::getLocalDate(null, 'F'), 'value' => 0, 'limit' => 0);
         }
         // Set the data
         Theme::Set('xmdsLimitSet', $xmdsLimit > 0);
         Theme::Set('bandwidthSuffix', $suffixes[$base]);
         Theme::Set('bandwidthWidget', json_encode($output));
         // We would also like a library usage pie chart!
         $libraryLimit = Config::GetSetting('LIBRARY_SIZE_LIMIT_KB');
         $libraryLimit = $libraryLimit * 1024;
         // Library Size in Bytes
         $sth = $dbh->prepare('SELECT IFNULL(SUM(FileSize), 0) AS SumSize, type FROM media GROUP BY type;');
         $sth->execute();
         $results = $sth->fetchAll();
         // Do we base the units on the maximum size or the library limit
         $maxSize = 0;
         if ($libraryLimit > 0) {
             $maxSize = $libraryLimit;
         } else {
             // Find the maximum sized chunk of the items in the library
             foreach ($results as $library) {
                 $maxSize = $library['SumSize'] > $maxSize ? $library['SumSize'] : $maxSize;
             }
         }
         // Decide what our units are going to be, based on the size
         $base = $maxSize == 0 ? 0 : floor(log($maxSize) / log(1024));
         $output = array();
         $totalSize = 0;
         foreach ($results as $library) {
             $output[] = array('value' => round((double) $library['SumSize'] / pow(1024, $base), 2), 'label' => ucfirst($library['type']));
             $totalSize = $totalSize + $library['SumSize'];
         }
         // Do we need to add the library remaining?
         if ($libraryLimit > 0) {
             $remaining = round(($libraryLimit - $totalSize) / pow(1024, $base), 2);
             $output[] = array('value' => $remaining, 'label' => __('Free'));
         }
         // What if we are empty?
         if (count($output) == 0) {
             $output[] = array('label' => __('Empty'), 'value' => 0);
         }
         Theme::Set('libraryLimitSet', $libraryLimit);
         Theme::Set('libraryLimit', round((double) $libraryLimit / pow(1024, $base), 2) . ' ' . $suffixes[$base]);
         Theme::Set('librarySize', Kit::formatBytes($totalSize, 1));
         Theme::Set('librarySuffix', $suffixes[$base]);
         Theme::Set('libraryWidget', 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['mediainventorystatus'] = $row['mediainventorystatus'] == 1 ? 'success' : ($row['mediainventorystatus'] == 2 ? 'danger' : 'warning');
                 // Assign this to the table row
                 $rows[] = $row;
             }
         }
         Theme::Set('display-widget-rows', $rows);
         // Get a count of users
         $sth = $dbh->prepare('SELECT IFNULL(COUNT(*), 0) AS count_users FROM `user`');
         $sth->execute();
         Theme::Set('countUsers', $sth->fetchColumn(0));
         // Get a count of active layouts
         $sth = $dbh->prepare('SELECT IFNULL(COUNT(*), 0) AS count_scheduled FROM `schedule_detail` WHERE :now BETWEEN FromDT AND ToDT');
         $sth->execute(array('now' => time()));
         Theme::Set('nowShowing', $sth->fetchColumn(0));
         // Latest news
         if (Config::GetSetting('DASHBOARD_LATEST_NEWS_ENABLED') == 1) {
             // Make sure we have the cache location configured
             Kit::ClassLoader('file');
             $file = new File($this->db);
             File::EnsureLibraryExists();
             // Use SimplePie to get the feed
             include_once '3rdparty/simplepie/autoloader.php';
             $feed = new SimplePie();
             $feed->set_cache_location($file->GetLibraryCacheUri());
             $feed->set_feed_url(Theme::GetConfig('latest_news_url'));
             $feed->set_cache_duration(86400);
             $feed->handle_content_type();
             $feed->init();
             $latestNews = array();
             if ($feed->error()) {
                 Debug::LogEntry('audit', 'Feed Error: ' . $feed->error(), get_class(), __FUNCTION__);
             } else {
                 // Store our formatted items
                 foreach ($feed->get_items() as $item) {
                     $latestNews[] = array('title' => $item->get_title(), 'description' => $item->get_description(), 'link' => $item->get_link());
                 }
             }
             Theme::Set('latestNews', $latestNews);
         } else {
             Theme::Set('latestNews', array(array('title' => __('Latest news not enabled.'), 'description' => '', 'link' => '')));
         }
     } 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');
 }