command.php 30 KB
Newer Older
Kulya's avatar
Kulya committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
<?php 
// error_reporting(-1);
// use PDO;
use \AloVoice\AloVoiceConnector as ALVC;

if (!isset($_REQUEST['module'])) {
	$module = "framework";
} else {
	$module = $_REQUEST['module'];
}

if (isset($_REQUEST['command'])) {
	$command = $_REQUEST['command'];
} else {
	$command = "unset";
}

// No auth - we'll do that later.
$bootstrap_settings['freepbx_auth'] = false;

//for error handling mode
$bootstrap_settings['whoops_handler'] = 'JsonResponseHandler';

// No non-BMO Modules.
$restrict_mods = true;

if(file_exists('/etc/freepbx.conf')){
	// Bootstrap!
	include_once '/etc/freepbx.conf';
	
	\FreePBX::Modules()->loadFunctionsInc('queues');
}

// $getQueue = getQueue(6000);
// $getQueue = saveQueue(["account"=>6011,"members"=>[101,102,103]]);
// $getQueue = removeQueue(6011);
// $getQueue = addMemeberQueue(6000,299);
// $getQueue = delMemeberQueue(6000,115);

// echo '<pre>'; var_dump($getQueue); echo '</pre>'; 

/* DOCS
addMemeberQueue 
	queue
	member

delMemeberQueue 
	queue
	member
	
removeQueue 
	queue
	
addNewQueue 
	number 
	name (optional)
	goto (optional)
	members (optional) (array of local extensions)
	weight (optional) (0-9)
	strategy (optional) (one of from array ['ringall','linear','leastrecent','fewestcalls','random','rrmemory','rrordered','wrandom'])
	recording (optional) (one of from array ['force','yes','dontcare','no','never'])
	
getQueue 
	queue	
	
getQueues (no params)

getQueueMembers
	queue	(optional)

*/
Kulya's avatar
Kulya committed
72
global $confs;
Kulya's avatar
Kulya committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

if(!empty($_REQUEST['cmd'])){
	header('Access-Control-Allow-Origin: *');
	header('Content-Type: application/json');
	$cmd = $_REQUEST['cmd'];
	$r = $_REQUEST;
}
elseif(!empty($ccmd)) {
	$cmd = $ccmd;
	$r = (!empty($params)) ? $params : [];
}
else {
	die();
}


echo json_encode(doCommandAjax($cmd,$r));
die();

function doCommandAjax($cmd,$r){
Kulya's avatar
Kulya committed
93
	$confs = ALVC::getConfigs();
Kulya's avatar
Kulya committed
94
	switch ($cmd) {
Kulya's avatar
Kulya committed
95 96 97
		case 'addNewMohFile':
			return addNewMohFile($r);
		break;
Kulya's avatar
Kulya committed
98 99 100 101 102 103
		case 'removeInroute':
			return removeInroute($r);
		break;
		case 'saveInroute':
			return saveInroute($r);
		break;
Kulya's avatar
Kulya committed
104 105 106
		case 'loadDestinationsCodesListHtml':
			return loadDestinationsCodesListHtml($r);
		break;
Kulya's avatar
Kulya committed
107 108 109 110 111 112 113 114 115
		case 'loadDestinationsList':
			return loadDestinationsList($r);
		break;
		case 'loadTrunksList':
			return loadTrunksList($r);
		break;
		case 'loadInroutesList':
			return loadInroutesList($r);
		break;
Kulya's avatar
Kulya committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
		case 'saveAudioFile':
			return saveAudioFile($r);
		break;
		case 'addMemeberQueue':
			return addMemeberQueue($r['queue'],$r['member']);
		break;
		case 'delMemeberQueue':
			return delMemeberQueue($r['queue'],$r['member']);
		break;
		case 'delMemeberFromQueues':
			return delMemeberFromQueues($r['members']);
		break;
		case 'removeQueue':
			return removeQueue($r['queue']);
		break;
		case 'addNewQueue':
			return addNewQueue($r);
		break;
Kulya's avatar
Kulya committed
134 135 136
		case 'saveQueue':
			return saveQueue($r);
		break;
Kulya's avatar
Kulya committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
		case 'getQueue':
			return getQueue($r['queue']);
		break;
		case 'getQueueMembers':
			$q = (!empty($r['queue'])) ? $r['queue'] : '';
			return getQueueMembers($q);
		break;
		case 'getQueues':
			return getQueues();
		break;
		case 'addnum':
			return addNumber($r);
		break;
		case 'delnum':
			return delNumber($r);
		break;
		case 'is_working':
			return isWorking();
		break;
		case 'stop_work':
			return stopWork();
		break;
		case 'start_work':
			return startWork();
		break;
		case 'restart_work':
			return restartWork();
		break;
		case 'test':
			global $ALVC;
			// var_dump($ALVC->getConfigs());  
			return ["test"=>"ok"];
		break;
		default:
			return ['error'=>'Command not found'];
		break;
	}
}



Kulya's avatar
Kulya committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
function removeInroute($r=[]){
	if( empty($r["extension"]) || empty($r["cidnum"]) )
	{ 
		return ["error"=>"Мало данных"]; 
	}
	
	$extension = ( $r["extension"] == "Все" ) ? "" : $r["extension"];
	$cidnum = ( $r["cidnum"] == "Все" ) ? "" : $r["cidnum"];
		
	$db = \FreePBX::Database();
	$sql = "DELETE FROM incoming WHERE cidnum = '".$cidnum."' AND extension = '".$extension."'";
	$res = $db->query($sql);
	
	exec("fwconsole reload");
	
	return true;
}

function saveInroute($r=[]){
	/*
	extension // did
	cidnum  
	mohclass
	destination
	delay_answer // 0
	description 

	*/
		
	// "app-blackhole,hangup,1",
	// "ext-local,vms1098,1",
	// timeconditions,1,1
	// from-did-direct,2424,1
	// ext-queues,99999,1
	// ext-group,99998,1
	
	if(
		empty($r["extension"]) ||
		empty($r["cidnum"]) ||
		empty($r["destination"])
	)
	{ 
		return ["error"=>"Мало данных"]; 
	}
	
	$destination = '';
	
	if(!empty($r["destination_code"])){
		if($r["destination"] == "ext-queues"){
			$destination = $r["destination"].','.$r["destination_code"].',1';
		}
Kulya's avatar
Kulya committed
229
		elseif($r["destination"] == "from-did-direct"){
Kulya's avatar
Kulya committed
230 231
			$destination = $r["destination"].','.$r["destination_code"].',1';
		}
Kulya's avatar
Kulya committed
232
		elseif($r["destination"] == "timeconditions"){
Kulya's avatar
Kulya committed
233 234
			$destination = $r["destination"].',1,1';
		}
Kulya's avatar
Kulya committed
235 236 237
		elseif($r["destination"] == "mp3play"){
			$destination = $r["destination"].','.$r["destination_code"].',1';
		}
Kulya's avatar
Kulya committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
		
	}
	
	elseif($r["destination"] == "timeconditions"){
		$destination = $r["destination_code"].',1,1';
	}
	elseif($r["destination"] == "hangup"){
		$destination = 'app-blackhole,hangup,1';
	}
	elseif($r["destination"] == "vm"){
		$destination = 'ext-local,vms1098,1';
	}
	
	if(empty($destination)){
		return ["error" => "Направление не верная"];
	}
	
	$did_vars = [
		"extension" => ( $r["extension"] == "Все" ) ? "" : $r["extension"],
		"cidnum" => ( $r["cidnum"] == "Все" ) ? "" : $r["cidnum"],
		"mohclass" => "default",
		"destination" => $destination,
		"delay_answer" => 0,
		"description" => (!empty($r["description"])) ? $r["description"] : "",
	];
	
	$res = \FreePBX::Core()->createUpdateDID($did_vars);
	
	if(!empty($res)){
		exec("fwconsole reload");
	}
	
	return ["query"=>$r, "ardid"=>$did_vars, "save_res" => $res];
}

Kulya's avatar
Kulya committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
function loadDestinationsCodesListHtml($r=[]){
	$confs = ALVC::getConfigs();
	$returnHTML = '';
	if(empty($r["dest"])){ return ''; }

	if($r["dest"] == "from-did-direct"){
		$alvActions = new \AloVoice\AloVoiceActions($confs);
		$arAllOperators = $alvActions->getAlovoiceOperatorsNums($r);
		$returnHTML .= '<select id="inrt_destination_code" class="form-control inrouteinp">';
		foreach($arAllOperators as $num=>$operator){
			$returnHTML .= '<option value="'.$num.'">'.$num.' - '.$operator["NAME"].' '.$operator["LAST_NAME"].'</option>';
		}
		$returnHTML .= '</select>';
	}
	
	elseif($r["dest"] == "ext-queues"){
		$alvActions = new \AloVoice\AloVoiceActions($confs);
		$arAllQueues = $alvActions->getAlovoiceAllQueues($r);
		$returnHTML .= '<select id="inrt_destination_code" class="form-control inrouteinp">';
		foreach($arAllQueues as $q=>$s){
			$returnHTML .= '<option value="'.$q.'">'.$q.' - '.$s.'</option>';
		}
		$returnHTML .= '</select>';
	}
	
	elseif($r["dest"] == "mp3play"){
		$alvActions = new \AloVoice\AloVoiceActions($confs);
		$path = ALVC::getSoundsPath();
		$arAllSounds = $alvActions->getAlovoiceSoundsList($path);
		$returnHTML .= '<select id="inrt_destination_code" class="form-control inrouteinp">';
		foreach($arAllSounds as $scode=>$snd){
			$returnHTML .= '<option value="'.$scode.'">'.$snd["title"].'</option>';
		}
		$returnHTML .= '</select>';
	}
	return $returnHTML;
}

Kulya's avatar
Kulya committed
311
function loadDestinationsList($r=[]){
Kulya's avatar
Kulya committed
312 313 314 315 316 317 318 319 320 321
	$arDestTypelist = allAlvDestinationsList();
	foreach($arDestTypelist as $dk=>$dest){
		if(substr($dk,0,1)=="_"){
			unset($arDestTypelist[$dk]);
		}
	}
	return $arDestTypelist;
}

function allAlvDestinationsList($r=[]){
Kulya's avatar
Kulya committed
322 323 324 325
	$destTitle = [];
	
	$destTitle["from-did-direct"] = 'Внут.номер';
	$destTitle["ext-queues"] = 'Очередь';
Kulya's avatar
Kulya committed
326
	$destTitle["ext-group"] = 'Группа';
Kulya's avatar
Kulya committed
327 328
	$destTitle["timeconditions"] = 'Правила по времени';
	$destTitle["vm"] = 'Голосовая почта';
Kulya's avatar
Kulya committed
329 330 331 332
	$destTitle["mp3play"] = 'Возпроизвести запись';
	$destTitle["_play-system-recording"] = 'Приветствие';
	$destTitle["_ext-trunk"] = 'На внешнюю линию';
	// $destTitle["ivr"] = 'IVR';
Kulya's avatar
Kulya committed
333 334 335 336 337 338 339 340
	$destTitle["hangup"] = 'Завершить звонок';

	
	return $destTitle;
}

function loadInroutesList($r=[]){
	$arInroutes = [];
Kulya's avatar
Kulya committed
341
	$arDestTypelist = allAlvDestinationsList();
Kulya's avatar
Kulya committed
342 343 344 345
	$db = \FreePBX::Database();
	$sql = "SELECT * FROM incoming ORDER BY extension,cidnum";
	$ob = $db->query($sql,\PDO::FETCH_ASSOC);
	
Kulya's avatar
Kulya committed
346 347 348 349
	$alvActions = new \AloVoice\AloVoiceActions($confs);
	$path = ALVC::getSoundsPath();
	$arAllSounds = $alvActions->getAlovoiceSoundsList($path);
		
Kulya's avatar
Kulya committed
350 351 352 353 354 355 356 357
	if($ob->rowCount()){
		$dbInroutes = $ob->fetchAll();
	}
	
	foreach($dbInroutes as $route){
		$arDest = explode(",",$route['destination']);
		
		$destTitle = '';
Kulya's avatar
Kulya committed
358 359 360
		if(!empty($arDest[0]) && (!empty($arDestTypelist[$arDest[0]]) || !empty($arDestTypelist["_".$arDest[0]]))){
			$destTitle = (!empty($arDestTypelist[$arDest[0]])) ? $arDestTypelist[$arDest[0]] : $arDestTypelist["_".$arDest[0]];
			$destCode = (!empty($arAllSounds[$arDest[1]])) ? $arAllSounds[$arDest[1]]["title"] : $arDest[1];
Kulya's avatar
Kulya committed
361
		}
Kulya's avatar
Kulya committed
362 363 364
		elseif(!empty($arDest[0]) && substr($arDest[0],0,3)=="ivr"){
			$destTitle = 'IVR';
			$destCode = substr($arDest[0],4);
Kulya's avatar
Kulya committed
365
		}
Kulya's avatar
Kulya committed
366 367 368 369 370 371 372 373 374 375 376 377
		// if(!empty($arDest[0]) && $arDest[0]=="from-did-direct"){
			// $destTitle = 'Внут.номер';
		// }
		// if(!empty($arDest[0]) && $arDest[0]=="ext-queues"){
			// $destTitle = 'Очередь';
		// }
		// if(!empty($arDest[0]) && $arDest[0]=="ext-group"){
			// $destTitle = 'Группа';
		// }
		// if(!empty($arDest[0]) && $arDest[0]=="timeconditions"){
			// $destTitle = 'Правила по времени';
		// }
Kulya's avatar
Kulya committed
378 379 380 381 382 383 384
		
		$arInroutes[] = [
			
			// 'id' => $route[''],
			'name' => $route['description'],
			'route_cid' => (!empty($route['cidnum'])) ? $route['cidnum'] : "Все",
			'route_did' => (!empty($route['extension'])) ? $route['extension'] : "Все",
Kulya's avatar
Kulya committed
385
			'route_goto' => $destTitle." (".$destCode.")",
Kulya's avatar
Kulya committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
			'route_goto_code' => $route['destination'],
			'route_moh' => $route['mohclass']
		];
	}
	
	$arHeaders = [
		'name' => 'Название',
		'route_cid' => 'Кто звонит',
		'route_did' => 'Куда звонит',
		'route_goto' => 'Назначение',
		'route_moh' => 'Мелодия в ожидании',
	];
	
	$arReturn = [
		'headers' => $arHeaders,
		'datas' => $arInroutes,
Kulya's avatar
Kulya committed
402
		'sounds' => $arAllSounds
Kulya's avatar
Kulya committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
	];
	
	return $arReturn;
}

function loadTrunksList($r=[]){
	// TODO: $assoc default to true, eventually..
	//outcid	keepcid	maxchans
	
	// $trunks = \FreePBX::Core()->listTrunks();
	
	$db = \FreePBX::Database();
	$sql = "SELECT `trunkid` , `tech` , `outcid`, `name`, `keepcid`, `maxchans`, `channelid` , `disabled` FROM `trunks` ORDER BY `trunkid`";
	$ob = $db->query($sql,\PDO::FETCH_ASSOC);
	
	$dbTrunks = [];
	
	if($ob->rowCount()){
		$dbTrunks = $ob->fetchAll();
	}
	
	
	// $unique_trunks = array();
	// foreach ($trunks as $trunk) {
		// $trunk_id = "OUT_".$trunk['trunkid'];
		// $disabled = $trunk['disabled'];
		// if($disabled=="off"){ continue; }
		// $tech = strtoupper($trunk['tech']);
		// switch ($tech) {
			// case 'IAX':
			// $dialstring = 'IAX2/'.$trunk['channelid'];
			// break;
			// case 'CUSTOM':
			// $dialstring = 'AMP:'.$trunk['channelid'];
			// break;
			// default:
			// $dialstring = $tech.'/'.$trunk['channelid'];
			// break;
		// }
		// $unique_trunks[] = array($trunk_id, $dialstring, $disabled);
	// }

	// $arTrunks = array();

	foreach ($dbTrunks as $trunk) {
				
		$arTrunks[$trunk["trunkid"]] = [
			'id' => $trunk["trunkid"],
			'type' => $trunk["tech"],
			'name' => $trunk["name"],
			'number' => (!empty($trunk["outcid"])) ? $trunk["outcid"] : "_",
			'maxchannels' => (!empty($trunk["maxchans"])) ? $trunk["maxchans"] : "-",
Kulya's avatar
Kulya committed
455
			'status' => (!empty($trunk["disabled"]) && $trunk["disabled"]=="off") ? "On" : "Off",
Kulya's avatar
Kulya committed
456
			'disabled' => $trunk["disabled"],
Kulya's avatar
Kulya committed
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
			// 'globalvar' => $trunk[0], //OUT_4
		];
		
	}
	
	$arHeaders = [
		'id' => 'ID',
		'name' => 'Название',
		'type' => 'Тип',
		'number' => 'Номер',
		'maxchannels' => 'Максимум линий',
		'status' => 'Статус',
	];

	$arReturn = [
		'headers' => $arHeaders,
		'datas' => $arTrunks,
		'test' => $rawTest,
	];
	
	return $arReturn;
}

Kulya's avatar
Kulya committed
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
function restartWork(){
	return true;
}

function startWork(){
	return true;
}

function stopWork(){
	$stopFile = 'stop';
	file_put_contents($stopFile,'1');
	return true;
}
function isWorking(){
	$ans = exec("ps -aux | grep listener.php | grep -v grep | awk '{print $2}'",$out);
	if(is_numeric($ans) && $ans>0){
		return true;
	}
	else {
		return false;
	}
}

function saveAudioFile($r){
	//$recsDir = __DIR__.'/records/';
	$confs = ALVC::getConfigs();
	$soundsDir = ALVC::getSoundsPath($confs);
	
	if(!empty($_FILES['record_file'])){
		$times = time();
		$filefullname = $times.'.'.$r["ext"];
		$filepath = $soundsDir.$filefullname;
		// $filelink = $confs['alovoice_host'].$confs['sounds_folder'].$filefullname;
			
		if(move_uploaded_file($_FILES['record_file']['tmp_name'],$filepath)){
			return ['recpath'=>$filepath];
		}
	}
	
	return ['error'=>['req'=>$r, 'files'=>$_FILES]];
}

function delNumber($r,$rl=true){
	if(empty($r['PEERNUMBERS'])){
		return ['error'=>'No Numbers'];
	}
	
	$results = [];
	foreach($r['PEERNUMBERS'] as $num){
		$results[] = \FreePBX::Core()->delDevice((int)$num);
	}
	
	if($rl){
		exec("fwconsole reload");
	}
	// exec("fwconsole reload >/dev/null 2>&1 &");
	return $results;
}

function addNumber($r){
	if(!empty($r['numbers'])){
		$arNumbers = json_decode($r['numbers'],true);
	}
	elseif(!empty($r['PEERNUMBER']) && !empty($r['PEERPASS'])){
		$numbers = str_replace(' ', '', $r["PEERNUMBER"]);
		$arNums = explode("-",$numbers);
		$numpass = (!empty($r["PEERPASS"])) ? $r["PEERPASS"] : rand(111111,999999);
		$arNumbers = [];
		if(count($arNums)>1){
			for($n=$arNums[0]; $n<=$arNums[1]; $n++){
				$arNumbers[$n] = $numpass;
			}
		}
		else {
			$arNumbers[$arNums[0]] = $numpass;
		}
	}

	if(empty($arNumbers)){
		return false;
	}
	
	$extens = [];
	foreach($arNumbers as $num=>$pass){
		$extens[] = array(
			'extension' => $num,
			'name' => $num,
			'description' => $num,
			'tech' => 'sip',
			'secret' => $pass,
			'callwaiting' => 'disabled'
		);
	}
	// $data = array(
		// array(
			// 'extension' => '4001',
			// 'name' => '4001',
			// 'description' => '4001',
			// 'tech' => 'sip',
			// 'secret' => 'voip#2021',
			// 'callwaiting' => 'disabled'
		// ),
		// array(
			// 'extension' => '4002',
			// 'name' => '4002',
			// 'description' => '4002',
			// 'tech' => 'sip',
			// 'secret' => 'voip#2021',
			// 'callwaiting' => 'disabled'
		// )
	// );
	$ret = \FreePBX::Bulkhandler()->import('extensions', $extens, true);
	exec("fwconsole reload");
	// exec("fwconsole reload >/dev/null 2>&1 &");
	return $ret;
}

function getQueueMembers($q){
	$arPeers = queues_get_static_members($q);
	
	$members = [];
	foreach($arPeers as $qk=>$qm){
		if (preg_match("/^.*?\/([\d]+).*,([\d]+)$/", $qm, $matches)) {
			if(!empty($matches[1])){ $members[] = $matches[1]; }
		}
	}
	return $members;
}

function addMemeberQueue($q,$m){
	global $db;
	$sql = "SELECT data FROM queues_details WHERE id = ".$q." AND keyword = 'member' ORDER BY flags";
	$qmembers = $db->getCol($sql);
	$issetNum = false;
	if(!empty($qmembers)){
		foreach($qmembers as $qk=>$qm){
			if (preg_match("/^.*?\/([\d]+).*,([\d]+)$/", $qm, $matches)) {
				$qmembers[$qk] = $matches[1];
				if($matches[1]==$m){
					$issetNum = true;
				}
			}
		}
	}
	else{
		$qmembers = [];
	}
	if($issetNum==false){
		$qmembers[] = (string)$m;
	}
	
	saveQueue(["account"=>$q,"members"=>$qmembers]);
	return $qmembers;
}

function delMemeberFromQueues($m){
	global $db;
	
	if(!is_array($m)){ $m = [$m]; }
	
	foreach($m as $num){
		$sql = "SELECT id FROM queues_details WHERE data LIKE '%".$num."%' AND keyword = 'member' ORDER BY flags";
		$queues = $db->getCol($sql);
		
		if(!empty($queues)){
			foreach( $queues as $q ){
				delMemeberQueue($q,$num,false);
			}
		}
	}
	
	delNumber(['PEERNUMBERS'=>$m],false);

				
	do_reload();
	return ["ok"];
}

function delMemeberQueue($q,$m,$r=true){
	global $db;
	$sql = "SELECT data FROM queues_details WHERE id = ".$q." AND keyword = 'member' ORDER BY flags";
	$qmembers = $db->getCol($sql);
	$issetNum = false;
	if(!empty($qmembers)){
		foreach($qmembers as $qk=>$qm){
			if (preg_match("/^.*?\/([\d]+).*,([\d]+)$/", $qm, $matches)) {
				$qmembers[$qk] = $matches[1];
				if(is_array($m) && in_array($matches[1],$m)){
					$qmembers[$qk] = null;
					unset($qmembers[$qk]);
				}
				elseif(!is_array($m) && $matches[1]==$m){
					$qmembers[$qk] = null;
					unset($qmembers[$qk]);
				}
			}
		}
	}
	else{
		$qmembers = [];
	}
	
	saveQueue(["account"=>$q,"members"=>$qmembers],$r);
	return $qmembers;
}

function removeQueue($q){
	queues_del($q);
	do_reload();
	return ["ok"];
}

function addNewQueue($data){
	$data["account"] = $data["number"];
	unset($data["number"]);
	return saveQueue($data);
}

function saveQueue($data,$r=true){
	global $db,$astman,$amp_conf;
	if(empty($data["account"])){ return false; }
	$oQueue = queues_get($data["account"]);
	
	$account = $data["account"];
	queues_del($account);
	
	$name = (!empty($data["name"])) ? $data["name"] : false;
	if(empty($name) && !empty($oQueue["name"])) { $name = $oQueue["name"]; }
	if(empty($name)){ $name = "Q".$data["account"]; }
	
	$password = (!empty($data["password"])) ? $data["password"] : (!empty($oQueue["password"])) ? $oQueue["password"] : "";
	$prefix = (!empty($data["prefix"])) ? $data["prefix"] : (!empty($oQueue["prefix"])) ? $oQueue["prefix"] : "";
Kulya's avatar
Kulya committed
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
	
	if(!empty($data["queue_destination_code"])){
			if($data["goto"] == "ext-queues"){
				$goto = $data["goto"].','.$data["queue_destination_code"].',1';
			}
			if($data["goto"] == "from-did-direct"){
				$goto = $data["goto"].','.$data["queue_destination_code"].',1';
			}
			if($data["goto"] == "timeconditions"){
				$goto = $data["goto"].',1,1';
			}

		if(empty($goto)){
			return ["error" => "Направление не верная"];
		}
	}
	elseif($data["goto"] == "timeconditions"){
		$goto = $data["goto"].',1,1';
	}
	elseif($data["goto"] == "hangup"){
		$goto = 'app-blackhole,hangup,1';
	}
	elseif($data["goto"] == "vm"){
		$goto = 'ext-local,vms1098,1';
	}
	else {
		$goto = (!empty($data["goto"])) ? $data["goto"] : false;
		if(empty($goto)) {
			$goto = (!empty($oQueue["goto"])) ? $oQueue["goto"] : "app-blackhole,hangup,1";
		}
Kulya's avatar
Kulya committed
742
	}
Kulya's avatar
Kulya committed
743
	
Kulya's avatar
Kulya committed
744 745 746 747
	
	$music = (!empty($data["music"])) ? $data["music"] : false;
	if(empty($music) && !empty($oQueue["music"])) { $music = $oQueue["music"]; } elseif(empty($music)) {$music = 'default';}
	
Kulya's avatar
Kulya committed
748 749 750
	$department = (!empty($data["department"])) ? $data["department"] : false;
	if(empty($department) && !empty($oQueue["department"])) { $department = $oQueue["department"]; } elseif(empty($department)) {$department = '1';}
	
Kulya's avatar
Kulya committed
751
	$strategy = (!empty($data["strategy"])) ? $data["strategy"] : false;
Kulya's avatar
Kulya committed
752
	if(empty($strategy) && !empty($oQueue["strategy"])) { $strategy = $oQueue["strategy"]; } elseif(empty($strategy)) {$strategy = 'ringall';}
Kulya's avatar
Kulya committed
753

754
	$recording = (!empty($data["recording"])) ? $data["recording"] : 'force';
Kulya's avatar
Kulya committed
755
	
Kulya's avatar
Kulya committed
756 757 758 759 760 761 762 763 764 765 766 767 768 769
	$agentannounce_id = (!empty($data["agentannounce_id"])) ? $data["agentannounce_id"] : (!empty($oQueue["agentannounce_id"])) ? $oQueue["agentannounce_id"] : NULL;
	$joinannounce_id = (!empty($data["joinannounce_id"])) ? $data["joinannounce_id"] : (!empty($oQueue["joinannounce_id"])) ? $oQueue["joinannounce_id"] : NULL;
	$maxwait = (!empty($data["maxwait"])) ? $data["maxwait"] : (!empty($oQueue["maxwait"])) ? $oQueue["maxwait"] : "";
	
	$members = (!empty($data["members"])) ? makeMembers($data["members"]) : [];
	if(empty($members) && !empty($oQueue["member"])) {
		$members = $oQueue["member"];
	}

	
	$fields = [];
	$fields[] = [$account,'maxlen',(!empty($oQueue["maxlen"])) ? $oQueue["maxlen"] : '0',0];
	$fields[] = [$account,'joinempty',(!empty($oQueue["joinempty"])) ? $oQueue["joinempty"] : 'yes',0];
	$fields[] = [$account,'leavewhenempty',(!empty($oQueue["leavewhenempty"])) ? $oQueue["leavewhenempty"] : 'no',0];
Kulya's avatar
Kulya committed
770
	$fields[] = [$account,'strategy',$strategy,0];
Kulya's avatar
Kulya committed
771 772 773 774 775 776 777 778 779 780 781
	$fields[] = [$account,'timeout',(!empty($oQueue["timeout"])) ? $oQueue["timeout"] : '15',0];
	$fields[] = [$account,'retry',(!empty($oQueue["retry"])) ? $oQueue["retry"] : '5',0];
	$fields[] = [$account,'wrapuptime',(!empty($oQueue["wrapuptime"])) ? $oQueue["wrapuptime"] : '0',0];
	$fields[] = [$account,'announce-frequency',(!empty($oQueue["announce-frequency"])) ? $oQueue["announce-frequency"] : '0',0];
	$fields[] = [$account,'min-announce-frequency',(!empty($oQueue["min-announce-frequency"])) ? $oQueue["min-announce-frequency"] : '15',0];
	$fields[] = [$account,'announce-holdtime',(!empty($oQueue["announce-holdtime"])) ? $oQueue["announce-holdtime"] : 'no',0];
	$fields[] = [$account,'queue-youarenext',(!empty($oQueue["queue-youarenext"])) ? $oQueue["queue-youarenext"] : 'silence/1',0];
	$fields[] = [$account,'queue-thereare',(!empty($oQueue["queue-thereare"])) ? $oQueue["queue-thereare"] : 'silence/1',0];
	$fields[] = [$account,'queue-callswaiting',(!empty($oQueue["queue-callswaiting"])) ? $oQueue["queue-callswaiting"] : 'silence/1',0];
	$fields[] = [$account,'queue-thankyou',(!empty($oQueue["queue-thankyou"])) ? $oQueue["queue-thankyou"] : '',0]; //queue-thankyou
	$fields[] = [$account,'periodic-announce-frequency',(!empty($oQueue["periodic-announce-frequency"])) ? $oQueue["periodic-announce-frequency"] : '0',0];
782
	$fields[] = [$account,'recording',$recording,0]; //(!empty($oQueue["recording"])) ? $oQueue["recording"] : 'force'
Kulya's avatar
Kulya committed
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
	$fields[] = [$account,'monitor-join',(!empty($oQueue["monitor-join"])) ? $oQueue["monitor-join"] : 'yes',0];
	$fields[] = [$account,'weight',(!empty($oQueue["weight"])) ? $oQueue["weight"] : '0',0];
	$fields[] = [$account,'autofill',(!empty($oQueue["autofill"])) ? $oQueue["autofill"] : 'no',0];
	$fields[] = [$account,'ringinuse',(!empty($oQueue["ringinuse"])) ? $oQueue["ringinuse"] : 'yes',0];
	$fields[] = [$account,'reportholdtime',(!empty($oQueue["reportholdtime"])) ? $oQueue["reportholdtime"] : 'no',0];
	$fields[] = [$account,'autopause',(!empty($oQueue["autopause"])) ? $oQueue["autopause"] : 'no',0];
	$fields[] = [$account,'autopausedelay',(!empty($oQueue["autopausedelay"])) ? $oQueue["autopausedelay"] : '0',0];
	$fields[] = [$account,'servicelevel',(!empty($oQueue["servicelevel"])) ? $oQueue["servicelevel"] : 60,0];
	$fields[] = [$account,'memberdelay',(!empty($oQueue["memberdelay"])) ? $oQueue["memberdelay"] : '0',0];
	$fields[] = [$account,'timeoutrestart',(!empty($oQueue["timeoutrestart"])) ? $oQueue["timeoutrestart"] : 'no',0];
	$fields[] = [$account,'skip_joinannounce',(!empty($oQueue["skip_joinannounce"])) ? $oQueue["skip_joinannounce"] : '',0];
	$fields[] = [$account,'answered_elsewhere',(!empty($oQueue["answered_elsewhere"])) ? $oQueue["answered_elsewhere"] : '0',0];
	$fields[] = [$account,'rvolume',(!empty($oQueue["rvolume"])) ? $oQueue["rvolume"] : '',0];
	$fields[] = [$account,'eventwhencalled',(!empty($oQueue["eventwhencalled"])) ? $oQueue["eventwhencalled"] : $amp_conf['QUEUES_EVENTS_MEMEBER_STATUS_DEFAULT'],0];
	$fields[] = [$account,'eventmemberstatus',(!empty($oQueue["eventmemberstatus"])) ? $oQueue["eventmemberstatus"] : $amp_conf['QUEUES_EVENTS_MEMEBER_STATUS_DEFAULT'],0];
	$fields[] = [$account,'autopausebusy',(!empty($oQueue["autopausebusy"])) ? $oQueue["autopausebusy"] : 'no',0];
	$fields[] = [$account,'autopauseunavail',(!empty($oQueue["autopauseunavail"])) ? $oQueue["autopauseunavail"] : 'no',0];
Kulya's avatar
Kulya committed
800
	$fields[] = [$account,'department',$department,0];
Kulya's avatar
Kulya committed
801
	
Kulya's avatar
Kulya committed
802
	$fields[] = [$account,'music',$music,0];
Kulya's avatar
Kulya committed
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922


	//there can be multiple members
	if (!empty($members)) {
		$count = 0;
		$members = array_unique($members);
		foreach ($members as $member) {
			$fields[] = array($account,'member',$member,$count);
			$count++;
		}
	}

	$compiled = $db->prepare('INSERT INTO queues_details (id, keyword, data, flags) values (?,?,?,?)');
	$result = $db->executeMultiple($compiled,$fields);

	if($db->IsError($result)) {
		return ["error"=>$result->getMessage()."<br><br>error adding to queues_details table"];
	}
	
	$alertinfo		= (!empty($data["alertinfo"])) ? $data["alertinfo"] : (!empty($oQueue["alertinfo"])) ? $oQueue["alertinfo"] : "";
	$ringing		= (!empty($data["ringing"])) ? $data["ringing"] : (!empty($oQueue["ringing"])) ? $oQueue["ringing"] : 0;
	$callconfirm_id		= (!empty($data["callconfirm_id"])) ? $data["callconfirm_id"] : (!empty($oQueue["callconfirm_id"])) ? $oQueue["callconfirm_id"] : NULL;
	$ivr_id		= (!empty($data["ivr_id"])) ? $data["ivr_id"] : (!empty($oQueue["ivr_id"])) ? $oQueue["ivr_id"] : 'none';
	$callback_id		= (!empty($data["callback_id"])) ? $data["callback_id"] : (!empty($oQueue["callback_id"])) ? $oQueue["callback_id"] : 'none';
	$cwignore		= (!empty($data["cwignore"])) ? $data["cwignore"] : (!empty($oQueue["cwignore"])) ? $oQueue["cwignore"] : '0';
	$queuewait		= (!empty($data["queuewait"])) ? $data["queuewait"] : (!empty($oQueue["queuewait"])) ? $oQueue["queuewait"] : '0';
	$qregex		= (!empty($data["qregex"])) ? $data["qregex"] : (!empty($oQueue["qregex"])) ? $oQueue["qregex"] : '0';
	$use_queue_context		= (!empty($data["use_queue_context"])) ? $data["use_queue_context"] : (!empty($oQueue["use_queue_context"])) ? $oQueue["use_queue_context"] : '0';
	$togglehint		= (!empty($data["togglehint"])) ? $data["togglehint"] : (!empty($oQueue["togglehint"])) ? $oQueue["togglehint"] : 0;
	$callconfirm		= (!empty($data["callconfirm"])) ? $data["callconfirm"] : (!empty($oQueue["callconfirm"])) ? $oQueue["callconfirm"] : 0;
	$qnoanswer		= (!empty($data["qnoanswer"])) ? $data["qnoanswer"] : (!empty($oQueue["qnoanswer"])) ? $oQueue["qnoanswer"] : '0';
	$monitor_type		= (!empty($data["monitor_type"])) ? $data["monitor_type"] : (!empty($oQueue["monitor_type"])) ? $oQueue["monitor_type"] : '';
	$monitor_heard		= (!empty($data["monitor_heard"])) ? $data["monitor_heard"] : (!empty($oQueue["monitor_heard"])) ? $oQueue["monitor_heard"] : '0';
	$monitor_spoken		= (!empty($data["monitor_spoken"])) ? $data["monitor_spoken"] : (!empty($oQueue["monitor_spoken"])) ? $oQueue["monitor_spoken"] : '0';

	
	$sql = "INSERT INTO queues_config (
			extension, descr, grppre, alertinfo, joinannounce_id,
			ringing, agentannounce_id, maxwait, password, ivr_id,
			callback_id, dest, cwignore, qregex, queuewait,
			use_queue_context, togglehint, qnoanswer, callconfirm,
			callconfirm_id, monitor_type, monitor_heard,
			monitor_spoken
		) VALUES (
			?, ?, ?, ?, ?,
			?, ?, ?, ?, ?,
			?, ?, ?, ?, ?,
			?, ?, ?, ?,
			?, ?, ?,
			?
		)";
	$sth = $db->prepare($sql);
	$values = array(
		$account, $name, $prefix, $alertinfo, $joinannounce_id,
		$ringing, $agentannounce_id, $maxwait, $password, $ivr_id,
		$callback_id, $goto, $cwignore, $qregex, $queuewait,
		$use_queue_context, $togglehint, $qnoanswer, $callconfirm,
		$callconfirm_id, $monitor_type, $monitor_heard,
		$monitor_spoken
	);
	$results = $sth->execute($values);

	if($db->IsError($results)) {
		return ["error"=>$results->getMessage()."<br><br>error adding to queues_config table"];
	}
	
	if(!empty($r)){
		do_reload();
	}
	
	return $values;
}

function getQueues(){
	return queues_list();
}

function getQueue($id){
	$queue = queues_get($id);

	if ($queue) {
		$queue['extension'] = $id;

		$dynmembers = array();
		foreach (explode("\n", $queue['dynmembers']) as $member) {
			$dynmembers[] = substr($member, 0, strpos($member, ","));
		}
		$queue['dynmembers'] = $dynmembers;

		$members = array();
		foreach ($queue['member'] as $member) {
			if (preg_match("/^.*?\/([\d]+).*,([\d]+)$/", $member, $matches)) {
				$members[] = $matches[1];
			}
		}
		$queue['member'] = $members;
	}

	return $queue ? $queue : false;
}

function makeMembers($members){
	if (empty($members)) {
		return null;
	}
	if(!is_array($members)){
		$members = explode("\n",$members);
	}

	foreach (array_keys($members) as $key) {
		//trim it
		$members[$key] = trim($members[$key]);
		$exten_context = "from-queue";
		$exten_type = 'Local';
		$penalty_val = 0;
		$members[$key] = $exten_type."/".$members[$key]."@".$exten_context."/n,".$penalty_val;
	}
	
	return $members;
}
Kulya's avatar
Kulya committed
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986

function addNewMohFile( $r=[] ) {
	if(empty($r["arfile"])){
		return false;
	}
	
	global $db,$astman,$amp_conf;
	
	$arFile = $r["arfile"];
	
	$mohdir = '/var/lib/asterisk/moh/';
	$uniqName = $arFile["time"];
	$newMohDir = $mohdir.$uniqName;
	$newMohFileName = $newMohDir."/".$uniqName;
	$newMohFile = $newMohFileName.".".$arFile["ext"];
	
	if(!is_dir($newMohDir)){
		mkdir($newMohDir,0777);
	}
	if(!empty($arFile["filepath"]) && file_exists($arFile["filepath"])){
		$origFile = $arFile["filepath"];
		// copy($arFile["filepath"],$newMohFile);
	}
	
	$media = \FreePBX::Media(); //\FreePBX::Music()->Media;
	// $media = $fbxMusic->Media();
	$media->load($origFile);
	$arCodecs = ["alaw","ulaw","g722","wav"];
	
	foreach($arCodecs as $codec) {
		$fmpath = $newMohFileName.".".$codec;
		if(!file_exists($fmpath)) {
			$media->convert($fmpath);
		}
	}
	
	$db = \FreePBX::Database();
	$sql = "INSERT INTO music (`category`, `type`, `application`, `format`) VALUES ('".$uniqName."', 'files', '', '')";
	$ob = $db->query($sql);
	
	return $db->lastInsertId();
}

function addCategoryById( $id, $name, $type ) {
	$name = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $name);
	$name = preg_replace("/\s+|'+|`+|\\+|\/+|\"+|<+|>+|\?+|\*|\.+|&+|\|/","",$name);
	$name = basename($name);
	$cat = $this->getCategoryByName($name);
	if(!empty($cat)) {
		$this->message = array(
			"type" => "danger",
			"message" => _("Category Already Exists")
		);
		return;
	}
	$sql = "INSERT INTO music (`id`, `category`, `type`) VALUES (?, ?,?)";
	$sth = $this->db->prepare($sql);
	$sth->execute(array($id,$name,$type));

	if(!file_exists($this->mohpath . "/" . $name)) {
		mkdir($this->mohpath . "/" . $name);
	}
	needreload();
}