1<?php
2/*
3	FusionPBX
4	Version: MPL 1.1
5
6	The contents of this file are subject to the Mozilla Public License Version
7	1.1 (the "License"); you may not use this file except in compliance with
8	the License. You may obtain a copy of the License at
9	http://www.mozilla.org/MPL/
10
11	Software distributed under the License is distributed on an "AS IS" basis,
12	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13	for the specific language governing rights and limitations under the
14	License.
15
16	The Original Code is FusionPBX
17
18	The Initial Developer of the Original Code is
19	Mark J Crane <markjcrane@fusionpbx.com>
20	Portions created by the Initial Developer are Copyright (C) 2008-2018
21	the Initial Developer. All Rights Reserved.
22
23	Contributor(s):
24	Mark J Crane <markjcrane@fusionpbx.com>
25	James Rose <james.o.rose@gmail.com>
26*/
27
28$output_type = "file"; //file or console
29
30if (defined('STDIN')) {
31	//get the document root php file must be executed with the full path
32		$document_root = str_replace("\\", "/", $_SERVER["PHP_SELF"]);
33		$document_root = str_replace("\\", "/", $_SERVER["PHP_SELF"]);
34		preg_match("/^(.*)\/secure\/.*$/", $document_root, $matches);
35		$document_root = $matches[1];
36	//set the include path
37		set_include_path($document_root);
38		$_SERVER["DOCUMENT_ROOT"] = $document_root;
39		//echo "$document_root is document_root\n";
40}
41
42if (stristr(PHP_OS, 'WIN')) { $IS_WINDOWS = true; } else { $IS_WINDOWS = false; }
43
44if (!function_exists('exec_in_dir')) {
45	function exec_in_dir($dir, $cmd, &$ok){
46		$args = func_get_args();
47		$cwd = getcwd();
48		chdir($dir);
49		$output = array();
50		$ret = 0;
51		$result = exec($cmd, $output, $ret);
52		if ($cwd)
53			chdir($cwd);
54		$ok = ($ret == 0);
55		return join($output, "\n");
56	}
57}
58
59if (!function_exists('correct_path')) {
60	function correct_path($p) {
61		global $IS_WINDOWS;
62		if ($IS_WINDOWS) {
63			return str_replace('/', '\\', $p);
64		}
65		return $p;
66	}
67}
68
69if (!function_exists('path_join')) {
70	function path_join() {
71		$args = func_get_args();
72		$paths = array();
73		foreach ($args as $arg) {
74			$paths = array_merge($paths, (array)$arg);
75		}
76
77		$prefix = null;
78		foreach($paths as &$path) {
79			if ($prefix === null && strlen($path) > 0) {
80				if (substr($path, 0, 1) == '/') $prefix = '/';
81				else $prefix = '';
82			}
83			$path = trim( $path, '/' );
84		}
85
86		if ($prefix === null){
87			return '';
88		}
89
90		$paths = array_filter($paths);
91		return $prefix . join('/', $paths);
92	}
93}
94
95if (!function_exists('tiff2pdf')) {
96	function tiff2pdf($tiff_file_name){
97		//convert the tif to a pdf
98		//Ubuntu: apt-get install libtiff-tools
99
100		global $IS_WINDOWS;
101
102		if (!file_exists($tiff_file_name)){
103			echo "tiff file does not exists";
104			return false; // "tiff file does not exists";
105		}
106
107		$GS = $IS_WINDOWS ? 'gswin32c' : 'gs';
108		$tiff_file = pathinfo($tiff_file_name);
109		$dir_fax = $tiff_file['dirname'];
110		$fax_file_name = $tiff_file['filename'];
111		$pdf_file_name = path_join( $dir_fax, $fax_file_name . '.pdf' );
112
113		if (file_exists($pdf_file_name))
114			return $pdf_file_name;
115
116		$dir_fax_temp = $_SESSION['server']['temp']['dir'];
117		if (!$dir_fax_temp){
118			$dir_fax_temp = path_join(dirname($dir_fax), 'temp');
119		}
120
121		if (!file_exists($dir_fax_temp)){
122			echo"can not create temporary directory";
123			return false; //
124		}
125
126		$cmd  = "tiffinfo " . correct_path($tiff_file_name) . ' | grep "Resolution:"';
127		$ok   = false;
128		$resp = exec_in_dir($dir_fax, $cmd, $ok);
129		if (!$ok){
130			echo"can not find fax resoulution";
131			return false; // "can not find fax resoulution"
132		}
133
134		$ppi_w = 0;
135		$ppi_h = 0;
136		$tmp = array();
137		if (preg_match('/Resolution.*?(\d+).*?(\d+)/', $resp, $tmp)){
138			$ppi_w = $tmp[1];
139			$ppi_h = $tmp[2];
140		}
141
142		$cmd = "tiffinfo " . $tiff_file_name . ' | grep "Image Width:"';
143		$resp = exec_in_dir($dir_fax, $cmd, $ok);
144		if (!$ok){
145			echo"can not find fax size";
146			return false; // "can not find fax size"
147		}
148
149		$pix_w = 0;
150		$pix_h = 0;
151		$tmp = array();
152		if (preg_match('/Width.*?(\d+).*?Length.*?(\d+)/', $resp, $tmp)){
153			$pix_w = $tmp[1];
154			$pix_h = $tmp[2];
155		}
156
157		$page_width  = $pix_w / $ppi_w;
158		$page_height = $pix_h / $ppi_h;
159		$page_size   = 'a4';
160
161		if (($page_width > 8.4) && ($page_height > 13)) {
162			$page_width  = 8.5;
163			$page_height = 14;
164			$page_size   = 'legal';
165		}
166		elseif (($page_width > 8.4) && ($page_height < 12)) {
167			$page_width  = 8.5;
168			$page_height = 11;
169			$page_size   = 'letter';
170		}
171		elseif (($page_width < 8.4) && ($page_height > 11)) {
172			$page_width  = 8.3;
173			$page_height = 11.7;
174			$page_size   = 'a4';
175		}
176		$page_width  = sprintf('%.4f', $page_width);
177		$page_height = sprintf('%.4f', $page_height);
178
179		$cmd = join(array('tiff2pdf',
180			'-o', correct_path($pdf_file_name),
181			correct_path($tiff_file_name),
182		), ' ');
183
184		$resp = exec_in_dir($dir_fax, $cmd, $ok);
185
186		if (!file_exists($pdf_file_name)){
187			echo "can not create pdf: $resp";
188			return false;
189		}
190
191		return $pdf_file_name;
192	}
193}
194
195if (!function_exists('fax_enqueue')) {
196	function fax_enqueue($fax_uuid, $fax_file, $wav_file, $reply_address, $fax_uri, $fax_dtmf, $dial_string){
197		global $db, $db_type;
198
199		$fax_task_uuid = uuid();
200		$dial_string .= "fax_task_uuid='" . $fax_task_uuid . "',";
201		$description = ''; //! @todo add description
202		if ($db_type == "pgsql") {
203			$date_utc_now_sql  = "NOW() at time zone 'utc'";
204		}
205		if ($db_type == "mysql") {
206			$date_utc_now_sql  = "UTC_TIMESTAMP()";
207		}
208		if ($db_type == "sqlite") {
209			$date_utc_now_sql  = "datetime('now')";
210		}
211
212		$sql = "INSERT INTO v_fax_tasks (fax_task_uuid, fax_uuid, ";
213		$sql .= "	task_next_time, task_lock_time, ";
214		$sql .= "	task_fax_file, task_wav_file, task_uri, task_dial_string, task_dtmf, ";
215		$sql .= "	task_interrupted, task_status, task_no_answer_counter, task_no_answer_retry_counter, task_retry_counter, ";
216		$sql .= "	task_reply_address, task_description) ";
217		$sql .= "VALUES ( ";
218		$sql .= " :fax_task_uuid, :fax_uuid, ";
219		$sql .= " ".$date_utc_now_sql.", NULL, ";
220		$sql .= "	:fax_file, :wav_file, :fax_uri, :dial_string, :fax_dtmf, ";
221		$sql .= " 'false', 0, 0, 0, 0, ";
222		$sql .= " :reply_address, :description, ";
223		$sql .= "); ";
224		$statement = $db->prepare($sql);
225		$statement->bindParam(':fax_task_uuid', $fax_task_uuid);
226		$statement->bindParam(':fax_uuid', $fax_uuid);
227		$statement->bindParam(':fax_file', $fax_file);
228		$statement->bindParam(':wav_file', $wav_file);
229		$statement->bindParam(':fax_uri', $fax_uri);
230		$statement->bindParam(':dial_string', $dial_string);
231		$statement->bindParam(':fax_dtmf', $fax_dtmf);
232		$statement->bindParam(':reply_address', $reply_address);
233		$statement->bindParam(':description', $description);
234		if ($statement->execute()) {
235			$response = 'Success';
236		}
237		else{
238			//! @todo log error
239			$response = 'Failed';
240			var_dump($db->errorInfo());
241		}
242		unset($statement);
243		return $response;
244	}
245}
246
247if (!function_exists('fax_split_dtmf')) {
248	function fax_split_dtmf(&$fax_number, &$fax_dtmf){
249		$tmp = array();
250		$fax_dtmf = '';
251		if (preg_match('/^\s*(.*?)\s*\((.*)\)\s*$/', $fax_number, $tmp)){
252			$fax_number = $tmp[1];
253			$fax_dtmf = $tmp[2];
254		}
255	}
256}
257
258//includes
259	if (!defined('STDIN')) { include "root.php"; }
260	require_once "resources/require.php";
261	include "resources/classes/event_socket.php";
262	include "resources/phpmailer/class.phpmailer.php";
263	include "resources/phpmailer/class.smtp.php"; // optional, gets called from within class.phpmailer.php if not already loaded
264
265//set php ini values
266	ini_set(max_execution_time,900); //15 minutes
267	ini_set('memory_limit', '96M');
268
269//start the to cache the output
270	if ($output_type == "file") {
271		ob_end_clean();
272		ob_start();
273	}
274
275//add a delimeter to the log
276	echo "\n---------------------------------\n";
277
278//get the parameters and save them as variables
279	$php_version = substr(phpversion(), 0, 1);
280	if ($php_version == '4') {
281		$domain_name = $_REQUEST["domain"];
282		$fax_email = $_REQUEST["email"];
283		$fax_extension = $_REQUEST["extension"];
284		$fax_file = $_REQUEST["name"];
285		$fax_messages = $_REQUEST["messages"];
286		$caller_id_name = $_REQUEST["caller_id_name"];
287		$caller_id_number = $_REQUEST["caller_id_number"];
288		$fax_relay = $_REQUEST["retry"];
289		$mailfrom_address = $_REQUEST["mailfrom_address"];
290	}
291	else {
292		$tmp_array = explode("=", $_SERVER["argv"][1]);
293		$fax_email = $tmp_array[1];
294		unset($tmp_array);
295
296		$tmp_array = explode("=", $_SERVER["argv"][2]);
297		$fax_extension = $tmp_array[1];
298		unset($tmp_array);
299
300		$tmp_array = explode("=", $_SERVER["argv"][3]);
301		$fax_file = $tmp_array[1];
302		unset($tmp_array);
303
304		$tmp_array = explode("=", $_SERVER["argv"][4]);
305		$fax_messages = $tmp_array[1];
306		unset($tmp_array);
307
308		$tmp_array = explode("=", $_SERVER["argv"][5]);
309		$domain_name = $tmp_array[1];
310		unset($tmp_array);
311
312		$tmp_array = explode("=", $_SERVER["argv"][6]);
313		$caller_id_name = $tmp_array[1];
314		unset($tmp_array);
315
316		$tmp_array = explode("=", $_SERVER["argv"][7]);
317		$caller_id_number = $tmp_array[1];
318		unset($tmp_array);
319
320		$tmp_array = explode("=", $_SERVER["argv"][8]);
321		$fax_relay = $tmp_array[1];
322		unset($tmp_array);
323
324		$tmp_array = explode("=", $_SERVER["argv"][9]);
325		$fax_prefix = $tmp_array[1];
326		unset($tmp_array);
327
328		$tmp_array = explode("=", $_SERVER["argv"][10]);
329		$mailfrom_address = $tmp_array[1];
330		unset($tmp_array);
331
332		//$tmp_array = explode("=", $_SERVER["argv"][10]);
333		//$destination_number = $tmp_array[1];
334		//unset($tmp_array);
335	}
336	$mailto_address = $fax_email;
337
338//get the fax file name (only) if a full path
339	$fax_path      = pathinfo($fax_file);
340	$fax_file_only = $fax_path['basename'];
341	$fax_file_name = $fax_path['filename'];
342	$dir_fax       = $fax_path['dirname'];
343
344//get the domain_uuid from the database
345	$sql = "select * from v_domains ";
346	$sql .= "where domain_name = '".$domain_name."' ";
347	$prep_statement = $db->prepare($sql);
348	$prep_statement->execute();
349	$result = $prep_statement->fetchAll(PDO::FETCH_ASSOC);
350	foreach ($result as &$row) {
351		//set the domain variables
352			$domain_uuid = $row["domain_uuid"];
353			$_SESSION["domain_uuid"] = $row["domain_uuid"];
354			$_SESSION["domain_name"] = $domain_name;
355		//set the setting arrays
356			$domain = new domains();
357			$domain->db = $db;
358			$domain->set();
359	}
360	unset ($prep_statement);
361
362//prepare smtp server settings
363	// load default smtp settings
364	$smtp['method']   = $_SESSION['email']['smtp_method']['text'];
365	$smtp['host']     = (strlen($_SESSION['email']['smtp_host']['text'])?$_SESSION['email']['smtp_host']['text']:'127.0.0.1');
366	if (isset($_SESSION['email']['smtp_port'])) {
367		$smtp['port'] = (int)$_SESSION['email']['smtp_port']['numeric'];
368	} else {
369		$smtp['port'] = 0;
370	}
371
372	$smtp['secure']   = $_SESSION['email']['smtp_secure']['text'];
373	$smtp['auth']     = $_SESSION['email']['smtp_auth']['text'];
374	$smtp['username'] = $_SESSION['email']['smtp_username']['text'];
375	$smtp['password'] = $_SESSION['email']['smtp_password']['text'];
376	$smtp['from'] = $_SESSION['email']['smtp_from']['text'];
377	$smtp['from_name'] = $_SESSION['email']['smtp_from_name']['text'];
378
379	if (isset($_SESSION['fax']['smtp_from']) && strlen($_SESSION['fax']['smtp_from']['text']) > 0) {
380		$smtp['from'] = $_SESSION['fax']['smtp_from']['text'];
381	}
382	if (isset($_SESSION['fax']['smtp_from_name']) && strlen($_SESSION['fax']['smtp_from_name']['text']) > 0) {
383		$smtp['from_name'] = $_SESSION['fax']['smtp_from_name']['text'];
384	}
385
386	// overwrite with domain-specific smtp server settings, if any
387	if ($domain_uuid != '') {
388		$sql = "select domain_setting_subcategory, domain_setting_value ";
389		$sql .= "from v_domain_settings ";
390		$sql .= "where domain_uuid = '".$domain_uuid."' ";
391		$sql .= "and (domain_setting_category = 'email' ";
392		$sql .= "or domain_setting_category = 'fax') ";
393		$sql .= "and domain_setting_name = 'text' ";
394		$sql .= "and domain_setting_enabled = 'true' ";
395		$prep_statement = $db->prepare($sql);
396		if ($prep_statement) {
397			$prep_statement->execute();
398			$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
399			foreach ($result as $row) {
400				if ($row['domain_setting_value'] != '') {
401					$smtp[str_replace('smtp_','',$row["domain_setting_subcategory"])] = $row['domain_setting_value'];
402				}
403			}
404		}
405		unset($sql, $prep_statement);
406	}
407
408	// value adjustments
409	$smtp['method'] 	= ($smtp['method'] == '') ? 'smtp' : $smtp['method'];
410	$smtp['auth'] 		= ($smtp['auth'] == "true") ? true : false;
411	$smtp['password'] 	= ($smtp['password'] != '') ? $smtp['password'] : null;
412	$smtp['secure'] 	= ($smtp['secure'] != "none") ? $smtp['secure'] : null;
413	$smtp['username'] 	= ($smtp['username'] != '') ? $smtp['username'] : null;
414
415//get the fax details from the database
416	$sql = "select * from v_fax ";
417	$sql .= "where domain_uuid = '".$_SESSION["domain_uuid"]."' ";
418	$sql .= "and fax_extension = '$fax_extension' ";
419	$prep_statement = $db->prepare($sql);
420	$prep_statement->execute();
421	$result = $prep_statement->fetchAll(PDO::FETCH_ASSOC);
422	foreach ($result as &$row) {
423		//set database fields as variables
424			//$fax_email = $row["fax_email"];
425			$fax_uuid = $row["fax_uuid"];
426			$fax_accountcode = $row["fax_accountcode"];
427			$fax_prefix = $row["fax_prefix"];
428			$fax_pin_number = $row["fax_pin_number"];
429			$fax_caller_id_name = $row["fax_caller_id_name"];
430			$fax_caller_id_number = $row["fax_caller_id_number"];
431			$fax_forward_number = $row["fax_forward_number"];
432			$fax_description = $row["fax_description"];
433			$fax_email_inbound_subject_tag = $row['fax_email_inbound_subject_tag'];
434	}
435	unset ($prep_statement);
436
437//set the fax directory
438	if (!file_exists($dir_fax) || !file_exists(path_join($dir_fax, $fax_file_only))) {
439		$dir_fax = $_SESSION['switch']['storage']['dir'].'/fax/'.$domain_name.'/'.$fax_extension.'/inbox';
440		if (!file_exists($dir_fax) || !file_exists(path_join($dir_fax, $fax_file_only))) {
441			$dir_fax = $_SESSION['switch']['storage']['dir'].'/fax/'.$fax_extension.'/inbox';
442		}
443	}
444	$fax_file = path_join($dir_fax, $fax_file_only);
445
446//used for debug
447	echo "fax_prefix: $fax_prefix\n";
448	echo "mailto_adress: $mailto_address\n";
449	echo "fax_email: $fax_email\n";
450	echo "fax_extension: $fax_extension\n";
451	echo "fax_name: $fax_file_only\n";
452	echo "dir_fax: $dir_fax\n";
453	echo "full_path: $fax_file\n";
454
455	$pdf_file = tiff2pdf($fax_file);
456	echo "file: $pdf_file \n";
457	if (!$pdf_file){
458		$fax_file_warning = 'warning: Fax image not available on server.';
459	}
460	else{
461		$fax_file_warning = '';
462	}
463
464//used for debug
465	echo "pdf file: $pdf_file\n";
466
467//forward the fax
468	if (file_exists($fax_file)) {
469		if (strpos($fax_file_name,'#') !== false) {
470			$tmp = explode("#",$fax_file_name);
471			$fax_forward_number = $fax_prefix.$tmp[0];
472		}
473
474		echo "fax_forward_number: $fax_forward_number\n";
475		if (strlen($fax_forward_number) > 0) {
476			fax_split_dtmf($fax_forward_number, $fax_dtmf);
477
478			$fax_send_mode = $_SESSION['fax']['send_mode']['text'];
479			if (strlen($fax_send_mode) == 0){
480				$fax_send_mode = 'direct';
481			}
482
483			$route_array = outbound_route_to_bridge($_SESSION['domain_uuid'], $fax_forward_number);
484			if (count($route_array) == 0) {
485				//send the internal call to the registered extension
486					$fax_uri = "user/".$fax_forward_number."@".$domain_name;
487					$fax_variables = "";
488			}
489			else {
490				//send the external call
491					$fax_uri = $route_array[0];
492					$fax_variables = "";
493					foreach($_SESSION['fax']['variable'] as $variable) {
494						$fax_variables .= $variable.",";
495					}
496			}
497
498			$dial_string  = "absolute_codec_string='PCMU,PCMA',";
499			$dial_string .= "accountcode='"                  . $fax_accountcode         . "',";
500			$dial_string .= "sip_h_X-accountcode='"          . $fax_accountcode         . "',";
501			$dial_string .= "domain_uuid="                   . $_SESSION["domain_uuid"] . ",";
502			$dial_string .= "domain_name="                   . $_SESSION["domain_name"] . ",";
503			$dial_string .= "origination_caller_id_name='"   . $fax_caller_id_name      . "',";
504			$dial_string .= "origination_caller_id_number='" . $fax_caller_id_number    . "',";
505			$dial_string .= "fax_ident='"                    . $fax_caller_id_number    . "',";
506			$dial_string .= "fax_header='"                   . $fax_caller_id_name      . "',";
507			$dial_string .= "fax_file='"                     . $fax_file                . "',";
508
509			if ($fax_send_mode != 'queue') {
510				$dial_string .= $fax_variables;
511				$dial_string .= "mailto_address='"     . $mailto_address   . "',";
512				$dial_string .= "mailfrom_address='"   . $mailfrom_address . "',";
513				$dial_string .= "fax_uri=" . $fax_uri  . ",";
514				$dial_string .= "fax_retry_attempts=1" . ",";
515				$dial_string .= "fax_retry_limit=20"   . ",";
516				$dial_string .= "fax_retry_sleep=180"  . ",";
517				$dial_string .= "fax_verbose=true"     . ",";
518				$dial_string .= "fax_use_ecm=off"      . ",";
519				$dial_string .= "api_hangup_hook='lua fax_retry.lua'";
520				$dial_string  = "{" . $dial_string . "}" . $fax_uri." &txfax('".$fax_file."')";
521
522				//get the event socket information
523					$sql = "select * from v_settings ";
524					$prep_statement = $db->prepare(check_sql($sql));
525					$prep_statement->execute();
526					$result = $prep_statement->fetchAll(PDO::FETCH_ASSOC);
527					foreach ($result as &$row) {
528						$event_socket_ip_address = $row["event_socket_ip_address"];
529						$event_socket_port = $row["event_socket_port"];
530						$event_socket_password = $row["event_socket_password"];
531						break;
532					}
533
534				//create the event socket connection
535					$fp = event_socket_create($event_socket_ip_address, $event_socket_port, $event_socket_password);
536
537				//send the command with event socket
538					if ($fp) {
539						//prepare the fax originate command
540							$cmd = "api originate " . $dial_string;
541						//send info to the log
542							echo "fax forward\n";
543							echo $cmd."\n";
544						//send the command to event socket
545							$response = event_socket_request($fp, $cmd);
546							$response = str_replace("\n", "", $response);
547						//send info to the log
548							echo "response: ".$response."\n";
549						//get the uuid
550							$uuid = str_replace("+OK ", "", $response);
551						//close event socket
552							fclose($fp);
553					}
554			}
555			else{
556				$wav_file = '';
557				$response = fax_enqueue($fax_uuid, $fax_file, $wav_file, $mailto_address, $fax_uri, $fax_dtmf, $dial_string);
558			}
559		}
560	}
561
562//send the email
563	if (strlen($fax_email) > 0 && file_exists($fax_file)) {
564		//prepare the message
565			$tmp_subject = (($fax_email_inbound_subject_tag != '') ? "[".$fax_email_inbound_subject_tag."]" : "Fax Received").": ".$fax_file_name;
566
567			$tmp_text_html = "<br><strong>Fax Received</strong><br><br>";
568			$tmp_text_html .= "Name: ".$fax_file_name."<br>";
569			$tmp_text_html .= "Extension: ".$fax_extension."<br>";
570			$tmp_text_html .= "Messages: ".$fax_messages."<br>";
571			$tmp_text_html .= $fax_file_warning."<br>";
572			if ($fax_relay == 'yes') {
573				$tmp_subject = "Fax Received for Relay: ".$fax_file_name;
574				$tmp_text_html .= "<br>This message arrived successfully from your fax machine, and has been queued for outbound fax delivery. You will be notified later as to the success or failure of this fax.<br>";
575			}
576			$tmp_text_plain = strip_tags(str_replace("<br>", "\n", $tmp_text_html));
577
578		//prepare the mail object
579			$mail = new PHPMailer();
580			if (isset($smtp['method'])) {
581				switch($smtp['method']) {
582					case 'sendmail': $mail->IsSendmail(); break;
583					case 'qmail': $mail->IsQmail(); break;
584					case 'mail': $mail->IsMail(); break;
585					default: $mail->IsSMTP(); break;
586				}
587			}
588			else {
589				$mail->IsSMTP(); // set mailer to use SMTP
590			}
591
592		//optionally skip certificate validation
593			if (isset($_SESSION['email']['smtp_validate_certificate'])) {
594				if ($_SESSION['email']['smtp_validate_certificate']['boolean'] == "false") {
595
596					// this works around TLS certificate problems e.g. self-signed certificates
597					$mail->SMTPOptions = array(
598						'ssl' => array(
599						'verify_peer' => false,
600						'verify_peer_name' => false,
601						'allow_self_signed' => true
602						)
603					);
604				}
605			}
606
607			if ($smtp['auth'] == "true") {
608				$mail->SMTPAuth = $smtp['auth']; // turn on/off SMTP authentication
609			}
610			$mail->Host = $smtp['host'];
611			if (strlen($smtp['port']) > 0) {
612				$mail->Port = $smtp['port'];
613			}
614			if (strlen($smtp['secure']) > 0 && $smtp['secure'] != 'none') {
615				$mail->SMTPSecure = $smtp['secure'];
616			}
617			if ($smtp['username'] != '') {
618				$mail->Username = $smtp['username'];
619				$mail->Password = $smtp['password'];
620			}
621			$mail->SMTPDebug  = 2;
622			$mail->From = $smtp['from'];
623			$mail->FromName = $smtp['from_name'];
624			$mail->Subject = $tmp_subject;
625			$mail->AltBody = $tmp_text_plain;
626			$mail->MsgHTML($tmp_text_html);
627
628			$tmp_to = $fax_email;
629			$tmp_to = str_replace(";", ",", $tmp_to);
630			$tmp_to_array = explode(",", $tmp_to);
631			foreach($tmp_to_array as $tmp_to_row) {
632				if (strlen($tmp_to_row) > 0) {
633					echo "tmp_to_row: $tmp_to_row\n";
634					$mail->AddAddress(trim($tmp_to_row));
635				}
636			}
637
638		//output to the log
639			echo "smtp_host: ".$smtp['host']."\n";
640			echo "smtp_from: ".$smtp['from']."\n";
641			echo "smtp_from_name: ".$smtp['from_name']."\n";
642			echo "tmp_subject: $tmp_subject\n";
643
644		//add the attachments
645			if (strlen($fax_file_name) > 0) {
646				if ($pdf_file && file_exists($pdf_file)) {
647					$mail->AddAttachment($pdf_file); // pdf attachment
648				}
649				else {
650					$mail->AddAttachment($fax_file); // tif attachment
651				}
652				//$filename='fax.tif'; $encoding = "base64"; $type = "image/tif";
653				//$mail->AddStringAttachment(base64_decode($strfax),$filename,$encoding,$type);
654			}
655
656		//send the email
657			if (!$mail->Send()) {
658				echo "Mailer Error: " . $mail->ErrorInfo;
659				$email_status=$mail;
660			}
661			else {
662				echo "Message sent!";
663				$email_status="ok";
664			}
665	}
666
667//when sending an email the following files are created:
668	//     /usr/local/freeswitch/storage/fax
669	//        emailed_faxes.log - this is a log of all the faxes we have successfully emailed.  (note that we need to work out how to rotate this log)
670	//        failed_fax_emails.log - this is a log of all the faxes we have failed to email.  This log is in the form of instructions that we can re-execute in order to retry.
671	//            Whenever this exists there should be an at job present to run it sometime in the next 3 minutes (check with atq).  If we succeed in sending the messages
672	//            this file will be removed.
673	//     /tmp
674	//        fax_email_retry.sh - this is the renamed failed_fax_emails.log and is created only at the point in time that we are trying to re-send the emails.  Note however
675	//            that this will continue to exist even if we succeed as we do not delete it when finished.
676	//        failed_fax_emails.sh - this is created when we have a email we need to re-send.  At the time it is created, an at job is created to execute it in 3 minutes time,
677	//            this allows us to try sending the email again at that time.  If the file exists but there is no at job this is because there are no longer any emails queued
678	//            as we have successfully sent them all.
679	if (strlen($fax_email) > 0 && file_exists($fax_file)) {
680		if (stristr(PHP_OS, 'WIN')) {
681			//not compatible with windows
682		}
683		else {
684			$fax_to_email_queue_dir = $_SESSION['switch']['storage']['dir']."/fax";
685			if ($email_status == 'ok') {
686				// log the success
687					$fp = fopen($fax_to_email_queue_dir."/emailed_faxes.log", "a");
688					fwrite($fp, $fax_file_name." received on ".$fax_extension." emailed to ".$fax_email." ".$fax_messages."\n");
689					fclose($fp);
690			} else {
691				// create an instruction log to email messages once the connection to the mail server has been restored
692					$fp = fopen($fax_to_email_queue_dir."/failed_fax_emails.log", "a");
693					fwrite($fp, PHP_BINDIR."/php ".$_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/secure/fax_to_email.php email='".$fax_email."' extension=".$fax_extension." name='".$fax_file."' messages='".$fax_messages."' domain=".$domain_name." caller_id_name='".$caller_id_name."' caller_id_number=".$caller_id_number." retry=true\n");
694					fclose($fp);
695				// create a script to do the delayed mailing
696					$fp = fopen($_SESSION['server']['temp']['dir']."/failed_fax_emails.sh", "w");
697					fwrite($fp, "rm ".$_SESSION['server']['temp']['dir']."/fax_email_retry.sh\n");
698					fwrite($fp, "mv ".$fax_to_email_queue_dir."/failed_fax_emails.log ".$_SESSION['server']['temp']['dir']."/fax_email_retry.sh\n");
699					fwrite($fp, "chmod 777 ".$_SESSION['server']['temp']['dir']."/fax_email_retry.sh\n");
700					fwrite($fp, $_SESSION['server']['temp']['dir']."/fax_email_retry.sh\n");
701					fclose($fp);
702					$tmp_response = exec("chmod 777 ".$_SESSION['server']['temp']['dir']."/failed_fax_emails.sh");
703				// note we use batch in order to execute when system load is low.  Alternatively this could be replaced with AT.
704					$tmp_response = exec("at -f ".$_SESSION['server']['temp']['dir']."/failed_fax_emails.sh now + 3 minutes");
705			}
706		}
707	}
708
709//open the file for writing
710	if ($output_type == "file") {
711		//open the file
712			$fp = fopen($_SESSION['server']['temp']['dir']."/fax_to_email.log", "w");
713		//get the output from the buffer
714			$content = ob_get_contents();
715		//clean the buffer
716			ob_end_clean();
717		//write the contents of the buffer
718			fwrite($fp, $content);
719			fclose($fp);
720	}
721
722?>
723