public function viewAction() { $id = (int) $this->getParam('id'); $record = Artist::find($id); if (!$record instanceof Artist) { throw new \DF\Exception\DisplayOnly('Artist Not Found'); } $this->view->artist = $record; // Generate statistics. $cache_key = 'artist_' . $record->id . '_stats'; $stats = \DF\Cache::get($cache_key); if (empty($stats)) { $stats = array('plays_per_day' => array(), 'song_lists' => array('most_played' => array('label' => 'Most Played Songs', 'songs' => array()), 'most_liked' => array('label' => 'Most Liked Songs', 'songs' => array()), 'most_recent' => array('label' => 'Most Recently Played', 'songs' => array()))); $active_streams = \Entity\StationStream::getMainRadioStreams(); $songs = $this->em->createQuery('SELECT s, sh FROM Entity\\Song s LEFT JOIN s.history sh WHERE s.artist LIKE :artist_q AND sh.stream_id IN (:streams) ORDER BY s.title, sh.timestamp DESC')->setParameter('artist_q', '%' . $record->name . '%')->setParameter('streams', $active_streams)->getArrayResult(); $plays_per_day = array(); foreach ($songs as &$song) { foreach ((array) $song['history'] as $i => $history) { // Get day of song play, incremenet counter. $day = strtotime(date('Y-m-d', $history['timestamp']) . ' 00:00:00') * 1000; $plays_per_day[$day] += 1; // Increment votes. $song['score_likes'] += $history['score_likes']; $song['score_dislikes'] += $history['score_dislikes']; } unset($song['history']); // Increment vote totals. $song['score_total'] = $song['score_likes'] - $song['score_dislikes']; $song['votes'] = $song['score_likes'] + $song['score_dislikes']; } // Remove current day, as it will always be lower. $current_day = strtotime(date('Y-m-d') . ' 00:00:00') * 1000; unset($plays_per_day[$current_day]); ksort($plays_per_day); foreach ($plays_per_day as $plays_day => $plays_total) { $stats['plays_per_day'][] = array($plays_day, $plays_total); } $stats['song_lists']['most_played']['songs'] = array_slice(Utilities::irsort($songs, 'play_count'), 0, 10); $stats['song_lists']['most_liked']['songs'] = array_slice(Utilities::irsort($songs, 'score_total'), 0, 10); $stats['song_lists']['most_recent']['songs'] = array_slice(Utilities::irsort($songs, 'last_played'), 0, 10); \DF\Cache::save($stats, $cache_key, array(), 300); } $this->view->stats = $stats; }
public function viewAction() { $id = (int) $this->getParam('id'); $podcast = Podcast::find($id); if (!$podcast instanceof Podcast) { throw new \DF\Exception\DisplayOnly('Podcast not found!'); } $this->view->podcast = $podcast; $this->view->social_types = Podcast::getSocialTypes(); // Stringify list of stations that play this podcast. $airs_on = ''; if (count($podcast->stations) > 0) { $airs_on_array = array(); foreach ($podcast->stations as $station) { $airs_on_array[] = '<a href="' . $station->web_url . '" target="_blank">' . $station->name . '</a>'; } $airs_on = 'Airs on ' . \DF\Utilities::joinCompound($airs_on_array); } $this->view->podcast_airs_on = $airs_on; // Paginate episodes. $query = $this->em->createQuery('SELECT pe FROM Entity\\PodcastEpisode pe WHERE pe.podcast_id = :podcast AND pe.is_active = 1 ORDER BY pe.timestamp DESC')->setParameter('podcast', $id); $this->view->pager = new \DF\Paginator\Doctrine($query, $this->getParam('page', 1), 25); }
public function truncate($text, $length = 80) { return \DF\Utilities::truncateText($text, $length); }
public static function getSyncTimes() { Settings::clearCache(); $syncs = array('nowplaying' => array('name' => 'Now Playing Data', 'latest' => Settings::getSetting('nowplaying_last_run', 0), 'contents' => array('Now Playing Data')), 'short' => array('name' => '1-Minute Sync', 'latest' => Settings::getSetting('sync_fast_last_run', 0), 'contents' => array('Schedule Notifications')), 'medium' => array('name' => '5-Minute Sync', 'latest' => Settings::getSetting('sync_last_run', 0), 'contents' => array('Homepage Tumblr Rotator', 'Station Schedules', 'Podcast Episodes', 'CentovaCast Metadata', 'Slim Player Cache')), 'long' => array('name' => '1-Hour Sync', 'latest' => Settings::getSetting('sync_slow_last_run', 0), 'contents' => array('Analytics and Statistics', 'Convention Archives', 'API Call Cleanup', 'Song History Cleanup', 'BronyTunes Sync', 'Pony.fm Sync', 'EqBeats Sync'))); foreach ($syncs as $sync_key => $sync_info) { $sync_latest = $sync_info['latest']; $syncs[$sync_key]['diff'] = time() - $sync_latest; $syncs[$sync_key]['diff_text'] = \DF\Utilities::timeDifferenceText($sync_latest, time()); } return $syncs; }
public function contactAction() { $all_categories = Station::getStationsInCategories(); $audio_stations = \DF\Utilities::columns($all_categories['audio']['stations'], 2); $video_stations = $all_categories['video']['stations']; $this->view->station_columns = array(array('<i class="icon ' . $all_categories['audio']['icon'] . '"></i> ' . $all_categories['audio']['name'], $audio_stations[0]), array(' ', $audio_stations[1]), array('<i class="icon ' . $all_categories['video']['icon'] . '"></i> ' . $all_categories['video']['name'], $video_stations)); $active_podcasts = array_filter(Podcast::fetchArray('name'), function ($row) { return $row['is_approved']; }); $this->view->podcasts = \DF\Utilities::columns($active_podcasts, 3); $this->view->podcast_social_types = Podcast::getSocialTypes(); }
public function processValue($post_value) { return \DF\Utilities::gstrtotime($post_value . ' 00:00:00'); }
/** * Send an individual notification. * * @param string $message The main message body of the tweet. * @param null $url URL to reference as a link in the tweet. * @param null $image URL or filesystem path of an image to reference. * @param bool $force Trigger a notification even in development mode. * @return bool */ public static function notify($message, $url = null, $image = null, $force = false) { static $twitter; \PVL\Debug::print_r(func_get_args()); // Suppress notifications for non-production applications. if (DF_APPLICATION_ENV != "production" && !$force) { return false; } // Send through Notifico hook. $payload = $message . ' - ' . $url; \PVL\Service\Notifico::post($payload); // Send through Twitter. if (!$twitter) { $di = \Phalcon\Di::getDefault(); $config = $di->get('config'); $twitter_config = $config->apis->twitter->toArray(); $twitter = new \tmhOAuth($twitter_config); } $message_length = 140; if ($url) { $message_length -= 23; } if ($image) { $message_length -= 23; } // Post t.co URLs directly instead of pulling down data. if (stristr($image, 't.co') !== FALSE) { $url .= ' ' . $image; $image = NULL; } // Cut off the URL $tweet = \DF\Utilities::truncateText($message, $message_length); if ($url) { $tweet .= ' ' . $url; } if ($image) { $image_data = base64_encode(@file_get_contents($image)); if (!empty($image_data)) { $twitter->request('POST', 'https://upload.twitter.com/1.1/media/upload.json', array('media' => $image_data)); \PVL\Debug::print_r($twitter->response['response']); $image_response = @json_decode($twitter->response['response'], true); if (isset($image_response['media_id_string'])) { $media_id = $image_response['media_id_string']; $twitter->request('POST', 'https://api.twitter.com/1.1/statuses/update.json', array('status' => $tweet, 'media_ids' => array($media_id))); \PVL\Debug::print_r($twitter->response['response']); } return true; } } $twitter->request('POST', 'https://api.twitter.com/1.1/statuses/update.json', array('status' => $tweet)); \PVL\Debug::print_r($twitter->response['response']); return true; }
/** * Generate a truncated summary of the podcast description. * * @param $text * @return mixed|string */ public static function getSummary($text) { $text = self::cleanUpText($text); // Strip all but the first line. $text = strtok($text, "\n"); // Remove URLs. $text = preg_replace('@(https?://([-\\w\\.]+[-\\w])+(:\\d+)?(/([\\w/_\\.#-]*(\\?\\S+)?[^\\.\\s])?).*$)@ui', ' ', $text); // Truncate to 300 characters. $text = \DF\Utilities::truncateText($text, 300); return $text; }
public function money($amount) { return \DF\Utilities::money_format($amount); }
public static function getHashes() { $em = self::getEntityManager(); $ids_raw = $em->createQuery('SELECT sebt.id, sebt.hash FROM ' . __CLASS__ . ' sebt')->getArrayResult(); return \DF\Utilities::ipull($ids_raw, 'id', 'hash'); }
public static function run($force_run = false) { $di = \Phalcon\Di::getDefault(); $em = $di->get('em'); $config = $di->get('config'); // Set up Google Client. $gclient_api_key = $config->apis->google_apis_key; $gclient_app_name = $config->application->name; if (empty($gclient_api_key)) { return null; } $gclient = new \Google_Client(); $gclient->setApplicationName($gclient_app_name); $gclient->setDeveloperKey($gclient_api_key); $gcal = new \Google_Service_Calendar($gclient); // Prevent running repeatedly in too short of a time (avoid API limits). $last_run = Settings::getSetting('schedule_manager_last_run', 0); if ($last_run > time() - 60 && !$force_run) { return null; } $schedule_items = array(); $schedule_records = array(); $stations = $em->createQuery('SELECT s FROM Entity\\Station s WHERE (s.gcal_url IS NOT NULL AND s.gcal_url != \'\') AND s.is_active = 1')->getArrayResult(); $active_stations = Utilities::ipull($stations, 'id'); // Clear all invalid station records. $em->createQuery('DELETE FROM Entity\\Schedule s WHERE (s.station_id IS NOT NULL) AND (s.station_id NOT IN (:station_ids))')->setParameter('station_ids', $active_stations)->execute(); foreach ($stations as $station) { if ($station['gcal_url']) { $schedule_items[] = array('name' => $station['name'], 'url' => $station['gcal_url'], 'type' => 'station', 'station_id' => $station['id'], 'image_url' => \DF\Url::content($station['image_url'])); } } Debug::startTimer('Get Calendar Records'); // Time boundaries for calendar entries. $threshold_start = date(\DateTime::RFC3339, strtotime('-1 week')); $threshold_end = date(\DateTime::RFC3339, strtotime('+1 year')); foreach ($schedule_items as $item) { // Get the "calendar_id" from the URL provided by the user. $orig_url_parts = parse_url($item['url']); $url_path_parts = explode('/', $orig_url_parts['path']); $calendar_id = urldecode($url_path_parts[3]); if (empty($calendar_id)) { continue; } // Call the external Google Calendar client. try { $all_events = $gcal->events->listEvents($calendar_id, array('timeMin' => $threshold_start, 'timeMax' => $threshold_end, 'singleEvents' => 'true', 'orderBy' => 'startTime', 'maxResults' => '300')); } catch (\Exception $e) { continue; } // Process each individual event. foreach ($all_events as $event_orig) { $title = $event_orig->summary; $body = $event_orig->description; $location = $event_orig->location; $web_url = $event_orig->htmlLink; $banner_url = null; $is_all_day = false; $start_time_obj = $event_orig->start; if ($start_time_obj->date) { $is_all_day = true; $start_time = strtotime($start_time_obj->date . ' 00:00:00'); } else { $start_time = strtotime($start_time_obj->dateTime); } $end_time_obj = $event_orig->end; if ($end_time_obj->date) { $is_all_day = true; $end_time = strtotime($end_time_obj->date . ' 00:00:00'); } elseif ($end_time_obj) { $end_time = strtotime($end_time_obj->dateTime); } else { $end_time = $start_time; } // Detect URLs for link. if ($body && !$web_url) { preg_match('@((https?://)?([-\\w]+\\.[-\\w\\.]+)+\\w(:\\d+)?(/([-\\w/_\\.]*(\\?\\S+)?)?)*)@', $body, $urls); if (count($urls) > 0) { $web_url = $urls[0]; } } // Detect URLs for photo. if ($location) { preg_match('@((https?://)?([-\\w]+\\.[-\\w\\.]+)+\\w(:\\d+)?(/([-\\w/_\\.]*(\\?\\S+)?)?)*)@', $location, $urls); if (count($urls) > 0) { $banner_url = $urls[0]; } } $guid = md5(implode('|', array($event_orig->id, $start_time, $end_time, $title, $location))); $schedule_record = array('guid' => $guid, 'type' => $item['type'], 'start_time' => $start_time, 'end_time' => $end_time, 'is_all_day' => $is_all_day, 'title' => $title, 'location' => $location, 'body' => \DF\Utilities::truncateText(strip_tags($body), 300), 'banner_url' => $banner_url, 'web_url' => $web_url); \PVL\Debug::print_r($schedule_record); $schedule_records[$item['station_id']][$guid] = $schedule_record; } } Debug::endTimer('Get Calendar Records'); if (count($schedule_records) == 0) { Debug::log('Error: No calendar records loaded'); return; } // Add/Remove all differential records. Debug::startTimer('Sync DB Records'); foreach ($schedule_records as $station_id => $station_records) { $station = Station::find($station_id); if ($station_id == 0) { $existing_guids_raw = $em->createQuery('SELECT s.guid FROM Entity\\Schedule s WHERE s.station_id IS NULL')->getArrayResult(); } else { $existing_guids_raw = $em->createQuery('SELECT s.guid FROM Entity\\Schedule s WHERE s.station_id = :sid')->setParameter('sid', $station_id)->getArrayResult(); } $existing_guids = array(); foreach ($existing_guids_raw as $i) { $existing_guids[] = $i['guid']; } $new_guids = array_keys($station_records); $guids_to_delete = array_diff($existing_guids, $new_guids); if ($guids_to_delete) { $em->createQuery('DELETE FROM Entity\\Schedule s WHERE s.guid IN (:guids)')->setParameter('guids', $guids_to_delete)->execute(); } $guids_to_add = array_diff($new_guids, $existing_guids); if ($guids_to_add) { foreach ($guids_to_add as $guid) { $schedule_record = $station_records[$guid]; $record = new Schedule(); $record->station = $station; $record->fromArray($schedule_record); $em->persist($record); } } $em->flush(); $em->clear(); } Debug::endTimer('Sync DB Records'); Settings::setSetting('schedule_manager_last_run', time()); }