<?php

class showtime2_utils{
  public function __construct() {} 

    public static function ClearPath($path){
        $patharray = explode('/', $path);
        $newpatharray = array();
        foreach ($patharray as $dir){
                switch ($dir){
                        case '' : break;
                        case '..':
                                array_pop($newpatharray);
                                break;
                        default :
                                $newpatharray[] = $dir;
                }
        }
        return (substr($path,0,1)=='/' ? '/' : '').implode('/', $newpatharray);
    }

    public static function createFile($filename,$content)
    {
      $file = fopen($filename,"w");
      fwrite($file, $content);
      fclose($file);

    }
    
    public static function copyFolder($source, $dest, $recursive = false)
    {
        if (!is_dir($dest)) { 
            mkdir($dest); 
      } 
        $handle = @opendir($source);
        if(!$handle)
            return false;
        while ($file = @readdir ($handle)){
          if (preg_match('/^\.{1,2}$/i', $file)) {continue;}
          if(!$recursive && $source != $source.$file."/")
            {if(is_dir($source.$file)) continue;}
          if(is_dir($source.$file))
            {showtime2_utils::copyFolder($source.$file."/", $dest.$file."/", $recursive);}
          else {
            copy($source.$file, $dest.$file);
          }
        }
        @closedir($handle);
    } 

    public static function removeFolder($dir) {
      // Wenn der Input ein Ordner ist, dann Überprüfung des Inhaltes beginnen
      if (is_dir($dir)) {
      // Ordnerinhalt auflisten und jedes Element nacheinander überprüfen
      $dircontent=scandir($dir);
      foreach ($dircontent as $c) {
        // Wenn es sich um einen Ordner handelt, die Funktion rmr(); aufrufen
        if ($c!='.' and $c!='..' and is_dir($dir.'/'.$c)) {
          showtime2_utils::removeFolder($dir.'/'.$c);
        // Wenn es eine Datei ist, diese löschen
        } else if ($c!='.' and $c!='..') {
          unlink($dir.'/'.$c);
      }
      }
      // Den nun leeren Ordner löschen
      rmdir($dir);
      // Wenn es sich um eine Datei handelt, diese löschen
      } else {
      unlink($dir);
      }
    }

    public static function moveFolder($source,$target, $recursive = false) {
      showtime2_utils::copyFolder($source,$target,$recursive);
      showtime2_utils::removeFolder($source);
    }

  public static function GetNivoCSS($theme,$showid){
        $mod = cms_utils::get_module('Showtime2');
        if ($mod->GetPreference('use_tmp')=='1')
          $prefix = 'tmp';
        else
          $prefix = 'uploads';    
        $nivo_css =  file_get_contents('../'.$prefix.'/_Showtime2/nivothemes/'.$theme.'/'.$theme.'.css');
        $nivo_css = str_replace('url(','url(../nivothemes/'.$theme.'/',$nivo_css);
        $nivo_css = str_replace('.theme-'.$theme,'.theme-'.$theme.$showid,$nivo_css);
        //$nivo_css = str_replace('.nivoSlider','.nivoSlider'.$showid,$nivo_css);
        return $nivo_css;
  }

  public static function CreatePictureLink($picture_url){
        $gCms = cmsms();
        $config = $gCms->GetConfig();
        $rooturl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on')?$config['ssl_url']:$config['root_url'];

        //link to an internal page using Alias depending on your 'url_rewriting', 'page_extension' settings.
        if (FALSE == empty($picture_url)){
                $manager =& $gCms->GetHierarchyManager();
                $node    = $manager->sureGetNodeById($picture_url);
                if(isset($node) && is_object($node)){
                        $content =& $node->GetContent();
                        if(isset($content) && is_object($content) && $content->Type() != 'content2'){
                            $hierarchypath = $content->HierarchyPath();
                            $alias = $content->Alias();
                            if ($config["url_rewriting"] == 'mod_rewrite'){
                                    $link = $rooturl. '/' . $hierarchypath . (isset($config['page_extension'])?$config['page_extension']:'.html');
                            }else{
                                    if (isset($_SERVER['PHP_SELF']) && $config['url_rewriting'] == 'internal'){
                                                    $link = $rooturl. '/index.php/' .$hierarchypath . (isset($config['page_extension'])?$config['page_extension']:'.html');
                                    }else{
                                            $link = $rooturl. '/index.php?' . $config['query_var'] . '=' . $alias;
                                    }
                            }
                        }else{
                            return '';
                        }
                }else{
                        return '';
                }
        }else{
                return '';
        }					
        return $link;
    }

  public static function format_bytes($size) {
        $units = array(' B', ' KB', ' MB', ' GB', ' TB');
        for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
        return round($size, 2).$units[$i];
    }  
    
  public static function is_valid_filename($name) {
    if( $name == '' ) return FALSE;
    if( strpos($name,'/') !== false ) return FALSE;
    if( strpos($name,'\\') !== false ) return FALSE;
    if( strpos($name,'..') !== false ) return FALSE;
    if( $name[0] == '.' || $name[0] == ' ' ) return FALSE;
    if( preg_match('/[\n\r\t\[\]\&\?\<\>\!\@\#\$\%\*\(\)\{\}\|\"\'\:\;\+]/',$name) ){
  return FALSE;
      }
    return TRUE;
  }

  public static function Slash($str,$str2="",$str3="") {
        if ($str=="") return $str2;
        if ($str2=="") return $str;
        if ($str[strlen($str)-1]!="/") {
                if ($str2[0]!="/") {
            return $str."/".$str2;
                } else { 
                    return $str.$str2;
                }
        } else {
            if ($str2[0]!="/") {
            return $str.$str2;
                } else { 
                    return $str.substr($str2,1); //trim away one of the slashes
                }
        }
        //Three strings not supported yet...
        return "Error in Slash-function. Please report";
    }   

  public static function GetShows() {
    $output = array();
    $db = cmsms()->GetDB();
    $query = "SELECT
                show_id, show_name
              FROM
                " . cms_db_prefix() . "module_showtime2_name
              ORDER BY
                show_name ASC";
    $result = $db->Execute($query);
    if ($result && $result->RecordCount() > 0)
    {
      while ($row = $result->FetchRow())
      {
        $output[$row['show_id']] = $row;
      }
    }
    return $output;
  }
}

?>
