<?php
include_once($_SESSION['binn_cms_lib_path']."/binnElements.inc.php");
include_once($_SESSION['binn_cms_lib_path']."/binnMail.inc.php");
include_once($_SESSION['binn_cms_lib_path']."/binnDownloadString.inc.php");

@set_time_limit(0);

function fUpdate_Send_Mail()
{
     $type = 'text/html';

     $from = $_POST['mail'];
     $message =  stripslashes($_POST['message']);
     
     $subject = PL_UPDATE_ARISEN_ERROR_3;

     $mailer = new binnMail($subject, '', $from, $_SESSION['binn_cms_email']);
     $mailer->type = 'text/html';

     $mailer->to = $from;
     $mailer->body = $message;

    if($mailer->send())
    {
        echo "<b style='color: #009900;'>".PL_UPDATE_SET_EMAIL_OK."</b>";
    }
    else 
    {
        echo "<b style='color: red;'>".PL_UPDATE_SET_EMAIL_ERROR."</b>";
    }
    
    fUpdate();
}

function fUpdate_Rollback()
{
    /*
  $GLOBALS['CP_LIST']="<br><b>".PL_UPDATE_INSTALLATION_RECOIL."</b> ".$_GET['version']." <b>".PL_UPDATE_OT."</b> ".$_GET['date'].":<br><br>";
  echo "<br><b>".PL_UPDATE_INSTALLATION_RECOIL."</b> ".$_GET['version']." <b>".PL_UPDATE_OT."</b> ".$_GET['date'].":<br><br>";
  fUpdate_Check($_SESSION['binn_basedir']."/cms/tmp/backup/".$_GET['bu_uid']."/", $_SESSION['binn_basedir']);
  
  if(@!array_key_exists("closed",$GLOBALS["file_not_access"]))
  {
      fUpdate_Copy($_SESSION['binn_basedir']."/cms/tmp/backup/".$_GET['bu_uid']."/", $_SESSION['binn_basedir']); 
      sql_query("DELETE FROM binn_update WHERE bu_version='{$_GET['version']}'");
      echo "<br><b style='color: #009900;'>".PL_UPDATE_UPDATING_RECOIL."</b><hr>";
  }
  else 
  {
      $varning = PL_UPDATE_ARISEN_ERROR."<br>";
      
      foreach ($GLOBALS["file_not_access"]["closed"] as $key => $value)
      {
          $varning .= "<font style='color: red;'>$value</font><br>";
      }
      echo $_SESSION['varning'] = $varning;
      echo "<br><b style='color:red;'>".PL_UPDATE_SET_EMAIL."</b><form action='/cms/kernel/content.php?event=pl_set_mail' method='POST'><input type='text' name='mail' value='".$_SESSION['binn_cms_email']."'>&nbsp;&nbsp;<input type='submit' value='".PL_UPDATE_SET_EMAIL_BUTTON."'></form>";
  }
  
  if(file_exists($_SESSION['binn_basedir']."/cms/tmp/backup/".$_GET['bu_uid']."/return_exec.php"))
  {
      include($_SESSION['binn_basedir']."/cms/tmp/backup/".$_GET['bu_uid']."/return_exec.php");
  }
  
  if(file_exists($_SESSION['binn_basedir']."/cms/tmp/backup/".$_GET['bu_uid']."/return_dump.sql"))
  {
    $list = @file($_SESSION['binn_basedir']."/cms/tmp/backup/".$_GET['bu_uid']."/return_dump.sql");

    $c = count($list);

    $q = "";
    $db_num = 0;
    $db = array();
    for ($m=0; $m<$c; $m++)
    {
      $str = $list[$m];

      if (($str[0] != "#") && ($str!="\r\n") && (strlen($str)>2))
      {

        if ((substr($str, 0, 6)=="INSERT") || (substr($str, 0, 5)=="ALTER"))
        $insert[] = substr($str, 0, strlen($str)-2);
        else
        {
          if (substr($str, 0, 6)=="CREATE")
          {
            $trig = 1;
            $db[$db_num] = substr($str, 0, strlen($str)-2);
          }
          else
          {
            $db[$db_num] .= substr($str, 0, strlen($str)-2);
            if (substr($str, 0, 6)==") TYPE")
            $db_num++;
          }
        }
      }
    }

    $num = count($db);
    $num2= count($insert);

    $error=0;

      for ($i=0; $i<$num; $i++) 
      {
        $res = sql_query($db[$i]);

        if (!$res) $error=1;
      }

      for ($i=0; $i<$num2; $i++)
      {
        $res = sql_query($insert[$i]);

      }
  }

  fUpdate();
  */
}

function fUpdate_Get_Dir($conn_id, $local_dir, $server_dir, $mode)
{
    $local_dir = str_replace('//', '/', $local_dir);
    
    if(!@file_exists($local_dir))
    {
        if(!@mkdir($local_dir, octdec($_SESSION['binn_file_rights'])))
        { 
            _showStaticWarning(PL_UPDATE_NO_MKDIR);
            return false;
        }
    }

    $ls_dir = @ftp_rawlist($conn_id, $server_dir);
    if (trim($ls_dir[0]) == '')
        return false;

    @chdir($local_dir);
    for($i = 0; $i < sizeof($ls_dir); $i++)
    {
        $curr_f_name = substr($ls_dir[$i], 55);

        $file_dl = true;
        $dir_dl = true;
        
        if(substr($ls_dir[$i], 0, 1) == 'd')
        {
            $dir_dl = fUpdate_Get_Dir($conn_id, $local_dir.'/'.$curr_f_name, $server_dir.'/'.$curr_f_name, $mode);
        }
        else
        {
            $file_dl = @ftp_get($conn_id, $local_dir.'/'.$curr_f_name, $server_dir.'/'.$curr_f_name, $mode);
        }

        if(!$file_dl && !$dir_dl)  return false;
    }

    return true;
}

function fUpdate_Check($dirSource, $dirTarget)
{
    $dirTarget = $dirTarget.'/';
    $dirTarget = str_replace('//', '/', $dirTarget);
    
    if ($handle = @opendir($dirSource))
    {
        while (false !== ($dir = @readdir($handle)))
        {
            if ($dir != '.' && $dir != '..')
            {
                $fromDir = $dirSource . $dir;
                $toDir  = $dirTarget . $dir;
        
                if (@is_dir($fromDir))
                {
                    if(!@file_exists($toDir))
                    {
                        $oldmask = umask(0);
                        if(!@mkdir($toDir))
                        {
                            $GLOBALS['file_not_access'][] = $toDir;
                        }
                        else
    		            {
    			            umask($oldmask);
    		            }
                    }
                    fUpdate_Check($fromDir . '/', $toDir . '/');
                }
                else
                {
                    $fileName = substr($fromDir, strrpos($fromDir, '/') + 1);
                    if ($fileName == 'dump.sql' || $fileName == 'exec.php')
                    {
                        continue;
                    }
                    if(@file_exists($toDir))
                    {
                        $access = @fileperms($toDir);
                        
                        if (!@is_writable($toDir))
                        {
                            $GLOBALS['file_not_access'][] = $toDir.' : '.substr(sprintf('%o', $access), -3,-2).substr(sprintf('%o', $access), -2,-1).substr(sprintf('%o', $access), -1);
                        }
                        /*$uid_file = @fileowner($toDir);
                        $gid_file = @filegroup($toDir);
                        $uid_server = '';
                        $gid_server = '';
                        
                        if (function_exists('posix_getuid'))
                        {
                            $uid_server = @posix_getuid();
                        }
                        if (function_exists('posix_getgid'))
                        {
                            $gid_server = @posix_getgid();
                        }
                        
                        if($uid_file == $uid_server)
                        {
                            if(substr(sprintf('%o', $access), -3,-2) < 6 && $access != 33206 && $access != 16895)
                            {
                                $GLOBALS['file_not_access'][] = $toDir.' : '.substr(sprintf('%o', $access), -3,-2).substr(sprintf('%o', $access), -2,-1).substr(sprintf('%o', $access), -1);
                            }
                        }
                        else if ($gid_file == $gid_server)
                        {
                            if(substr(sprintf('%o', $access), -2,-1) < 6 && $access != 33206 && $access != 16895)
                            {
                                $GLOBALS['file_not_access'][] = $toDir.' : '.substr(sprintf('%o', $access), -3,-2).substr(sprintf('%o', $access), -2,-1).substr(sprintf('%o', $access), -1);
                            }
                        }
                        else 
                        {
                            if(substr(sprintf('%o', $access), -1) < 6 && $access != 33206 && $access != 16895)
                            {
                                $GLOBALS['file_not_access'][] = $toDir.' : '.substr(sprintf('%o', $access), -3,-2).substr(sprintf('%o', $access), -2,-1).substr(sprintf('%o', $access), -1);
                            }
                        }*/
                    }
                }
            }
        }
        @closedir($handle);
    }
}

function fUpdate_Copy($dirSource, $dirTarget, $dirBackup = '', $backup)
{
    $dirTarget = $dirTarget.'/';
    $dirTarget = str_replace('//', '/', $dirTarget);
    $dirSource = str_replace('//', '/', $dirSource);
    $dirBackup = str_replace('//', '/', $dirBackup);
    
    $backup = $backup && $_SESSION['binn_update_rollback'];
    
    if($backup && !file_exists($dirBackup)) 
    {
        $oldmask = umask(0);
        if(!@mkdir($dirBackup))
        {
            _showStaticWarning(PL_UPDATE_NO_MKDIR);
            return;
        }
        else
	    {
		    umask($oldmask);
	    }
    }
    
    if ($handle = @opendir($dirSource))
    {
        while (false !== ($dir = @readdir($handle)))
        {
            if ($dir != '.' && $dir != '..')
            {
                $fromDir = $dirSource . $dir;
                $toDir = $dirTarget . $dir;
                $toDirBackup = $dirBackup . $dir;

                if (@is_dir($fromDir))
                {
                    if(!@file_exists($toDir))
                    {
                        $oldmask = umask(0);
                        if(!@mkdir($toDir))
                        {
                            _showStaticWarning(PL_UPDATE_NO_MKDIR);
                            return;
                        }
                        else
                		{
                			umask($oldmask);
                		}
                    }
                    
                    if($backup && !file_exists($toDirBackup))
                    {
                        $oldmask = umask(0);
                        if(!@mkdir($toDirBackup))
                        {
                            _showStaticWarning(PL_UPDATE_NO_MKDIR);
                            return;
                        }
                        else
    		            {
    			            umask($oldmask);
    		            }
                    }

                    fUpdate_Copy($fromDir . '/', $toDir . '/', $toDirBackup . '/', $backup);
                }
                else
                {
                    $fileName = substr($fromDir, strrpos($fromDir, '/') + 1);
                    if ($fileName == 'dump.sql' || $fileName == 'exec.php')
                    {
                        continue;
                    }
                    if ($backup && ($fileName == 'rollback_dump.sql' || $fileName == 'rollback_exec.php'))
                    {
                        $copy_error_backup = @copy($fromDir, $toDirBackup);
                        @chmod($toDirBackup, octdec($_SESSION['binn_file_rights']));
                        continue;
                    }
                          
                    if($backup)
                    {
                        $copy_error_backup = @copy($toDir, $toDirBackup);
                    }
          
                    $copy_error = @copy($fromDir, $toDir);
                    @chmod($toDir, octdec($_SESSION['binn_file_rights']));
                    
                    if ($copy_error > 0) 
                    {
                        $copy_status = '<b style="color: #009900;">'.PL_UPDATE_OK.'</b>';
                    }
                    else
                    {
                        $copy_status = '<b style="color: #DD0000;">'.PL_UPDATE_ERROR.'</b>';
                        $GLOBALS['copy_error'] = 1;
                    }

                    echo PL_UPDATE_COPY_FILE.$toDir.' - '.$copy_status.'<br>';
                }
            }
        }
        @closedir($handle);
    }
}

function fUpdate()
{
    if(!@opendir($_SESSION['binn_basedir'].'/cms/tmp'))
    {
        $oldmask = umask(0);
        if(!@mkdir($_SESSION['binn_basedir'].'/cms/tmp', octdec($_SESSION['binn_file_rights'])))
        {
            _showStaticWarning(PL_UPDATE_NO_MKDIR);
            return;
        }
        else
		{
			umask($oldmask);
		}
       
        if(!@opendir($_SESSION['binn_basedir'].'/cms/tmp/'.$update_id))
        {
            $oldmask = umask(0);
            if(!@mkdir($_SESSION['binn_basedir'].'/cms/tmp/'.$update_id, octdec($_SESSION['binn_file_rights'])))
            {
                _showStaticWarning(PL_UPDATE_NO_MKDIR);
                return;
            }
            else
    		{
    			umask($oldmask);
    		}
        }
    }

    if(!@opendir($_SESSION['binn_basedir'].'/cms/tmp/backup'))
    {   
        $oldmask = umask(0);
        if(!@mkdir($_SESSION['binn_basedir'].'/cms/tmp/backup', octdec($_SESSION['binn_file_rights'])))
        {   
            _showStaticWarning(PL_UPDATE_NO_MKDIR);
            return;
        }
        else
		{
			umask($oldmask);
		}
    }
    
    $arr = sql_query('SELECT * FROM binn_update ORDER BY bu_dsetup DESC');
    
    echo '<br><center><b>'.PL_UPDATE_UPDATE_SYSTEM.'</b></center>';
  
    $tbl = '<center><b><i>'.PL_UPDATE_ESTABLISHED_UPDATING.'</i></b><br><br>
            <table width="95%" cellpadding="3" cellspacing="0" border="0">
            <tr style="background:#486BA1;color:#FFFFFF;font-weight:bold;text-align:center;">
                <td width="70">'.PL_UPDATE_VERSION.'</td>
                <td width="110">'.PL_UPDATE_DATE_RELIZE.'</td>
                <td width="110">'.PL_UPDATE_DATE_INSTALLATION.'</td>
                <td>'.PL_UPDATE_INFORMATION.'</td><td>&nbsp;</td></tr>';
    
    $i_updates = array();
    
    for($i = 0; $i < count($arr); $i++)
    {
        list($bu_id, $bu_uid, $bu_version, $bu_dreliase, $bu_dsetup, $bu_info) = $arr[$i];
        if($i == 0)
        {
            $last_v = $bu_version;
            $last_d = $bu_dsetup;
            $last_r = $bu_dreliase;
          
            if(@opendir($_SESSION['binn_basedir'].'/cms/tmp/backup/'.$bu_uid))
            {
                $button = '<input type="button" onClick="document.location=\'/cms/kernel/content.php?event=pl_update_rollback&version='.$last_v.'&bu_uid='.$bu_uid.'&date='.date('d.m.Y', $bu_dreliase).'\'" value="'.PL_UPDATE_RECOIL.'">';
            }
            else 
            {
                $button = '&nbsp;';
            }
        }
        else 
        {
            $button = '&nbsp;';
        }
    
        $i_updates[$bu_uid] = true;
    
        $tbl .= '<tr style="text-align:center;background:#E2E2E2;" valign="middle">
            <td style="border-bottom: 1px solid #000099;">'.$bu_version.'</td>
            <td style="border-bottom: 1px solid #000099;">'.date('d.m.Y', $bu_dreliase).'</td>
            <td style="border-bottom: 1px solid #000099;">'.date('d.m.Y', $bu_dsetup).'</td>
            <td style="border-bottom: 1px solid #000099;" align="left">'.$bu_info.'</td>
            <td style="border-bottom: 1px solid #000099;">'.$button.'</td></tr>';
    }
    $tbl .= '</table></center>';

    $UPLOAD_TYPE='FTP';

    if(@file_exists($_SESSION['binn_basedir'].'/cms/tmp/'.BINN_UPDATE_FILENAME)) 
    {
        $info = @file($_SESSION['binn_basedir'].'/cms/tmp/'.BINN_UPDATE_FILENAME);

        for($i = 0; $i < count($info); $i++)
        {
            $str = explode(';', $info[$i]);
            
            if(!array_key_exists($str[0], $i_updates) && BINN_DISTR_VERSION < $str[1])
            {
                $UPLOAD_TYPE = 'LOCAL';
                break;
            }
        }
    }

    $update_flag = false;
    $installing_update_id = -1;
    $installing_update_version = '';
    $installing_update_date = '';
    $installing_update_backup = 0;
    $installing_update_text = '';
    
    if ($UPLOAD_TYPE == 'FTP') 
    {
        $httpRequest = new binnSocket('http://www.sbuilder.ru/'.BINN_UPDATE_FILENAME);
        $info = $httpRequest->downloadString();
        if(!$info || stristr($info, '404 not found'))
        {
            _showStaticWarning(PL_UPDATE_ERROR_CONNECTION);
            return ;
        }

        $info = explode("\r\n", $info);
        $tbl_a = '<hr size="1"><center><b><i>'.PL_UPDATE_NO_UPDATE.'</i></b><br><br>
            <table width="95%" cellpadding="3" cellspacing="0">
            <tr style="background:#486BA1;color:#FFFFFF;font-weight:bold;text-align:center; border-bottom: 1px solid #000099;">
            <td width="70">'.PL_UPDATE_VERSION.'</td>
            <td width="110">'.PL_UPDATE_DATE_RELIZE.'</td>
            <td>'.PL_UPDATE_INFORMATION.'</td></tr>';
    
        $num = count($info);
        for ($i = 0; $i < $num; $i++)
        {
            if (empty($info[$i]))
                continue;
                
            $str = explode(';', $info[$i]);
                
            $update_id = $str[0];
            $version = $str[1];
            
            if(!array_key_exists($update_id, $i_updates) && BINN_DISTR_VERSION < $version && $update_id != '')
            {
                $drelease = $str[2];
                $descr = trim($str[3], "\r\n");    
        
                if ($installing_update_id == -1) 
                {
                    $installing_update_id = $update_id;
                    $installing_update_version = $version;
                    $installing_update_date = $drelease;
                    $installing_update_backup = (isset($str[4]) && $str[4] == '1' ? 1 : 0);
                    $installing_update_text = $descr;
                }
                $update_flag = true;
                
                $tbl_a .= '<tr style="text-align:center;background:#E2E2E2;" valign="middle">
                    <td style="border-bottom: 1px solid #000099;">'.$version.'</td>
                    <td style="border-bottom: 1px solid #000099;">'.$drelease.'</td>
                    <td style="border-bottom: 1px solid #000099;" align="left">'.$descr.'</td></tr>';
            }
        }
        $tbl_a .= '</table></center>';
    } 
    else 
    {
        $tbl_a = '<br><center><b><i>'.PL_UPDATE_NO_INSTALLING_UPDATE.'</i></b>
        <table width="95%" cellpadding="3" cellspacing="0" border="0">
        <tr style="background:#486BA1;color:#FFFFFF;font-weight:bold;text-align:center; border-bottom: 1px solid #000099;">
        <td>'.PL_UPDATE_VERSION.'</td>
        <td>'.PL_UPDATE_DATE_RELIZE.'</td>
        <td>'.PL_UPDATE_INFORMATION.'<br><i>'.PL_UPDATE_DATA_UPDATING_LOCATED.'</i></td></tr>';
    
        for($i = 0; $i < count($info); $i++)
        {
            if (empty($info[$i]))
                continue;

            $str = explode(';', $info[$i]);
            $update_id = $str[0];
            $version = $str[1];
            
            if(!array_key_exists($update_id, $i_updates) && BINN_DISTR_VERSION < $version && $update_id != '')
            {
                $drelease = $str[2];
                $descr = trim($str[3], "\r\n");  
            
                if ($installing_update_id == -1) 
                {
                    $installing_update_id = $update_id;
                    $installing_update_version = $version;
                    $installing_update_date = $drelease;
                    $installing_update_backup = (isset($str[4]) && $str[4] == '1' ? 1 : 0);
                    $installing_update_text = $descr;
                }
                $update_flag = true;
                
                $tbl_a .= '
                <tr style="text-align:center;background:#E2E2E2;" valign="middle">
                <td style="border-bottom: 1px solid #000099;">'.$version.'</td>
                <td style="border-bottom: 1px solid #000099;">'.$drelease.'</td>
                <td style="border-bottom: 1px solid #000099;" align="left">'.$descr.'</td></tr>';
            }
        }
        $tbl_a .= '</table></center>';
    }

    if($update_flag)
    {
        $dload = '<br><center><form action="'.$_SESSION['binn_cms_mainfile'].'?event=pl_update_start" method="post">
                  <input type="hidden" name="update_id" value="'.$installing_update_id.'">
                  <input type="hidden" name="update_version" value="'.$installing_update_version.'">
                  <input type="hidden" name="update_date" value="'.$installing_update_date.'">
                  <input type="hidden" name="update_backup" value="'.$installing_update_backup.'">
                  <textarea name="update_text" style="width:1px; height:1px; visibility: hidden;">'.htmlspecialchars($installing_update_text, ENT_QUOTES, ($_SESSION['binn_cms_utf8'] ? 'utf-8' : 'windows-1251')).'</textarea>
                  <input type="submit" value="'.PL_UPDATE_INSTALLING_NEXT_UPDATE.'">
                  </form>
                  </center><br><br>';
    }
    else 
    {
        $dload = '';
    }
        
    if(count($i_updates) > 0)
    {
        echo '<b>'.PL_UPDATE_CURRENT_RELEASE_SYSTEM.'</b>: <i>'. $last_v .'</i> ('.PL_UPDATE_UPDATE_OT.'<i>'.date('d.m.Y', $last_r).'</i>)<br>
              <b>'.PL_UPDATE_DATE_LAST_UPDATING.'</b>: <i>'. date('d.m.Y', $last_d) .'</i><br>'.$tbl.$tbl_a;
    }
    else
    {
        echo '<b>'.PL_UPDATE_CURRENT_RELEASE_SYSTEM.'</b>: <i>'.BINN_DISTR_VERSION.'</i><br>
              <b>'.PL_UPDATE_DATE_LAST_UPDATING.'</b>: <i>'.PL_UPDATE_NO_UPDATING_2.'</i><br>'.$tbl_a;
    }
    echo $dload;
}

function fUpdate_Start()
{
    $update_id = $_POST['update_id'];
    if (empty($update_id))
    {
        fUpdate();
        return;
    }
    $update_version = $_POST['update_version'];
    $update_date = $_POST['update_date'];
    $update_backup = $_POST['update_backup'] == 1;
    $update_text = $_POST['update_text'];
    
    $UPLOAD_TYPE='FTP';

    if(file_exists($_SESSION['binn_basedir'].'/cms/tmp/'.BINN_UPDATE_FILENAME)) 
    {
        $arr = sql_query('SELECT bu_version FROM binn_update ORDER BY bu_version DESC');
        list($last_v) = $arr[0];

        if ($last_v < BINN_DISTR_VERSION) 
        {
            $last_v = BINN_DISTR_VERSION;
        }

        $info = @file($_SESSION['binn_basedir'].'/cms/tmp/'.BINN_UPDATE_FILENAME);
        
        for($i = 0; $i < count($info); $i++)
        {
            $str = explode(';', $info[$i]);
            if($last_v < $str[1])
            {
                $UPLOAD_TYPE = 'LOCAL';
                break;
            }
        }
    }

    if ($UPLOAD_TYPE == 'FTP') 
    {
        $httpRequest = new binnSocket('http://www.sbuilder.ru/get_ftp.php');
        $text = $httpRequest->downloadString();
        
        if(!$text)
        {
            _showWarning(PL_UPDATE_ERROR_CONNECTION);
            return ;
        }
      
        $status = explode(';', $text);
        $ftp_login = $status[0];
        $ftp_passw = $status[1];

        $conn_id = false;
        if (function_exists('ftp_connect'))
            $conn_id = @ftp_connect('sbuilder.ru');
        
        if(!$conn_id)
        {
            _showWarning(PL_UPDATE_ERROR_CONNECTION);
            return;
        }

        if(!@ftp_login($conn_id, $ftp_login, $ftp_passw))
        {
            _showWarning(PL_UPDATE_ERROR_CONNECTION_2);
            return;
        }
        //   
        @ftp_pasv($conn_id, true);
  
        if(!@file_exists($_SESSION['binn_basedir'].'/cms/tmp/'.$update_id)) 
        {   
            $oldmask = umask(0);
            if(!@mkdir($_SESSION['binn_basedir'].'/cms/tmp/'.$update_id, octdec($_SESSION['binn_file_rights'])))
            {
                _showStaticWarning(PL_UPDATE_NO_MKDIR);
                return;
            }
            else
    	    {
    	        umask($oldmask);
    	    }
        }
     
        if(!fUpdate_Get_Dir($conn_id, $_SESSION['binn_basedir'].'/cms/tmp/'.$update_id.'/', $update_id, FTP_BINARY))
        {
            _showStaticWarning(PL_UPDATE_ERROR_UPDATE_2);
            return;
        }
    }

    echo '<br><b>'.PL_UPDATE_INSTALLATION_UPDATING.'</b> '.$update_version.' <b>'.PL_UPDATE_OT.'</b> '.$update_date.':<br><br>';

    $GLOBALS['copy_error'] = 0;
    $GLOBALS['file_not_access'] = array();
  
    fUpdate_Check($_SESSION['binn_basedir'].'/cms/tmp/'.$update_id.'/', $_SESSION['binn_basedir']);

    if(count($GLOBALS['file_not_access']) == 0)
    {
        fUpdate_Copy($_SESSION['binn_basedir'].'/cms/tmp/'.$update_id.'/', $_SESSION['binn_basedir'], $_SESSION['binn_basedir'].'/cms/tmp/backup/'.$update_id.'/', $update_backup); 
      
        if ($GLOBALS['copy_error'] == 0)
        {
            echo "<br><b style='color: #009900;'>".PL_UPDATE_UPDATING_PASSED_SUCCESSFULLY."</b><hr>";
        }
        else
        {
            echo "<br><b style='color: #009900;'>".PL_UPDATE_UPDATING_PASSED_INCORRECT."</b><hr>";
        }
      
        if(@file_exists($_SESSION['binn_basedir'].'/cms/tmp/'.$update_id.'/exec.php'))
        {
            include($_SESSION['binn_basedir'].'/cms/tmp/'.$update_id.'/exec.php');
        }
      
        if(file_exists($_SESSION['binn_basedir'].'/cms/tmp/'.$update_id.'/dump.sql'))
        {
            $list = @file($_SESSION['binn_basedir'].'/cms/tmp/'.$update_id.'/dump.sql');
    
            $c = count($list);
            $q = '';
            $db_num = 0;
            $db = array();
            $insert = array();
            $drop = array();
            
            for ($m = 0; $m < $c; $m++)
            {
                $str = $list[$m];
    
                if (($str[0] != '#') && ($str != "\r\n") && (strlen($str) > 2))
                {
                    if ((substr($str, 0, 6) == 'INSERT') || (substr($str, 0, 5) == 'ALTER') || (substr($str, 0, 6) == 'UPDATE') || (substr($str, 0, 6) == 'DELETE'))
                    {
                        $insert[] = substr($str, 0, strlen($str)-2);
                    }
                    elseif(substr($str, 0, 4) == 'DROP')
                    {
                        $drop[] = substr($str, 0, strlen($str)-2);
                    }
                    else
                    {
                        if (substr($str, 0, 6) == 'CREATE')
                        {
                            $db[$db_num] = substr($str, 0, strlen($str)-2);
                        }
                        else
                        {
                            $db[$db_num] .= substr($str, 0, strlen($str)-2);
                            if (substr($str, 0, 6) == ') TYPE')
                            {
                                $db_num++;
                            }
                        }
                    }
                }
            }
    
            $num = count($db);
            $num1 = count($drop);
            $num2= count($insert);
    
            $error = 0;
    
            for ($i=0; $i<$num1; $i++)
            {
                $res = sql_query($drop[$i]);
                
                if (!$res) $error = 1;
            }
            
            for ($i = 0; $i < $num; $i++) 
            {
                $res = sql_query($db[$i]);
    
                if (!$res) $error = 1;
            }
    
            for ($i=0; $i<$num2; $i++)
            {
                $res = sql_query($insert[$i]);
                
                if (!$res) $error = 1;
            }
        }

        $date = explode('.', $update_date);
        $update_date = mktime(0, 0, 0, $date[1], $date[0], $date[2]);
        sql_query("INSERT INTO binn_update (bu_uid, bu_version, bu_dreliase, bu_dsetup, bu_info) VALUES ('".$update_id."', '".$update_version."', '".$update_date."', '".mktime()."', '".$update_text."');");
    }
    else 
    {
        $warning = '<b>'.PL_UPDATE_ARISEN_ERROR.'</b><br><br>';
      
        foreach ($GLOBALS['file_not_access'] as $key => $value)
        {
            $warning .= '<span style="color: red;">'.$value.'</span><br>';
        }
      
        echo $warning.'<br><form action="/cms/kernel/content.php?event=pl_update_send_mail" method="post">
            <b>'.PL_UPDATE_SET_EMAIL.':</b>
            &nbsp;&nbsp;<input type="text" name="mail" value="'.$_SESSION['binn_cms_email'].'">
            &nbsp;&nbsp;<input type="submit" value="'.PL_UPDATE_SET_EMAIL_BUTTON.'">
            <textarea name="message" style="width:1px; height:1px;visibility:hidden;">'.htmlspecialchars($warning, ENT_QUOTES, ($_SESSION['binn_cms_utf8'] ? 'utf-8' : 'windows-1251')).'</textarea>
            </form><hr size="1">';
    }
    fUpdate();
}
?> 