<?php
/**
* @version 1.0
* @package JDownloads
* @copyright (C) 2011 www.jdownloads.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*
* Plugin to handle the auto publishing timeframe options.
* 
*/

defined( '_JEXEC' ) or die( 'Restricted access' );
Error_Reporting(E_ERROR);   

jimport('joomla.plugin.plugin'); 
  class plgSystemjdownloads_system_plugin extends JPlugin { 
     
     function plgSystemjdownloads_system_plugin (&$subject, $config) { 
        parent::__construct( $subject, $config ); 
     } 

     function onAfterInitialise() { 
     
         $app = &JFactory::getApplication();
         $database = &JFactory::getDBO();

         // exist the tables?
         $prefix = $database->_table_prefix; 
         $tablelist = $database->getTableList();
         if ( !in_array ( $prefix.'jdownloads_files', $tablelist ) ){
             return;
         }    
         
         // No need in admin
         //if( $app->isAdmin() ) return;

         $j = date('Y');
         $m = date('m');
         $d = date('d');
         $h = date('H');
         $min = date('i');
         $sec = date('s');
         
         $unpublish_time = date('Y-m-d H:i:s',mktime($h,$min,$sec,$m,$d-1,$j));
         $now = date('Y-m-d H:i:s');
         
         // get all published files with use the timeframe options
         $database->setQuery("SELECT file_id from #__jdownloads_files WHERE published = 1 AND use_timeframe = 1 AND publish_to != '0000-00-00 00:00:00' AND publish_to <= '$now'");
         $files = $database->loadResultArray();
         if ($files){
                $fileslist = implode(',', $files);  
                $database->setQuery("UPDATE #__jdownloads_files SET published = '0', use_timeframe = '0' WHERE file_id IN ('$fileslist')"); 
                $database->query(); 
         }
         // get all unpublished files with use the timeframe options
         $database->setQuery("SELECT file_id from #__jdownloads_files WHERE published = 0 AND use_timeframe = 1 AND publish_from != '0000-00-00 00:00:00' AND publish_from <= '$now'");
         $files = $database->loadResultArray();
         if ($files){
                $fileslist = implode(',', $files);  
                $database->setQuery("UPDATE #__jdownloads_files SET published = '1' WHERE file_id IN ('$fileslist')"); 
                $database->query(); 
         }
         return;  
     }
  }  
?>