<?php
/*
This file is part of Thomas Bley's moregroupware webmail2/calendar2/admin2 module. (tb-mgw)

More information:
-----------------

Simple Groupware Solutions Thomas Bley
Fichtenstr. 23
Germany, 85640 Putzbrunn

Contact:
--------

info@simple-groupware.de

http://www.simple-groupware.de


Copyright 2002-2003 Thomas Bley
tb-mgw is distributed under the terms of the GNU General Public License 

tb-mgw is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

tb-mgw is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with tb-mgw; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

// Imap_Tree
// Moregroupware.org

require_once(WM2_INC_DIR.'imap/imap.php');
require_once(INCLUDEPATH . "crypt.inc.php");

error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

function get_imap_tree($row) {

  global $MGW,$username,$delimiter,$fields,$imap_conn_error,$force_imap_reload,$imap_list_all;
  
  $account = $row["id"];
  $accountname = $row["mailboxname"];
  $cacher = "";
  $folders = array();
  $cache_version = "0.1";
  $cache_version_now = "0";
  $cache_file = CACHE_FOLDER."imap/tree/".$account.".php";

  if (!$force_imap_reload and file_exists($cache_file) and (filemtime($cache_file)+3600) > time()) {
    include $cache_file;
  }

  if ($cache_version != $cache_version_now) {
    $myC = new Crypto();
    $password = $myC->decrypt($username, $row["password"]);
  
    if ($row["enable_ssl"]=="checked") {
      $default_port = "993";
    } else {
      $default_port = "143";
	}

    $default_protocol = "imap";

    $email = my_imap_connect("int",$default_port,$default_protocol,$row,$password,"INBOX");
    $imap_conn = $email;

    if (!isset($imap_conn_error) or $imap_conn_error=="") {

      $delimiter = sqimap_get_delimiter($email);

	  if (isset($row["imap_list_all"]) and $row["imap_list_all"]=="checked") {
	    $imap_list_all = true;
	  } else {
	    $imap_list_all = false;
	  }
	  
      $result = sqimap_mailbox_list($email);
  
      $folders = array();
      $indexer = array();

      $special_folders = array("inbox","drafts","sent","trash","spam");

      if (is_array($result) and count($result) != 0) {
        foreach ($result as $folder) {
          if (is_array($folder) and count($folder) != 0 and is_numeric($folder["id"]) and $folder["formatted"] != "") {
            $folder["id"]++;
            $protect = "false";
        
            $parentname = "";
            if ($folder["unformatted"] != $folder["formatted"]) {
              $parentname = substr($folder["unformatted"],0,strrpos($folder["unformatted"],$delimiter));
              if (isset($indexer[$parentname])) { $parent = $indexer[$parentname]; } else {
			    $parent = 0;

				$pos = strrpos($parentname,$delimiter);
                $parentname2 = substr($parentname,$pos+1);
                $parentname = substr($parentname,0,$pos);

                if (isset($indexer[$parentname])) {
				  $folder["formatted"] = $parentname2."/".$folder["formatted"];
				  $parent = $indexer[$parentname];
				}

			  }
            } else {
              $parent = 0;
            }
        
			$folder["formatted"] = imap_utf7_decode_local($folder["formatted"]);
            if ((strtolower($parentname) == "inbox" and in_array(strtolower($folder["formatted"]),$special_folders)) or in_array(strtolower($folder["unformatted"]),$special_folders)) {
              $folder["formatted"] = mboxname_replace_imap($folder["formatted"]);
              $protect = "true";
            }

            if (strpos("@".strtolower($folder["unformatted"]),"trash")==1 or strpos("@".strtolower($folder["unformatted"]),"inbox".$delimiter."trash")==1) {
              $isintrash = 1;
            } else {
              $isintrash = 0;
            }

            /*
            if (strtolower($folder["unformatted"])=="inbox") {
              $isinbox = 1;
            } else {
              $isinbox = 0;
            }
            */
            $isinbox = 0;
          
            $thiscount = 0;
            if (isset($row["imap_show_numbers"]) and $row["imap_show_numbers"]=="checked") $thiscount = sqimap_get_num_messages($email, $folder["unformatted-disp"]);
            if ($thiscount != 0) {
              $thiscount_unread = sqimap_unseen_messages($email, $folder["unformatted-disp"]);
            } else {
              $thiscount_unread = 0;
            }
            $folders[$folder["id"]] = array($parent,$folder["id"],$folder["formatted"],$protect,$thiscount,$thiscount_unread,$isinbox,$folder["unformatted-disp"],$isintrash);
            $indexer[$folder["unformatted"]] = $folder["id"];
          }
        }  
      }
	  
      my_imap_close($email,$imap_conn,"int");
  
      $fp = fopen($cache_file, "w");
	  fwrite($fp,"<?php\n\$cache_version_now=\"".$cache_version."\";\n");
  	  if (count($folders)!=0) {
	    fwrite($fp,"\$folders=".draw_array($folders,true));
	  } else {
	    fwrite($fp,"\$folders=array();\n");
  	  }
	  fwrite($fp,"?>\n");
      fclose($fp);
    
    } else {
      $fields[] = 'field_'.$row["id"].'_0 = insFld(foldersTree, gFld("'.$accountname.': '.$imap_conn_error.'", '.$row["id"].', 0,true,false,false,"#",0,0,0,0))';
    }
  }
  
  if (count($folders)!=0) {

    $folders2 = array();

    foreach ($folders as $key=>$key2) {
      if ($key2[3]) {
        $folders2[$key2[1]] = $key2;
      }
    }
    foreach ($folders as $key=>$key2) {
      if (!$key2[3]) {
        $folders2[$key2[1]] = $key2;
      }
    }
    
    $fields[] = 'field_'.$row["id"].'_0 = insFld(foldersTree, gFld("'.$accountname.'", '.$row["id"].', 0,true,false,false,"#",0,0,1,0))';

    foreach ($folders2 as $key=>$key2) {
      if (isset($folders2[$key2[0]]) or $key2[0] == 0) {
        
        if ($key2[0] == 0) {$father = 'field_'.$row["id"].'_0'; } else {$father = "field_".$row["id"]."_".$key2[0];}
        $fields[] = 'field_'.$row["id"].'_'.$key.' = insFld('.$father.', gFld("'.addslashes($key2[2]).'", '.$row["id"].', '.$key.','.$key2[3].','.$key2[8].',false,"#",'.$key2[4].','.$key2[5].','.$key2[6].',0))';

        $images = array("inbox","drafts","sent","trash");
        foreach ($images as $image) {
          if (str_replace("inbox.","",strtolower($key2[7])) == $image) {
            $fields[] = 'field_'.$row["id"].'_'.$key.'.iconSrc = ICONPATH + "'.$image.'folderclosed.gif";';
            $fields[] = 'field_'.$row["id"].'_'.$key.'.iconSrcClosed = ICONPATH + "'.$image.'folderclosed.gif"';
          }
        }

      }
    }
  }    

  return $fields;
}
?>