File: D:/HostingSpaces/PvdBoogaard/indoorski.nl/backup/oude-site/cms/modules/podcast/module.podcast.php
<?php
/**
* This file contains the iwp_module_podcast class
*
* @version $Id$
*
*
* @package IWP_Modules
* @subpackage Podcast_Module
*/
/**
* Podcast Content Class
* This class deals with the Podcast module when in content context.
* It constructs the layout, field arrays and handles the remote requests (such as saving, uploading, etc.).
*
* @package IWP_Modules
* @subpackage Podcast_Module
*/
class iwp_module_podcast extends iwp_module {
/**
* This is the name of the module. It should be the same value as used in the classname, filename and foldername.
*
* @var string
*/
public $moduleName = "podcast";
protected $fileDirectories = array('podcast');
/**
* This static variable holds the current instance of this object being loaded.
* So using the getInstance function anywhere will return the very same instance.
*
* @var object Instance
*/
public static $Instance;
/**
* getInstance
* This is a static function that sets up the class instance and stores it to the static variable. It will then return that instantiation in the future.
*
* @return object Returns the instantiated object
**/
public static function getInstance(){
if(!isset(self::$Instance)){
self::$Instance = new self();
}
return self::$Instance;
}
/**
* __construct
* This runs the parent constructor
*
* @return void
*/
public function __construct(){
parent::__construct();
$this->UploadPath = IWP_FILES_PATH . '/podcast';
$this->UploadDir = IWP_FILES_URI . '/podcast';
}
/**
* Returns a list of database tables for this module.
*
* @param boolean $withoutPrefix A boolean for whether or not to include the prefix for the table.
*
* @return string
*/
public function getTables($withoutPrefix=false) {
$tables = array(
'podcast',
);
if($withoutPrefix) {
return $tables;
}
foreach($tables as $k=>$table ){
$tables[$k] = IWP_MODULE_DB_PREFIX . $table;
}
return $tables;
}
public function GetUploadPath(){
if(!is_dir($this->UploadPath)){
@mkdir($this->UploadPath, 0777);
@chmod($this->UploadPath, 0777);
if(!is_dir($this->UploadPath)){
$this->ErrorMessage('The Podcast folder does not exist and could not be created. Please create and make writable this folder: '. $this->UploadPath);
}
}
return $this->UploadPath;
}
/**
* Deletes all data associated with this module.
* This is used when cleaning out the data during the importer process
*
* @return void
*/
public function TruncateAllData () {
$this->db->Query('TRUNCATE TABLE ' . $this->getTable());
$dirObject = new DirectoryIterator($this->UploadPath);
foreach($dirObject as $fileName=>$objFile){
if($objFile->isFile()){
@unlink($objFile->getPath() . DIRECTORY_SEPARATOR . $objFile->getFilename());
}
}
}
/**
* Checks whether this module is a content module or not. If it is, then it can be displayed as an option when creating a content type.
*
* @return boolean True if it is a content module, false otherwise.
*/
public function IsContentModule () { return true; }
public function HasConfigurationScreen () { return true; }
/**
* AdminGetContentTypeArray
* This function returns the array of options used by this module in the content types page.
*
* @return array The array of options
*/
public function AdminGetContentTypeArray(){
return false;
}
/**
* AdminGetContentArray
* This function returns the array of options used by this module in the create/edit content page when
* a specified content type has the podcast module as a field.
*
* @return array The array of fields
*/
public function AdminGetContentArray($contentId=null){
$arrFields = array(
'uploadpodcast' => array(
'type' => 'module_custom:podcast',
'default' => '',
'value' => '',
),
);
$this->template->Assign('podcastUseNone', $this->output->Checked());
if(is_null($contentId) || $contentId == 0){
return $arrFields;
}
$data = $this->GetContentModuleData($contentId);
if(isset($data['filename'])){
// Check if its an external one or not
if($data['external'] == 0 && file_exists($this->GetUploadPath(). '/'. $data['filename'])){
$this->template->Assign('podcastUseNone', '');
$this->template->Assign('podcastUseCurrent', $this->output->Checked());
$this->template->Assign('CurrentPodcast', $this->output->LinkTag($this->UploadDir .'/'.$data['filename'], $data['filename'], true));
$this->template->Assign('podcastId', $data['id']);
}elseif ($data['external'] == 1){
$this->template->Assign('podcastUseNone', '');
$this->template->Assign('podcastUseCurrent', $this->output->Checked());
$this->template->Assign('CurrentPodcast', $this->output->LinkTag($data['filename'], $data['filename'], true));
$this->template->Assign('podcastId', $data['id']);
}
}
return $arrFields;
}
/**
* @see iwp_module::AdminGetVariablesArray
*/
public function AdminGetVariablesArray () {
return array(
'explicit',
'iTunesAuthor',
'iTunesCategories1',
'iTunesCategories2',
'iTunesCategories3',
'iTunesKeywords',
'iTunesSummary'
);
}
/**
* This is used to save the podcast. It checks to see if its a URL or if none is selected.
* If the option is set to current, it doesn't do anything.
*
* @param array $Post The post data sent to the page
* @param integer $ContentId The content ID number of the content item being saved
*/
public function SaveField($Post, $ContentId){
if(!isset($Post['podcast_select'])){
$this->DeletePodcast($ContentId);
return;
}
if($Post['podcast_select'] == 'none'){
$this->DeletePodcast($ContentId);
return;
}elseif ($Post['podcast_select'] == 'url' && !$this->valid->IsBlank($Post['podcast_url']) && $Post['podcast_url'] != 'http://'){
$this->DeletePodcast($ContentId);
$Insert = array();
$Insert['external'] = 1;
$Insert['contentid'] = $ContentId;
$Insert['filename'] = $Post['podcast_url'];
$Insert['title'] = $Post['podcast_url'];
$this->db->InsertQuery($this->getTable(), $Insert);
}
if ((int)$Post['podcastId'] > 0) {
$this->db->UpdateQuery($this->getTable(), array('contentid'=>$ContentId), 'id='.(int)$Post['podcastId']);
}
return;
}
/**
* Removes the database record and podcast file based on a content ID number
*
* @param integer $ContentID
*/
public function DeletePodcast($ContentID){
$CountQuery = $this->db->Query('select * from '. $this->getTable() . ' where contentid='.$ContentID);
if($this->db->CountResult($CountQuery) > 0){
$OldPodcast = $this->db->Fetch($CountQuery);
// remove the old file
if(file_exists($this->GetUploadPath(). '/' . $OldPodcast['filename'])){
unlink($this->GetUploadPath(). '/' . $OldPodcast['filename']);
}
$this->db->Query('delete from ' . $this->getTable() . ' where contentid='.$ContentID);
}
}
/**
* RemoteUploadPodcast
* Takes a podcast upload, replaces the old one if it exists and returns an XML response
*
* @return void
*/
public function RemoteUploadPodcast(){
// we need to make sure the page isn't ever cached
header("Expires: Mon, 23 Jul 1993 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: post-check=0, pre-check=0, max-age=0", false);
// make sure there are files to deal with
if(empty($_FILES) || !isset($_FILES["podcast_file"]) || empty($_FILES["podcast_file"]['tmp_name'])){
$this->xml->writeElement('status', 'error');
$this->xml->writeElement('type', 'nofiles');
$this->xml->writeElement('message', 'No file was uploaded. Please select a file from your computer to upload.');
$this->xml->outputXML();
die();
}
// lets make sure its one of our allowed podcast files
if(!$this->valid->IsNotBadFileExtension($_FILES["podcast_file"]["name"])){
$this->xml->writeElement('status', 'error');
$this->xml->writeElement('type', 'bad_filename');
$this->xml->writeElement('message', 'The file that was uploaded was not valid.');
$this->xml->outputXML();
die();
}
// check for an existing podcast and delete it if it exists
$this->DeletePodcast((int)$_GET['contentid']);
if(!move_uploaded_file($_FILES["podcast_file"]["tmp_name"], $this->GetUploadPath(). '/'. $_FILES["podcast_file"]["name"])){
$this->xml->writeElement('status', 'error');
$this->xml->writeElement('type', 'move_file_fail');
$this->xml->writeElement('message', 'The uploaded file could not be moved to the podcast directory. Make sure it is writable and try again.');
$this->xml->outputXML();
die();
}
// Lets use the posted file data
$ContentID = max(0, (int)$_GET['contentid']);
$InsertData = array();
$InsertData['filename'] = $_FILES["podcast_file"]["name"];
$InsertData['title'] = $_FILES["podcast_file"]["name"];
$InsertData['external'] = 0;
$InsertData['contentid'] = $ContentID;
$PodcastID = $this->db->InsertQuery($this->getTable(), $InsertData);
$PodcastID = (int)$PodcastID;
if($PodcastID > 0){
// if we got here, its in the database
$this->xml->writeElement('status', 'success');
$this->xml->writeCDataElement('file', $_FILES['podcast_file']['name']);
$this->xml->writeElement('podcastid', $PodcastID);
$this->xml->outputXML();
}else{
// if we're here, something went wrong with the db insertion
// roll back the upload
if(file_exists($this->GetUploadPath(). '/'. $_FILES["podcast_file"]["name"])){
unlink($this->GetUploadPath(). '/'. $_FILES["podcast_file"]["name"]);
}
$this->xml->writeElement('status', 'error');
$this->xml->writeElement('type', 'dberror');
$this->xml->writeCDataElement('file', $_FILES['podcast_file']['name']);
$this->xml->writeElement('unique', (int)$_GET['unique']);
$this->xml->writeElement('message', "Couldn't insert into DB: " . $this->db->GetErrorMsg());
$this->xml->outputXML();
}
die();
}
public function AdminConfigure ()
{
$groupName = $this->lang->Get('DefaultPodcastItunesSettings');
$this->form->AddGroup($groupName);
$this->form->AddField('textbox', 'iTunesAuthor', $groupName, $this->lang);
$categoryFields = array();
$field = $categoryFields[] = $this->form->AddField('select', 'iTunesCategories1', $groupName, $this->lang)->SetAttribute('class', 'Field350');
$field->AddFieldOption('None', sprintf('%s / %s', $this->lang->Get('PrimaryCategory'), $this->lang->Get('NoCategory')));
$field = $categoryFields[] = $this->form->AddField('select', 'iTunesCategories2', $groupName, $this->lang)->SetAttribute('class', 'Field350')->DisableName();
$field->AddFieldOption('None', sprintf('%s / %s', $this->lang->Get('SecondaryCategory'), $this->lang->Get('NoCategory')));
$field = $categoryFields[] = $this->form->AddField('select', 'iTunesCategories3', $groupName, $this->lang)->SetAttribute('class', 'Field350')->DisableName();
$field->AddFieldOption('None', sprintf('%s / %s', $this->lang->Get('TertiaryCategory'), $this->lang->Get('NoCategory')));
$categoryOptions = $this->iTunesCategoryList();
foreach ($categoryFields as &$field) {
foreach ($categoryOptions as $optionValue => $optionText) {
$field->AddFieldOption($optionValue, $optionText);
}
}
$this->form->AddField('textbox', 'iTunesKeywords', $groupName, $this->lang)->Append('<div style="margin:0;" class="aside">'. $this->lang->Get('field_iTunesKeywords_Aside') .'</span>');
$this->form->AddField('textarea', 'iTunesSummary', $groupName, $this->lang)->SetAttribute('class', 'Field350')->Append('<div style="margin:0;" class="aside">'. $this->lang->Get('field_iTunesSummary_Aside') .'</span>');
$this->form->AddField('checkbox', 'explicit', $groupName, $this->lang);
$this->form->JsOnLoad[] = "$('#PodcastFeedContainer').text(". iwp_FilterJavascriptString($this->GetUri('PodcastFeed')) .")";
}
/**
* iTunesCategoryList
*
* @return array An array of key/value pairs that can be pushed through AddFieldOption
*/
public function iTunesCategoryList () {
// lets build the array!
$iTunesCats['Arts']['name'] = 'Arts';
$iTunesCats['Arts'][] = 'Design';
$iTunesCats['Arts'][] = 'Fashion & Beauty';
$iTunesCats['Arts'][] = 'Food';
$iTunesCats['Arts'][] = 'Literature';
$iTunesCats['Arts'][] = 'Performing Arts';
$iTunesCats['Arts'][] = 'Visual Arts';
$iTunesCats['Business']['name'] = 'Business';
$iTunesCats['Business'][] = 'Business News';
$iTunesCats['Business'][] = 'Careers';
$iTunesCats['Business'][] = 'Investing';
$iTunesCats['Business'][] = 'Management & Marketing';
$iTunesCats['Business'][] = 'Shopping';
$iTunesCats['Comedy']['name'] = 'Comedy';
$iTunesCats['Education']['name'] = 'Education';
$iTunesCats['Education'][] = 'Education Technology';
$iTunesCats['Education'][] = 'Higher Education';
$iTunesCats['Education'][] = 'K-12';
$iTunesCats['Education'][] = 'Language Courses';
$iTunesCats['Education'][] = 'Training';
$iTunesCats['Games_Hobbies']['name'] = 'Games & Hobbies';
$iTunesCats['Games_Hobbies'][] = 'Automotive';
$iTunesCats['Games_Hobbies'][] = 'Aviation';
$iTunesCats['Games_Hobbies'][] = 'Hobbies';
$iTunesCats['Games_Hobbies'][] = 'Other Games';
$iTunesCats['Games_Hobbies'][] = 'Video Games';
$iTunesCats['Government_Organizations']['name'] =
'Government & Organizations';
$iTunesCats['Government_Organizations'][] = 'Local';
$iTunesCats['Government_Organizations'][] = 'National';
$iTunesCats['Government_Organizations'][] = 'Non-Profit';
$iTunesCats['Government_Organizations'][] = 'Regional';
$iTunesCats['Health']['name'] = 'Health';
$iTunesCats['Health'][] = 'Alternative Health';
$iTunesCats['Health'][] = 'Fitness & Nutrition';
$iTunesCats['Health'][] = 'Self-Help';
$iTunesCats['Health'][] = 'Sexuality';
$iTunesCats['Kids_Family']['name'] = 'Kids & Family';
$iTunesCats['Music']['name'] = 'Music';
$iTunesCats['News_Politics']['name'] = 'News & Politics';
$iTunesCats['Religion_Spirituality']['name'] = 'Religion & Spirituality';
$iTunesCats['Religion_Spirituality'][] = 'Buddhism';
$iTunesCats['Religion_Spirituality'][] = 'Christianity';
$iTunesCats['Religion_Spirituality'][] = 'Hinduism';
$iTunesCats['Religion_Spirituality'][] = 'Islam';
$iTunesCats['Religion_Spirituality'][] = 'Judaism';
$iTunesCats['Religion_Spirituality'][] = 'Other';
$iTunesCats['Religion_Spirituality'][] = 'Spirituality';
$iTunesCats['Science_Medicine']['name'] = 'Science & Medicine';
$iTunesCats['Science_Medicine'][] = 'Medicine';
$iTunesCats['Science_Medicine'][] = 'Natural Sciences';
$iTunesCats['Science_Medicine'][] = 'Social Sciences';
$iTunesCats['Society_Culture']['name'] = 'Society & Culture';
$iTunesCats['Society_Culture'][] = 'History';
$iTunesCats['Society_Culture'][] = 'Personal Journals';
$iTunesCats['Society_Culture'][] = 'Philosophy';
$iTunesCats['Society_Culture'][] = 'Places & Travel';
$iTunesCats['Sports_Recreation']['name'] = 'Sports & Recreation';
$iTunesCats['Sports_Recreation'][] = 'Amateur';
$iTunesCats['Sports_Recreation'][] = 'College & High School';
$iTunesCats['Sports_Recreation'][] = 'Outdoor';
$iTunesCats['Sports_Recreation'][] = 'Professional';
$iTunesCats['Technology']['name'] = 'Technology';
$iTunesCats['Technology'][] = 'Gadgets';
$iTunesCats['Technology'][] = 'Tech News';
$iTunesCats['Technology'][] = 'Podcasting';
$iTunesCats['Technology'][] = 'Software How-To';
$iTunesCats['TV_Film']['name'] = 'TV & Film';
$options = array();
foreach ($iTunesCats as $key => $value) {
$optionValue = $value['name'];
$optionText = $value['name'];
$options[$optionValue] = $optionText;
foreach ($value as $sub_key => $sub_value) {
if ($sub_key == "name")
continue;
$thisvalue = $value['name'] . "|" . $sub_value;
$optionValue = $value['name'] . '|' . $sub_value;
$optionText = ' -- ' . $sub_value;
$options[$optionValue] = $optionText;
}
}
return $options;
}
public function LoadFrontEndData($id){
$returnArray = array();
$returnArray['hasPodcast'] = false;
if(!iwp_IsId($id)){
return $returnArray;
}
$q = $this->db->query('select * from '. $this->getTable(). ' where contentid='. $id);
$data = $this->db->fetch($q);
// checking if there is at least one podcast
if(!is_array($data) || sizeof($data) < 1){
return $returnArray;
}
$returnArray['hasPodcast'] = true;
$returnArray['PodcastFileLink'] = $this->UploadDir .'/'.$data['filename'];
$returnArray['PodcastFeedLink'] = $this->GetUri('PodcastFeed');
$returnArray['iTunesLink'] = str_replace('http', 'itpc', $returnArray['PodcastFeedLink']);
return $returnArray;
}
public function GetUri($which, $name=null, $id=null) {
$this->LoadUris();
$uri = $this->UriList[$which];
if(!is_null($name)){
$uri = str_replace('{name}', $name, $uri);
}
if(!is_null($id)){
$uri = str_replace('{idnumber}', $id, $uri);
}
$uri = $this->urls->ForceSlash($uri);
return $this->urls->ForceSlash(iwp_config::Get('siteURL'), false, true) . $uri;
}
public function ShowPageByIniUri($url) {
$uriList = $this->urls->GetModuleUrls($this->moduleName);
$matchedUri = $this->urls->GetCurrentModulePage();
$this->LoadUris();
if($matchedUri == 'PodcastFeed'){
$this->ShowFeedPage();
}
}
public function ShowFeedPage() {
$this->cache->SetDir('rss_out');
$cacheId = 'podcast.viewfeed';
if(!$this->cache->HasExpired($cacheId)){
header('Content-Type: text/xml; charset=utf-8');
echo $this->cache->ReadCache($cacheId);
die();
}
$this->vars->Load($this->moduleName);
$rss = new iwp_rsscreator(true); // true = podcast
$rss->SetPodcastVar('author', $this->GetVar('iTunesAuthor'));
$rss->SetPodcastVar('summary', $this->GetVar('iTunesSummary'));
$rss->SetPodcastVar('keywords', $this->GetVar('iTunesKeywords'));
if($this->GetVar('explicit') == 'checked') {
$rss->SetPodcastVar('explicit', 'yes');
} else {
$rss->SetPodcastVar('explicit', 'no');
}
$rss->StartRSS(iwp_config::Get('siteName'), iwp_config::Get('siteURL'));
$query = $this->db->Query("select * from ".$this->getTable() ." as m
inner join ". IWP_TABLE_CONTENT ." as c on m.contentid = c.contentid
inner join ".IWP_TABLE_URLS." as ur on ur.associd= c.contentid
left join ".IWP_TABLE_USERS." as us on find_in_set(us.userid, c.author)
where ur.assoctype='content'
order by c.startdate desc");
while($row = $this->db->Fetch($query)) {
if(!is_file($this->GetUploadPath().'/'. $row['filename'])){
continue;
}
$item = array();
$item['title'] = $row['title'];
$item['link'] = iwp_config::Get('siteURL') . $row['urlpath'];
$item['description'] = $row['summary'];
$item['author'] = trim($row['firstname'] .' '.$row['lastname']);
$item['lastBuildDate'] = date("D, d M Y H:i:s T", strtotime($row['startdate']));
$item['itunes_summary'] = $row['summary'];
$item['itunes_author'] = trim($row['firstname'] .' '.$row['lastname']);
$item['enclosure'] = true;
$item['enclosure_url'] = $this->UploadDir .'/'. $row['filename'];
$item['enclosure_path'] = $this->GetUploadPath().'/'. $row['filename'];
$rss->AddItem($item);
}
$rssContent = $rss->EndRSS(false);
$this->cache->WriteCache($cacheId, $rssContent);
die($rssContent);
}
/**
* This function is called by the module framework when the user requests this module be activated.
*
* @return Boolean Returns true on success, otherwise false.
*/
public function ActivateModule ()
{
$success = false;
if (parent::ActivateModule()) {
$tableName = $this->getTable();
if ($this->db->TableExists($tableName)) {
if ($this->db->ColumnExists($tableName, array('filename', 'external', 'contentid', 'title'))) {
// table and columns exists
$success = true;
} else if (iwp_session::Exists('module_podcast_removetable')) {
// table exists and this is the second time they have clicked, drop the table and re-create it
if ($this->RunModuleTableQuery()) {
$success = true;
}
} else {
// table exists but columns do not match
iwp_session::Set('module_podcast_removetable', 1);
$this->messages[] = sprintf($this->lang->Get('ModuleTableExistsButDifferent'), $tableName);
}
} else {
// table does not exist at all
if ($this->RunModuleTableQuery()) {
$success = true;
}
}
if ($success) {
iwp_session::Kill('module_podcast_removetable');
} else {
parent::DeactivateModule();
}
}
return $success;
}
/**
* Creates the database table for this module, dropping any table that gets in its way.
*
* @return Boolean Returns true on success, otherwise false.
*/
public function CreateModuleTable ()
{
$this->table->AddField('id')->SetAsPrimaryKey();
$this->table->AddField('contentid')->SetAsInt();
$this->table->AddField('external')->SetAsTinyInt();
$this->table->AddField('title')->SetAsVarChar();
$this->table->AddField('filename')->SetAsVarChar();
$this->tableSchema = $this->table->GetCreateTable();
}
}