<?php

/*
 *    Launchpad robot
 *
 *    version: 0.02a
 *    developed: Karoly Gossler
 *    mail: connor [at) connor (dot] hu
 *    web: blog.connor.hu
 *    licence: GPLv2 :: http://www.gnu.org/licenses/gpl.txt
 */

class launchpad
{
  public 
$verbose;

  private 
$tmp_dir '.';
  private 
$cookie_file '/cookie.lp.txt';
  private 
$email;
  private 
$password;
  public 
$mailbox_user;
  public 
$mailbox_password;
  public 
$mailbox_domain;

  private 
$main_page 'https://launchpad.net/';
  private 
$trans_domain 'https://translations.launchpad.net';

  public function 
__construct($email$password)
  {
        
$this->email $email;
        
$this->password $password;
        
$this->mailbox_password $mailbox_password;
  }

  private 
$not_logged_in_text 'Not logged in ';

  public function 
is_logged_in()
  {
    
$fetcher = new page_get('https://launchpad.net');
    
$fetcher->save_cookies $fetcher->load_cookies $this->tmp_dir $this->cookie_file;
        
$fetcher->referer 'https://launchpad.net';
    
$fetcher->fetch();

//        print_r($fetcher->get_headers());

    
return ! (bool) strpos($fetcher->result$this->not_logged_in_text);
  }

  private 
$email_form_name 'loginpage_email';
  private 
$passwd_form_name 'loginpage_password';
  private 
$login_button_name 'loginpage_submit_login';
  private 
$login_button_value 'Log In';

  public function 
login()
  {    
    
$form_vars = array(
      
$this->email_form_name => $this->email,
      
$this->passwd_form_name => $this->password,
      
$this->login_button_name => $this->login_button_value,
      );

    
$fetcher = new page_get('https://launchpad.net/+login');
        
$fetcher->referer 'https://launchpad.net/+login';
    
$fetcher->save_cookies $fetcher->load_cookies $this->tmp_dir $this->cookie_file;
        
$fetcher->post_data $form_vars;
    
$fetcher->fetch();

//        print_r($fetcher->result);

    
return true;
  }

  private 
$distribution null;
  public function 
set_distribution($distribution)
  {
    if (!
in_array($distribution, array('dapper''edgy''feisty''gutsy')))
    {
      return 
false;
    }
    
$this->distribution $distribution;
  }

    public function 
get_languages()
    {
        
$url $this->trans_domain .'/ubuntu/'$this->distribution .'/';
        
$list = array();

    
$fetcher = new page_get($url);
        
$fetcher->referer 'https://launchpad.net/ubuntu/'$this->distribution .'/';
    
$fetcher->save_cookies $fetcher->load_cookies $this->tmp_dir $this->cookie_file;
    
$fetcher->fetch();
        
$content $fetcher->result;

        
$dom = new DomDocument();
        @
$dom->loadhtml($content);
        
$xpath = new Domxpath($dom);

        
$result $xpath->query('//*[@id="languagestats"]/tbody/tr/td[1]');

        for (
$i 0$i $result->length$i++)
        {
            
$name $result->item($i)->childNodes->item(1)->nodeValue;
            
preg_match('!/([a-z\_A-Z]+)$!'$result->item($i)->childNodes->item(1)->getattribute('href'), $match);
            
$key $match[1];
            
$list[$key] = $name;
        }

        return 
$list;
    }

    public function 
get_templates($source_package)
    {
        
$url $this->trans_domain .'/ubuntu/'$this->distribution .'/+source/'$source_package .'/';
    
$fetcher = new page_get($url);
        
$fetcher->referer 'https://launchpad.net/ubuntu/'$this->distribution .'/+source/'$source_package .'/';
    
$fetcher->save_cookies $fetcher->load_cookies $this->tmp_dir $this->cookie_file;
    
$fetcher->fetch();
        
$content $fetcher->result;

//        file_put_contents('tmp', $content);

//        $content = file_get_contents('tmp');

        
preg_match_all('!Template\ \"([^\"]+)\"!'$content$matches);
        return 
$matches[1];
    }

    public function 
export_po($source_name$template_name$export_dir)
    {
        
$url $this->trans_domain .'/ubuntu/'$this->distribution .'/+source/'$source_name .'/+pots/'$template_name .'/hu/+export';

    
$fetcher = new page_get($url);
        
$fetcher->referer $url;
    
$fetcher->save_cookies $fetcher->load_cookies $this->tmp_dir $this->cookie_file;
    
$fetcher->post_data['format'] = 'PO';
    
$fetcher->fetch();

//        print_r($fetcher->get_headers());
        
if (strpos($fetcher->result'msgid ""') !== false)
        {
            
file_put_contents($export_dir .'hu_'$source_name .'_'$template_name .'.po'$fetcher->result);
        }
        else
        {
            while (
true)
            {
                echo 
'read mail';
                echo 
NL;

                
$link $this->read_mails($source_name$template_name);
                if (
$link !== false)
                {
                    
$fetcher->url $link;
                    
$fetcher->fetch();
                    
file_put_contents($export_dir .'hu_'$source_name .'_'$template_name .'.po'$fetcher->result);
                    break;
                }
                
sleep(60*2);
            }
        }
    }

    public function 
init_mailer($server$username$password)
    {
        
$this->mailbox_user $username;
        
$this->mailbox_password $password;
        
$this->mailbox_domain $server;
    }

    private function 
read_mails($source_name$template_name)
    {
        
$mbox imap_open('{'$this->mailbox_domain .':110/pop3/notls}INBOX'$this->mailbox_user$this->mailbox_password);

        
$mboxinfo imap_mailboxmsginfo($mbox);

        for (
$i 0$i $mboxinfo->Nmsgs$i++)
        {
            if (
imap_headerinfo($mbox$i+1)->subject == 'Translation download request: '$template_name)
            {
                
preg_match('!http(.*)!'imap_body($mbox$i+1), $matches);
                
$link $matches[0];
                
imap_delete($mbox$i+1);
                
imap_expunge($mbox);
                
imap_close($mbox);
                return 
trim($link);
            }
        }

        
imap_close($mbox);
        return 
false;
    }

    public function 
get_new_uploads($list_to)
    {
        
$start 0;

        while (
true)
        {
            
$url 'https://launchpad.net/ubuntu/'$this->distribution .'/+queue?queue_state=3&queue_text=&start='$start;

            
$fetcher = new page_get($url);
            
$fetcher->referer 'https://launchpad.net/ubuntu/feisty';
            
$fetcher->save_cookies $fetcher->load_cookies $this->tmp_dir $this->cookie_file;
            
$fetcher->fetch();
            
$content $fetcher->result;

            
$dom = new DomDocument();
            @
$dom->loadhtml($content);
            
$xpath = new Domxpath($dom);

            
file_put_contents('tmp'$content);

            if (
$list_per_page === null)
            {
                
$list_per_page '//*[@id="maincontent"]/div[2]/div/table/tbody/tr/td/strong[2]';
                
$result $xpath->query($list_per_page);
                
$list_per_page = (int) $result->item(0)->nodeValue;
            }

            
$result $xpath->query('//*[@id="distroreleasequeue"]/tbody/tr');

            for (
$i 0$i $result->length$i++)
            {
                
$package_name trim($result->item($i)->childNodes->item(2)->childNodes->item(2)->nodeValue);
                
$version trim($result->item($i)->childNodes->item(4)->nodeValue);
                
$stamp strtotime($result->item($i)->childNodes->item(8)->childNodes->item(1)->nodeValue);

                if (
$stamp $list_to)
                {
                    return 
$list;
                }

                
$list[] = array(
                    
'package_name' => $package_name,
                    
'version' => $version,
                    
'upload_time' => $stamp,
                    );
            }

            
$start += $list_per_page;
        }

        return 
$list;
    }

    public function 
get_translations()
    {
        
$url =  $this->trans_domain .'/ubuntu/'$this->distribution .'/+lang/hu';

        
$next_link '//*[@id="maincontent"]/div[2]/table/tbody/tr/td[2]/a[@rel="next"]';
        do
        {
            
$fetcher = new page_get($url);
            
$fetcher->referer 'https://launchpad.net/ubuntu/feisty';
            
$fetcher->save_cookies $fetcher->load_cookies $this->tmp_dir $this->cookie_file;
            
$fetcher->fetch();
            
$content $fetcher->result;

            
$dom = new DomDocument();
            @
$dom->loadhtml($content);
            
$xpath = new Domxpath($dom);

            
$result $xpath->query('//*[@id="translationstatuses"]/tbody/tr');

            foreach (
$result as $item)
            {
                
$i 0;
                
// TODO: nem kell ciklus
                
foreach ($item->getelementsbytagname('td') as $cell)
                {
                    switch(
$i)
                    {
                        case 
0:
                            
$link $cell->getelementsbytagname('a')->item(0)->getattribute('href');
                            
preg_match('!\/\+source\/([^\/]+)/!'$link$matches);
                            
$name $cell->getelementsbytagname('a')->item(0)->nodeValue;
                            break;

                        case 
1:
                            
$size $cell->nodeValue;
                            break;

                        case 
3:
                            
$todo = (int) $cell->nodeValue;
                            break;
                    }
                    
$i++;
                }
                
$list[] = array(
                    
'link' => $link,
                    
'source_name' => $matches[1],
                    
'name' => $name,
                    
'size' => $size,
                    
'todo' => $todo,
                    );
            }

            
$result $xpath->query($next_link);
            if (
$result->length)
            {
                
$url $result->item(0)->getattribute('href');
            }
            else
            {
                
$url false;
            }

        } while (
$url);

        return 
$list;
    }
}

class 
page_get
{
  public 
$load_cookies '';
  public 
$save_cookies '';
  public 
$result '';
  public 
$post_data false;
  public 
$referer false;
    public 
$debug false;
  public 
$url '';
  private 
$redirect_couter 0;
  private 
$url_parts '';
  private 
$headers = array();

  public function 
__construct($url)
  {
    
$this->url $url;
    if (!
defined('NL'))
    {
      
define('NL'"\n");
    }
        if (!
function_exists('gzdecode')) {
            function 
gzdecode ($data) {
                
// Check if data is GZIP'ed
                
if (strlen($data) < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
                    return 
false;
                }

                
// Remove first 10 bytes
                
$data substr($data10);

                
// Return regular data
                
return gzinflate($data);
            }
        }
    }

    public function 
get_headers()
    {
        return 
$this->headers;
    }

  private function 
get_header()
  {
    
$this->url_parts parse_url($this->url);

    if (
$this->url_parts['path'] === null)
    {
      
$this->url_parts['path'] = '/';
    }
    if (
$this->url_parts['query'] !== null)
    {
      
$this->url_parts['path'] .= ('?'$this->url_parts['query']);
    }

    
$cookies '';
    if (
$this->load_cookies !== false && is_file($this->load_cookies))
    {
      
$cookies trim(implode(''file($this->load_cookies)));
    }

    if (
$this->post_data !== false)
    {
      
$header 'POST '$this->url_parts['path'] .' HTTP/1.1'NL;
    }
    else
    {
      
$header 'GET '$this->url_parts['path'] .' HTTP/1.1'NL;
    }
    
$header .= 'Host: '$this->url_parts['host'] . NL;

        if (
$this->referer !== false)
        
$header .= 'Referer: '$this->referer NL;

        
$header .= 'Keep-Alive: 300'NL;
        
$header .= 'Connection: keep-alive'NL;
        
$header .= 'Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'NL;
        
$header .= 'Accept-Language: hu'NL;
        
$header .= 'Accept-Encoding: gzip,deflate'NL;
    
$header .= 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; hu; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4'NL;

    if (
$cookies)
    {
      
$header .= 'Cookie: '$cookies NL;
    }
    if (
$this->post_data !== false)
    {
      foreach (
$this->post_data as $name => $value)
      {
                
$post_data .= '&'$name .'='urlencode($value);
      }
            
$post_data substr($post_data1);
            
$header .= 'Content-Type: application/x-www-form-urlencoded' .NL;
      
$header .= 'Content-Length: 'strlen($post_data) .NL;
      
$header .= NL;
      
$header .= $post_data;
    }
    else
    {
      
$header .= NL;
    }
    return 
$header;
  }

  public function 
fetch()
  {
    
$header $this->get_header();

        if (
$this->debug == true)
        {
            
print_r($header);
        }
        echo 
$this->url;
        echo 
"\n";

    if (
$this->url_parts['scheme'] == 'http')
    {
      
$prefix '';
      
$port 80;
    }
    elseif (
$this->url_parts['scheme'] == 'https')
    {
      
$prefix 'ssl://';
      
$port 443;
    }

    
$t fsockopen($prefix $this->url_parts['host'], $port$errno$errstr12);
    if (
$t === false)
    {
      exit;
    }

        
fputs($t$header);

    
$just_headers false;
    
$result '';

    while (!
feof($t))
    {
      
$result .= fread($t1024);
      if (
$just_headers !== false && strpos($result'Connection: ') !== false)
      {
        break;
      }
    }
    
fclose($t);

        
$isheader true;
    foreach (
explode("\n"$result) as $line)
    {
      if (
strlen(trim($line)) === 0)
      {
        
$isheader false;
        continue;
      }
      if (
$isheader)
      {
        list(
$name$value) = $this->header_parse($line);
        
$name strtolower($name);
        
$this->headers[$name] = $value;
        
        if (
$name == 'location') {
          
$this->redirect_couter++;
          if (
$this->redirect_couter 10)
            return;

                    
// todo rendes location kezelés
                    
if (substr($value04) == 'http')
                        
$this->url trim($value);
                    else
                        
$this->url $this->url_parts['scheme'] .'://'$this->url_parts['host'] . trim($value);

                    
$this->fetch();

          return;
        }
      }
      else
      {
        
$content .= $line "\n";
      }
    }

        if (
$this->headers['set-cookie'] && $this->save_cookies)
        {
            
file_put_contents($this->save_cookiessubstr($this->headers['set-cookie'], 0strpos($this->headers['set-cookie'], ';')));
        }

        if (
trim($this->headers['content-encoding']) == 'gzip')
            
$content gzdecode($content);

    
$this->result $content;
  }

  private function 
header_parse($header)
  {
    if (
substr($header04) == 'HTTP')
    {
      return array(
0$header);
    }
    return array(
substr($header0strpos($header':')), substr($headerstrpos($header':')+2));
  }
}

?>