<?php

	class EcmEmailsDataFormatter {
		
		var $data;
		
		function EcmEmailsDataFormatter($data) {
			$this->data = $data;
		}
		
		function from_addrs() {
			return '';
		}
		
		function from() {
			if(isset($this->data['from'])) 
				return $this->formatAddr($this->data['from']);
			return '';
		}
		
		function formatAddr($addr) {
			if(is_array($addr)) {
				$str = '';
				foreach($addr as $key => $value) {
					if(is_array($value)) {
						$focus = $this->getBean($value[0], $value[1]);
						if($focus != null) {
							if($value[0] == "Accounts")
								$str .= $focus->name.' <'.$focus->email1.'>; ';
							else
							if($value[0] == "Contacts" || $value[0] == "Users" || $value[0] == "Employees" || $value[0] == "Leads")
								$str .= $focus->full_name.' <'.$focus->email1.'>; ';
						}
					} else {
						$str .= $value;
					}
				}
				return $str;
			}
			return '';
		}
		
		function to_addrs() {
			if(isset($this->data['to'])) {
				return $this->formatAddr($this->data['to']);
			}
			return '';
		}
		
		function to_addrs_ids() {
			return '';
		}
		
		function to_addrs_names() {
			return '';
		}
		
		function to_addrs_emails() {
			return '';
		}
		
		function cc_addrs() {
			if(isset($this->data['cc'])) {
				return $this->formatAddr($this->data['cc']);
			}
			return '';		
		}

		function cc_addrs_ids() {
			return '';
		}
		
		function cc_addrs_names() {
			return '';
		}
		
		function cc_addrs_emails() {
			return '';
		}

		function bcc_addrs() {
			if(isset($this->data['bcc'])) {
				return $this->parseEmails($this->data['bcc']);
			}
			return '';		
		}

		function bcc_addrs_ids() {
			return '';
		}
		
		function bcc_addrs_names() {
			return '';
		}
		
		function bcc_addrs_emails() {
			return '';
		}
				
		function subject() {
			if(isset($this->data['subject'])) {
				return $this->data['subject'];
			}
			return '';
		}
		
		function parseEmails($e, $glue_before = "<", $glue_after =">; ", $el = 0) {
			$str = '';
			for($i = 0; $i < count($e); $i ++) {
				if(!is_array($e[$i])) {
					$str .= $glue_before.$e[$i].$glue_after;
				} else {
					$str .= $glue_before.$e[$i][$el].$glue_after;
				}
			}
			return $str;
		}
		
		function parseEmail($e) {
			return '';
		}
		
		function descriptionHTML() {
			if(isset($this->data['body_html'])) {
				return $this->data['body_html'];
			}
			return '';
		}
		
		function description() {
			if(isset($this->data['body'])) {
				return $this->data['body'];
			}
			return '';
		}
		
		function parentType() {
			if(isset($this->data['parent']) && isset($this->data['parent']['type'])) {
				return $this->data['parent']['type'];
			}
			return '';
		}
		
		function saveEmailRelationToAssignedIds($email_id) {
		   if(isset($this->data['assigned_ids'])) {		  
		      foreach($this->data['assigned_ids'] as $key => $value) {
			  	 if($key != "EcmDocumentTemplates" && $key != "Users") {
				 	$focus = $this->getBean($key, $value);
					$focus->load_relationship("emails");
					if(isset($focus->emails)) {
						$focus->emails->add($email_id);
					}
				 }
			  }
		   }
		}
		
		function assignedUserId() {
			if(isset($this->data['assigned_user']) && isset($this->data['assigned_user']['id'])) {
				return $this->data['assigned_user']['id'];
			}
			global $current_user;
			return $current_user->id;
		}
		
		function assignedUserName() {
			if(isset($this->data['assigned_user']) && isset($this->data['assigned_user']['name'])) {
				return $this->data['assigned_user']['name'];
			}
			global $current_user;
			return $current_user->user_name;
		}
		
		function templateId() {
			if(isset($this->data['template_id'])) {
				return $this->data['template_id'];
			}
			return '';
		}
		
		function loadMFP($fill_focus = true) {
		   if(isset($this->data['assigned_ids'])) {		  
			  require_once('modules/EcmDocumentTemplates/ModuleFieldsParser/ModuleFieldsParser.php');
			  $mfp = new ModuleFieldsParser();
			  $mfp->clear();
			  
			  global $app_list_strings;
			  global $beanList;			
			
			  foreach($this->data['assigned_ids'] as $key => $value) {
			  	  if($key == "Users" && (!isset($value) || $value == '')) $value = $this->assignedUserId();
			  	  $focus = $fill_focus ? $this->getBean($key, $value) : null;
			  	  $mfp->add($key, str_replace("ecm", "", strtolower($beanList[$key])).'_', $focus, $app_list_strings['moduleList'][$key]);
			  }
			  return $mfp;
		   }
		   return null;
		}
		
		function getBean($module, $id) {
			global $beanList, $beanFiles;
			$file = $beanFiles[$beanList[$module]];
			if(file_exists($file)) {
				require_once($file);
				$focus = new $beanList[$module]();
				$focus->retrieve($id);
				$focus->format_all_fields();
				return $focus;
			}			
			return null;
		}
		
		function loadParserArray($name = '') {
		   if(isset($this->data['assigned_ids'])) {		  
			  $mfp = $this->loadMFP(false);
			  $mfp_arr = $mfp->getFormHTML(false,$name);
			  return $mfp_arr;
		  
		  }
		  return '';
		}
		
		function getModuleName($module) {
			global $app_list_strings;
			return $app_list_strings['moduleList'][$module];
		}
		
		function beanName($module, $id) {
			if($module == "Users") return $this->assignedUserName();
			$focus = $this->getBean($module, $id);
			if($focus != null)
				return $focus->get_summary_text();
			return '';
		}
		
		function extraAssigned() {
			if(isset($this->data) && is_array($this->data['assigned_ids'])) {
				$ea = '';
				foreach($this->data['assigned_ids'] as $key => $value) { 
					if($key == "Users" && (!isset($value) || $value == '')) {
						$value = $this->assignedUserId();
					}
 					if(isset($value) && $value != '')
						$ea .= $this->getModuleName($key).',&nbsp;&nbsp;'.$this->beanName($key, $value).
							'
							 <input type="hidden" name="assigned_ids[]" value="'.$key.":|:".$value.'" />
							 <br />
							 ';
				}
				return $ea;
			}
			return '';
		}
		
		function getAttachments() {
			$arr = array();
			if(isset($this->data['attachments']['links']) && is_array($this->data['attachments']['links']))
				$arr = array_merge($arr, $this->data['attachments']['links']);
			if(isset($this->data['attachments']['sugar']) && is_array($this->data['attachments']['sugar'])) {
				$tmp = array();
				foreach($this->data['attachments']['sugar'] as $att) {
					$link = "index.php?module=".$att[1]."&action=".$att[2];
					$att[3] = array_merge($att[3], $att[4]);
					if(is_array($att[3])) {
						foreach($att[3] as $key => $value) {
							$link .= "&".$key."=".$value;
						}
					}
					$tmp[] = array($att[0], $link);
				}
				$arr = array_merge($arr, $tmp);
			}
			
			foreach($arr as $key => $value) 
				$arr[$key]['md5'] = md5($value[0].$value[1]);
				
			return $arr;
		}
		
		function getAttachmentsNotes($ids, $parent_name, $parent_module, $parent_id) {
			$notes = array();
			
			if(isset($this->data['attachments']['links']) && is_array($this->data['attachments']['links']))
				foreach($this->data['attachments']['links'] as $att) 
					if(in_array(md5($att[0].$att[1]), $ids))
						$notes[] = $this->createNoteFromLink($att[0], $att[2], $att[1], $parent_name, $parent_module, $parent_id);
					


			if(isset($this->data['attachments']['sugar']) && is_array($this->data['attachments']['sugar'])) {
				foreach($this->data['attachments']['sugar'] as $att) {

					$link = "index.php?module=".$att[1]."&action=".$att[2];
					$attt = array_merge($att[3], $att[4]);
					if(is_array($attt)) {
						foreach($attt as $key => $value) {
							$link .= "&".$key."=".$value;
						}
					}
					if(in_array(md5($att[0].$link), $ids)) {
						$tmp = array('module' => $att[1], 'action' => $att[2]);
						if(is_array($att[3]))
							$tmp = array_merge($tmp, $att[3]);
						$notes[] = $this->createNoteFromSugarFile($att[0], $att[5], $tmp, $parent_name, $parent_module, $parent_id);
					} 
				}
			}
			
			return $notes;
		}

		function createNoteFromSugarFile($name, $mime_type, $data, $parent_name, $parent_module, $parent_id) {
			require_once('modules/Notes/Note.php');
			$n = new Note();
			$n->name = translate('LBL_EMAIL_ATTACHMENT', "Emails").': '.$name;
			$n->filename = $name;
			$n->file_mime_type = $mime_type;
			$n->parent_id = $parent_id;
			$n->parent_type = $parent_module;
			$n->parent_name = $parent_name;
			$nid = $n->save();	
			
			$post = $_POST;
			$get = $_GET;
			$request = $_REQUEST;
			
			$_GET = array_merge($_GET, $data);
			$_REQUEST = array_merge($_REQUEST, $data);
			$_POST = array();
			
			ob_start();
				
				include("modules/".$data['module']."/".$data['action'].".php");
		
			$file_data = ob_get_contents();
			ob_end_clean();
			
			global $sugar_config;
			$f=fopen($sugar_config['upload_dir'].$nid,'wb');
			if($f) {
				fwrite($f,$file_data,strlen($file_data));
			}
			fclose($f);
			
			$_POST = $post;
			$_GET = $get;
			$_REQUEST = $request;		
			
			return $n;				
		}	
			
		function createNoteFromLink($name, $mime_type, $link, $parent_name, $parent_module, $parent_id) {
			require_once('modules/Notes/Note.php');
			$n = new Note();
			$n->name = translate('LBL_EMAIL_ATTACHMENT', "Emails").': '.$name;
			$n->filename = $name;
			$n->file_mime_type = $mime_type;
			$n->parent_id = $parent_id;
			$n->parent_type = $parent_module;
			$n->parent_name = $parent_name;

			$nid = $n->save();	
			global $sugar_config;
			if(!copy($link, $sugar_config['upload_dir'].$nid)) {
				//$errors= error_get_last(); echo "COPY ERROR: ".$errors['type']; echo "<br />\n".$errors['message'];
			}

			return $n;
		}
	}

?>