HosipLan

Untitled

Feb 24th, 2012
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.21 KB | None | 0 0
  1. <?php
  2.  
  3. class GmailImap
  4. {
  5.     var $server = '{imap.gmail.com:993/ssl/novalidate-cert}';
  6.  
  7.     var $headers;
  8.     var $connection;
  9.  
  10.     function __construct($email, $password)
  11.     {
  12.         imap_timeout(IMAP_OPENTIMEOUT, 10);
  13.  
  14.         $this->connection = imap_open($this->server, $email, $password, OP_READONLY);
  15.  
  16.         if (!$this->connection){
  17.             //debug::dump(imap_errors());
  18.             throw new GmailImapException("Spojení se nezdařilo! ".imap_last_error());
  19.         }
  20.  
  21.         if( !imap_ping($this->connection) ){
  22.             throw new GmailImapException("Spojení se přerušilo! ".imap_last_error());
  23.         }
  24.  
  25.         if( $hdr = imap_check($this->connection) ){
  26.             //debug::dump("Zprav na serveru: " . $hdr->Nmsgs);
  27.  
  28.         } else {
  29.             throw new GmailImapException("'imap_check' selhal! ".imap_last_error());
  30.         }
  31.  
  32.         if( class_exists('Environment') ){
  33.             Environment::getApplication()->onShutdown[] = array($this, '__destruct');
  34.         }
  35.     }
  36.  
  37.  
  38.     function getAttachment($time = Null, $saveAStime = Null)
  39.     {
  40.         $filtered = imap_search($this->connection, "ON ".date("d-M-Y", $time));
  41.  
  42.         if( $filtered === False ){
  43.             return array( $time => array() );
  44.         }
  45.        
  46.         if( $saveAStime !== Null ){
  47.             $time = $saveAStime;
  48.         }
  49.  
  50.         $xmls = array();
  51.  
  52.         foreach( $filtered AS $msgno ){
  53.             // Tue, 22 Dec 2009 13:19:35 +0100
  54.  
  55.             // prectu hlavicky zprav
  56.             $overview = imap_fetch_overview($this->connection, $msgno.':'.$msgno, 0);
  57.  
  58.             // a projdu vsechny zpravy
  59.             foreach( $overview AS $i => $message ){
  60.                 //echo "message: "; debug::dump($message);
  61.  
  62.                 $struct = imap_fetchstructure($this->connection, $message->msgno);
  63. //              echo "struct: "; debug::dump($struct);
  64.                 //echo "parts: "; debug::dump($struct->parts);
  65.  
  66.                 $subjArray = explode(" ", $message->subject);
  67.  
  68. //              echo "subjArray: "; debug::dump($subjArray);
  69.                 //debug::dump("Pocet priloh ve zprave ".$message->msgno." je: ".(count($struct->parts)-1));
  70.  
  71. //              $message = imap_fetchbody($this->connection, $message->msgno, 1);
  72. //              switch( $struct->parts[0]->type ){
  73. //                  case 0: //7BIT
  74. //                      $message = imap_utf7_decode($message);
  75. //                      break;
  76. //                  case 1: //8BIT
  77. //                      $message = imap_8bit($message);
  78. //                      break;
  79. //                  case 2: //BINARY
  80. //                      $message = ($message);
  81. //                      break;
  82. //                  case 3: //BASE64
  83. //                      $message = base64_decode($message);
  84. //                      break;
  85. //                  case 4: //QUOTED-PRINTABLE
  86. //                      $message = quoted_printable_decode($message);
  87. //                      break;
  88. //                  case 5: //OTHER
  89. //              }
  90.  
  91.                 //Pokud obsahuje prilohu...
  92.                 if( count($struct->parts) >= 2 ){
  93.                     // nactu druhou cast zpravy (prvni priloha)
  94.                     $fileContent = imap_fetchbody($this->connection, $message->msgno, 2);
  95.                     //echo "fileContent"; debug::dump($fileContent);
  96.  
  97.                     // a provedu parserovani
  98.                     $decoded = imap_base64($fileContent);
  99.                     //echo "decoded"; debug::dump($decoded);
  100.  
  101.                     $time = strtotime($message->date);
  102.                     $report = Environment::expand("%appDir%/temp/reports").'/'.$saveAStime.'.'.date('Y-m-d', $saveAStime).'.'.rand(1000,9999);
  103.                     $report_zip = $report.".zip";
  104.                     $report_xml = $report.".xml";
  105.  
  106.                     if( !@file_put_contents("safe://".$report_zip, $decoded) ){
  107.                         throw new IOException("Writting error for file {$report_zip}");
  108.                     }
  109.  
  110.                     $zip = new PclZip("safe://".$report_zip);
  111.                     if ($zip->extract(PCLZIP_OPT_PATH, dirname($report)) == 0) {
  112.                         if( !is_file($report_zip) ){
  113.                             throw new FileNotFoundException("File {$report_zip} doesn't exists!");
  114.                         }
  115.  
  116.                         throw new IOException("Error: wasn't able to open archive {$report_zip}");
  117.                     }
  118.  
  119.                     $extracted = dirname($report_zip).'/report.xml';
  120.                     if( !@copy($extracted, "safe://".$report_xml) ){
  121.                         if( !is_file($extracted) ){
  122.                             throw new FileNotFoundException("File {$extracted} doesn't exists!");
  123.                         }
  124.  
  125.                         throw new IOException("Error: wasn't able to copy '{$extracted}' to '{$report_xml}'");
  126.                     }
  127.  
  128.                     if( !@unlink("safe://".$extracted) OR !@unlink("safe://".$report_zip) ){
  129.                         throw new IOException("Error: wasn't able to clean up");
  130.                     }
  131.  
  132.                     $xmls[$saveAStime][] = $report_xml;
  133.                 }
  134.  
  135.                 //echo "<hr>";
  136.             }
  137.         }
  138.  
  139.         return $xmls;
  140.     }
  141.  
  142.  
  143.     public function __destruct()
  144.     {
  145.             // ukoncim spojeni
  146.             $ukonci = @imap_close($this->connection);
  147.             if( !$ukonci ){
  148.                 //debug::dump(imap_errors());
  149.                 throw new GmailImapException("Spojení se nepodařilo ukončit.");
  150.             }
  151.     }
  152.  
  153.  
  154.  
  155.     /**
  156.      * Return array of IMAP messages for pagination
  157.      *
  158.      * @param   int     $page       page number to get
  159.      * @param   int     $per_page   number of results per page
  160.      * @param   array   $sort       array('subject', 'asc') etc
  161.      *
  162.      * @return  mixed   array containing imap_fetch_overview, pages, and total rows if successful, false if an error occurred
  163.      * @author  Raja K
  164.      */
  165.     public function listMessages($page = 1, $per_page = 25, $sort = null) {
  166.         $limit = ($per_page * $page);
  167.         $start = ($limit - $per_page) + 1;
  168.         $start = ($start < 1) ? 1 : $start;
  169.         $limit = (($limit - $start) != ($per_page-1)) ? ($start + ($per_page-1)) : $limit;
  170.         $info = imap_check($this->_imap_stream);
  171.         $limit = ($info->Nmsgs < $limit) ? $info->Nmsgs : $limit;
  172.  
  173.         if(true === is_array($sort)) {
  174.             $sorting = array(
  175.                         'direction' => array(   'asc' => 0,
  176.                                                 'desc' => 1),
  177.  
  178.                         'by'        => array(   'date' => SORTDATE,
  179.                                                 'arrival' => SORTARRIVAL,
  180.                                                 'from' => SORTFROM,
  181.                                                 'subject' => SORTSUBJECT,
  182.                                                 'size' => SORTSIZE));
  183.             $by = (true === is_int($by = $sorting['by'][$sort[0]]))
  184.                             ? $by
  185.                             : $sorting['by']['date'];
  186.             $direction = (true === is_int($direction = $sorting['direction'][$sort[1]]))
  187.                             ? $direction
  188.                             : $sorting['direction']['desc'];
  189.  
  190.             $sorted = imap_sort($this->_imap_stream, $by, $direction);
  191.  
  192.             $msgs = array_chunk($sorted, $per_page);
  193.             $msgs = $msgs[$page-1];
  194.         }
  195.         else
  196.             $msgs = range($start, $limit); //just to keep it consistent
  197.  
  198.         $result = imap_fetch_overview($this->_imap_stream, implode($msgs, ','), 0);
  199.         if(false === is_array($result)) return false;
  200.  
  201.         //sorting!
  202.         if(true === is_array($sorted)) {
  203.             $tmp_result = array();
  204.             foreach($result as $r)
  205.                 $tmp_result[$r->msgno] = $r;
  206.  
  207.             $result = array();
  208.             foreach($msgs as $msgno) {
  209.                 $result[] = $tmp_result[$msgno];
  210.             }
  211.         }
  212.  
  213.         $return = array('res' => $result,
  214.                         'start' => $start,
  215.                         'limit' => $limit,
  216.                         'sorting' => array('by' => $sort[0], 'direction' => $sort[1]),
  217.                         'total' => imap_num_msg($this->_imap_stream));
  218.         $return['pages'] = ceil($return['total'] / $per_page);
  219.         return $return;
  220.     }
  221.  
  222. }
  223.  
  224.  
  225.  
  226. class GmailImapException extends Exception { }
Advertisement
Add Comment
Please, Sign In to add comment