예제 #1
0
 public function ajaxHandler()
 {
     $request = $_REQUEST;
     if (!empty($_REQUEST['oldval']) && $_REQUEST['command'] == 'add') {
         $_REQUEST['command'] = 'edit';
     }
     switch ($_REQUEST['command']) {
         case 'add':
             $this->numberAdd($request);
             return array('status' => true);
             break;
         case 'edit':
             $this->numberDel($request['oldval']);
             $this->numberAdd($request);
             return array('status' => true);
             break;
         case 'bulkdelete':
             $numbers = isset($_REQUEST['numbers']) ? $_REQUEST['numbers'] : array();
             $numbers = json_decode($numbers, true);
             foreach ($numbers as $number) {
                 $this->numberDel($number);
             }
             return array('status' => 'true', 'message' => _("Numbers Deleted"));
             break;
         case 'del':
             $ret = $this->numberDel($request['number']);
             return array('status' => $ret);
             break;
         case 'calllog':
             $number = $request['number'];
             $sql = 'SELECT calldate FROM asteriskcdrdb.cdr WHERE src = ?';
             $stmt = \FreePBX::Database()->prepare($sql);
             $stmt->execute(array($number));
             $ret = $stmt->fetchAll(\PDO::FETCH_ASSOC);
             return $ret;
             break;
         case 'getJSON':
             switch ($request['jdata']) {
                 case 'grid':
                     $ret = array();
                     $blacklist = $this->getBlacklist();
                     foreach ($blacklist as $item) {
                         $number = $item['number'];
                         $description = $item['description'];
                         if ($number == 'dest' || $number == 'blocked') {
                             continue;
                         } else {
                             $ret[] = array('number' => $number, 'description' => $description);
                         }
                     }
                     return $ret;
                     break;
             }
             break;
     }
 }
예제 #2
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $helper = $this->getHelper('question');
     $output->write(_("Connecting to the Database..."));
     try {
         $db = \FreePBX::Database();
     } catch (\Exception $e) {
         $output->writeln("<error>" . _("Unable to connect to database!") . "</error>");
         return;
     }
     $output->writeln(_("Connected"));
     $driver = $db->getAttribute(\PDO::ATTR_DRIVER_NAME);
     $bundles = array();
     while (true) {
         $question = new Question($driver . '>', '');
         $question->setAutocompleterValues($bundles);
         $answer = $helper->ask($input, $output, $question);
         if (preg_match("/^exit/i", $answer)) {
             exit;
         }
         $bundles[] = $answer;
         try {
             $time_start = microtime(true);
             $ob = $db->query($answer);
             $time_end = microtime(true);
         } catch (\Exception $e) {
             $output->writeln("<error>" . $e->getMessage() . "</error>");
             continue;
         }
         if (!$ob) {
             $output->writeln("<error>" . $db->errorInfo() . "</error>");
             continue;
         }
         //if we get rows back from a query fetch them
         if ($ob->rowCount()) {
             $gotRows = $ob->fetchAll(\PDO::FETCH_ASSOC);
         } else {
             $gotRows = array();
         }
         if (!empty($gotRows)) {
             $rows = array();
             foreach ($gotRows as $row) {
                 $rows[] = array_values($row);
             }
             $table = new Table($output);
             $table->setHeaders(array_keys($gotRows[0]))->setRows($rows);
             $table->render();
             $output->writeln(sprintf(_("%s rows in set (%s sec)"), $ob->rowCount(), round($time_end - $time_start, 2)));
         } else {
             $output->writeln(_("Successfully executed"));
         }
     }
 }
예제 #3
0
 public function __construct()
 {
     $db = FreePBX::Database();
     $dash = FreePBX::Dashboard();
     if (!is_object($db)) {
         throw new Exception("DB isn't a Database?");
     }
     if (!is_object($dash)) {
         throw new Exception("Dash isn't an Object?");
     }
     $this->db = $db;
     $this->dash = $dash;
     // Generate a temporary 'what's next' array for lookups.
     foreach ($this->periods as $p => $i) {
         if ($this->last) {
             $this->pnext[$this->last] = $p;
             $this->last = $p;
         } else {
             $this->last = $p;
         }
     }
 }
예제 #4
0
FreePBX::Config()->define_conf_setting('AMPUSERMANEMAILFROM', $set, true);
//Quick check to see if we are previously installed
//this lets us know if we need to create a default group
$sql = "SELECT * FROM userman_groups";
$sth = FreePBX::Database()->prepare($sql);
try {
    $sth->execute();
    $grps = $sth->fetchAll();
} catch (\Exception $e) {
    $grps = array();
}
if (empty($grps)) {
    $sql = "INSERT INTO userman_groups (`groupname`, `description`, `users`) VALUES (?, ?, ?)";
    $sth = FreePBX::Database()->prepare($sql);
    $sth->execute(array(_("All Users"), _("This group was created on install and is automatically assigned to new users. This can be disabled in User Manager Settings"), "[]"));
    $id = FreePBX::Database()->lastInsertId();
    $config = array("default-groups" => array($id));
    FreePBX::Userman()->setConfig("authFREEPBXSettings", $config);
    //Default Group Settings
    FreePBX::Userman()->setModuleSettingByGID($id, 'contactmanager', 'show', true);
    FreePBX::Userman()->setModuleSettingByGID($id, 'contactmanager', 'groups', array($id));
    FreePBX::Userman()->setModuleSettingByGID($id, 'fax', 'enabled', true);
    FreePBX::Userman()->setModuleSettingByGID($id, 'fax', 'attachformat', "pdf");
    FreePBX::Userman()->setModuleSettingByGID($id, 'faxpro', 'localstore', "true");
    FreePBX::Userman()->setModuleSettingByGID($id, 'restapi', 'restapi_token_status', true);
    FreePBX::Userman()->setModuleSettingByGID($id, 'restapi', 'restapi_users', array("self"));
    FreePBX::Userman()->setModuleSettingByGID($id, 'restapi', 'restapi_modules', array("*"));
    FreePBX::Userman()->setModuleSettingByGID($id, 'restapi', 'restapi_rate', "1000");
    FreePBX::Userman()->setModuleSettingByGID($id, 'xmpp', 'enable', true);
    FreePBX::Userman()->setModuleSettingByGID($id, 'ucp|Global', 'allowLogin', true);
    FreePBX::Userman()->setModuleSettingByGID($id, 'ucp|Global', 'originate', true);
예제 #5
0
    foreach ($files as $file) {
        //move all custom files to the default language first
        if (preg_match("/^custom\\/(.*)/", $file, $matches)) {
            foreach (glob($dir . "/custom/" . $matches[1] . ".*") as $f) {
                $ff = basename($f);
                rename($f, $dir . "/" . $default . "/custom/" . $ff);
            }
            $filenames[] = $file;
            //if any files are using languages then remove the language since Asterisk does this for us
        } elseif (preg_match("/^(?:\\w{2}\\_\\w{2}|\\w{2}\\/)/", $file)) {
            $filenames[] = preg_replace("/^(?:\\w{2}\\_\\w{2}|\\w{2}\\/)/", "", $file);
            //Else just use the file as is
        } else {
            $filenames[] = $file;
        }
    }
    $sql = "UPDATE recordings SET filename = ? WHERE id = ?";
    $sth = FreePBX::Database()->prepare($sql);
    $sth->execute(array(implode('&', $filenames), $recording['id']));
}
if (file_exists($dir . "/custom")) {
    $files = glob($dir . "/custom/*");
    foreach ($files as $file) {
        $parts = pathinfo($file);
        FreePBX::Recordings()->addRecording($parts['filename'], "Migrated file", $file);
    }
    $files = glob($dir . "/custom/*");
    if (empty($files)) {
        rmdir($dir . "/custom");
    }
}
예제 #6
0
function paging_get_config($engine)
{
    global $db, $ext, $chan_dahdi, $version, $amp_conf, $conferences_conf;
    switch ($engine) {
        case "asterisk":
            // setup for intercom
            $fcc = new featurecode('paging', 'intercom-prefix');
            $intercom_code = $fcc->getCodeActive();
            unset($fcc);
            // Since these are going down channel local, set ALERT_INFO and SIPADDHEADER which will be set in dialparties.agi
            // no point in even setting the headers here they will get lost in channel local
            //
            /* Set these up once here and in intercom so that autoanswer macro does not have
             * to go through this for every single extension which causes a lot of extra overhead
             * with big page groups
             */
            $has_answermacro = false;
            $alertinfo = 'Ring Answer';
            $callinfo = '<uri>\\;answer-after=0';
            $sipuri = 'intercom=true';
            $doptions = 'A(beep)b(autoanswer^s^1(${ALERTINFO},${CALLINFO}))';
            $vxml_url = '';
            $dtime = '5';
            $custom_vars = array();
            $autoanswer_arr = paging_get_autoanswer_defaults();
            foreach ($autoanswer_arr as $autosetting) {
                switch (trim($autosetting['var'])) {
                    case 'ALERTINFO':
                        $alertinfo = trim($autosetting['setting']);
                        break;
                    case 'CALLINFO':
                        $callinfo = trim($autosetting['setting']);
                        break;
                    case 'SIPURI':
                        $sipuri = trim($autosetting['setting']);
                        break;
                    case 'VXML_URL':
                        $vxml_url = trim($autosetting['setting']);
                        break;
                    case 'DOPTIONS':
                        $doptions = trim($autosetting['setting']);
                        break;
                    case 'DTIME':
                        $dtime = trim($autosetting['setting']);
                        break;
                    default:
                        $key = trim($autosetting['var']);
                        $custom_vars[$key] = trim($autosetting['setting']);
                        if (ltrim($custom_vars[$key], '_') == "ANSWERMACRO") {
                            $has_answermacro = true;
                        }
                        break;
                }
            }
            $apppaging = 'app-paging';
            if (!empty($intercom_code)) {
                $code = '_' . $intercom_code . '.';
                $context = 'ext-intercom';
                // Add for languages
                $ext->add($context, 'lang-playback', '', new ext_gosubif('$[${DIALPLAN_EXISTS(' . $context . ',${CHANNEL(language)})}]', $context . ',${CHANNEL(language)},${ARG1}', $context . ',en,${ARG1}'));
                $ext->add($context, 'lang-playback', '', new ext_return());
                $ext->add($context, $code, '', new ext_macro('user-callerid'));
                $ext->add($context, $code, '', new ext_setvar('dialnumber', '${EXTEN:' . strlen($intercom_code) . '}'));
                $ext->add($context, $code, '', new ext_setvar('INTERCOM_CALL', 'TRUE'));
                $ext->add($context, $code, '', new ext_gosub('1', 's', 'sub-record-check', 'exten,${dialnumber}'));
                $ext->add($context, $code, '', new ext_gotoif('$["${DB(AMPUSER/${AMPUSER}/intercom/block)}" = "blocked"]', 'end'));
                $ext->add($context, $code, '', new ext_gotoif('$["${DB(DND/${dialnumber})}" = "YES"]', 'end'));
                $ext->add($context, $code, '', new ext_gotoif('$["${DB(AMPUSER/${dialnumber}/intercom/${AMPUSER})}" = "allow" ]', 'allow'));
                $ext->add($context, $code, '', new ext_gotoif('$["${DB(AMPUSER/${dialnumber}/intercom/${AMPUSER})}" = "deny" ]', 'nointercom'));
                $ext->add($context, $code, '', new ext_gotoif('$["${DB(AMPUSER/${dialnumber}/intercom)}" = "disabled" ]', 'nointercom'));
                $ext->add($context, $code, 'allow', new ext_dbget('DEVICES', 'AMPUSER/${dialnumber}/device'));
                $ext->add($context, $code, '', new ext_gotoif('$["${DEVICES}" = "" ]', 'end'));
                $ext->add($context, $code, '', new ext_dbget('OVERRIDE', 'AMPUSER/${dialnumber}/intercom/override'));
                $ext->add($context, $code, '', new ext_setvar('LOOPCNT', '${FIELDQTY(DEVICES,&)}'));
                /* Set these up so that macro-autoanswer doesn't have to
                 */
                $ext->add($context, $code, '', new ext_setvar('_SIPURI', ''));
                if (trim($alertinfo) != "") {
                    $ext->add($context, $code, '', new ext_setvar('_ALERTINFO', $alertinfo));
                }
                if (trim($callinfo) != "") {
                    $ext->add($context, $code, '', new ext_setvar('_CALLINFO', $callinfo));
                }
                if (trim($sipuri) != "") {
                    $ext->add($context, $code, '', new ext_setvar('_SIPURI', $sipuri));
                }
                if (trim($vxml_url) != "") {
                    $ext->add($context, $code, '', new ext_setvar('_VXML_URL', $vxml_url));
                }
                foreach ($custom_vars as $key => $value) {
                    $ext->add($context, $code, '', new ext_setvar('_' . ltrim($key, '_'), $value));
                }
                $ext->add($context, $code, '', new ext_setvar('_DTIME', $dtime));
                $ext->add($context, $code, '', new ext_setvar('_ANSWERMACRO', ''));
                $ext->add($context, $code, '', new ext_gotoif('$[${LOOPCNT} > 1 ]', 'pagemode'));
                $ext->add($context, $code, '', new ext_macro('autoanswer', '${DEVICES}'));
                $ext->add($context, $code, '', new ext_setvar('_DOPTIONS', $doptions));
                $ext->add($context, $code, 'check', new ext_chanisavail('${DEVICE}', 's'));
                // If it's ringing for an inbound call, we should page.
                $ext->add($context, $code, '', new ext_execif('$["${AVAILSTATUS}" = "6"]', 'Set', 'AVAILORIGCHAN=${DEVICE}'));
                // Did we have a device we can page? If so, go to continue. If not, check for
                // paging override functions.
                $ext->add($context, $code, '', new ext_gotoif('$["${AVAILORIGCHAN}" != ""]', 'continue'));
                // Check the intercom override.
                $ext->add($context, $code, '', new ext_execif('$["${OVERRIDE}" = ""]', 'Set', 'OVERRIDE=reject'));
                $ext->add($context, $code, '', new ext_gotoif('$["${OVERRIDE}" = "reject"]', 'end'));
                // We don't know what the phones are going to do. Let's be generous.
                $ext->add($context, $code, '', new ext_set('DTIME', '30'));
                // If it's ring, treat it as a normal call.
                $ext->add($context, $code, '', new ext_execif('$["${OVERRIDE}" = "ring"]', 'Set', 'DOPTIONS=A(beep)'));
                // It's something else. Assume it's force, and just smash the device.
                $ext->add($context, $code, 'continue', new ext_noop('Continuing with page', 5));
                $len = strlen($code) - 2;
                $dopt = 'I';
                // Don't sent connectedline updates.
                $ext->add($context, $code, '', new ext_gotoif('$["${DB(AMPUSER/${EXTEN:' . $len . '}/cidname)}" = ""]', 'godial'));
                $ext->add($context, $code, '', new ext_set('CONNECTEDLINE(name,i)', '${DB(AMPUSER/${EXTEN:' . $len . '}/cidname)}'));
                $ext->add($context, $code, '', new ext_set('CONNECTEDLINE(num)', '${EXTEN:' . $len . '}'));
                $ext->add($context, $code, 'godial', new ext_dial('${DIAL}', '${DTIME},' . $dopt . '${DOPTIONS}${INTERCOM_EXT_DOPTIONS}'));
                $ext->add($context, $code, 'end', new ext_execif('$[${INTERCOM_RETURN}]', 'Return'));
                $ext->add($context, $code, '', new ext_busy());
                $ext->add($context, $code, '', new ext_macro('hangupcall'));
                $ext->add($context, $code, 'pagemode', new ext_setvar('ITER', '1'));
                $ext->add($context, $code, '', new ext_setvar('DIALSTR', ''));
                $ds = $amp_conf['ASTCONFAPP'] == 'app_confbridge' ? '${DIALSTR}-${CUT(DEVICES,&,${ITER})}' : '${DIALSTR}&LOCAL/PAGE${CUT(DEVICES,&,${ITER})}@' . $apppaging;
                $ext->add($context, $code, 'begin', new ext_chanisavail('${DB(DEVICE/${CUT(DEVICES,&,${ITER})}/dial)}', 's'));
                $ext->add($context, $code, '', new ext_gotoif('$["${AVAILORIGCHAN}" = ""]', 'skip'));
                $ext->add($context, $code, '', new ext_setvar('DIALSTR', $ds));
                $ext->add($context, $code, 'skip', new ext_setvar('ITER', '$[${ITER} + 1]'));
                $ext->add($context, $code, '', new ext_gotoif('$[${ITER} <= ${LOOPCNT}]', 'begin'));
                $ext->add($context, $code, '', new ext_setvar('DIALSTR', '${DIALSTR:1}'));
                $ext->add($context, $code, '', new ext_gotoif('$["${DIALSTR}" = ""]', 'end2'));
                $ext->add($context, $code, '', new ext_setvar('_AMPUSER', '${AMPUSER}'));
                if ($amp_conf['ASTCONFAPP'] == 'app_confbridge') {
                    $ext->add($context, $code, '', new ext_gosub('1', 'page', false, '${DIALSTR}'));
                } else {
                    $ext->add($context, $code, '', new ext_page('${DIALSTR},d'));
                }
                $ext->add($context, $code, 'end2', new ext_execif('$[${INTERCOM_RETURN}]', 'Return'));
                $ext->add($context, $code, '', new ext_busy());
                $ext->add($context, $code, '', new ext_macro('hangupcall'));
                $ext->add($context, $code, 'nointercom', new ext_noop('Intercom disallowed by ${dialnumber}'));
                $ext->add($context, $code, '', new ext_execif('$[${INTERCOM_RETURN}]', 'Return'));
                $ext->add($context, $code, '', new ext_gosub('1', 'lang-playback', $context, 'hook_0'));
                $ext->add($context, $code, '', new ext_congestion());
                if ($amp_conf['ASTCONFAPP'] == 'app_confbridge') {
                    $sub = 'page';
                    $ext->add($context, $sub, '', new ext_set('PAGE_CONF', '${EPOCH}${RAND(100,999)}'));
                    $ext->add($context, $sub, '', new ext_set('PAGEMODE', 'PAGE'));
                    $ext->add($context, $sub, '', new ext_set('PAGE_MEMBERS', '${ARG1}'));
                    $ext->add($context, $sub, '', new ext_set('PAGE_CONF_OPTS', 'duplex'));
                    $ext->add($context, $sub, '', new ext_agi('page.agi'));
                    $ext->add($context, $sub, '', new ext_set('CONFBRIDGE(user,template)', 'page_user_duplex'));
                    $ext->add($context, $sub, '', new ext_set('CONFBRIDGE(user,admin)', 'yes'));
                    $ext->add($context, $sub, '', new ext_set('CONFBRIDGE(user,marked)', 'yes'));
                    $ext->add($context, $sub, '', new ext_meetme('${PAGE_CONF}', ',', 'admin_menu'));
                    $ext->add($context, $sub, '', new ext_hangup());
                }
                $lang = 'en';
                // English
                $ext->add($context, $lang, 'hook_0', new ext_playback('intercom&for&extension'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_playback('is&disabled'));
                $ext->add($context, $lang, '', new ext_return());
                $lang = 'ja';
                // Japanese
                $ext->add($context, $lang, 'hook_0', new ext_playback('extension'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_playback('jp-no&intercom&jp-wa&disabled-2'));
                $ext->add($context, $lang, '', new ext_return());
                $extintercomusers = 'ext-intercom-users';
                $sql = "SELECT LENGTH(id) as len FROM devices GROUP BY len";
                $sth = FreePBX::Database()->prepare($sql);
                $sth->execute();
                $rows = $sth->fetchAll(\PDO::FETCH_ASSOC);
                foreach ($rows as $row) {
                    $ext->add($extintercomusers, '_' . $intercom_code . str_repeat('X', $row['len']), '', new ext_goto($context . ',${EXTEN},1'));
                }
                $context = $extintercomusers;
                // for language handling which is done on a per context basis
                $ext->add($context, 'lang-playback', '', new ext_gosubif('$[${DIALPLAN_EXISTS(' . $context . ',${CHANNEL(language)})}]', $context . ',${CHANNEL(language)},${ARG1}', $context . ',en,${ARG1}'));
                $ext->add($context, 'lang-playback', '', new ext_return());
                $ext->addInclude('from-internal-additional', $context);
            }
            $fcc = new featurecode('paging', 'intercom-on');
            $oncode = $fcc->getCodeActive();
            unset($fcc);
            if ($oncode) {
                $ext->add($context, $oncode, '', new ext_macro('user-callerid'));
                $ext->add($context, $oncode, '', new ext_set('CONNECTEDLINE(name-charset,i)', 'utf8'));
                $ext->add($context, $oncode, '', new ext_set('CONNECTEDLINE(name,i)', _("Intercom: Enabled")));
                $ext->add($context, $oncode, '', new ext_set('CONNECTEDLINE(num,i)', '${AMPUSER}'));
                $ext->add($context, $oncode, '', new ext_answer(''));
                $ext->add($context, $oncode, '', new ext_wait('1'));
                $ext->add($context, $oncode, '', new ext_setvar('DB(AMPUSER/${AMPUSER}/intercom)', 'enabled'));
                $ext->add($context, $oncode, '', new ext_playback('intercom&enabled'));
                $ext->add($context, $oncode, '', new ext_macro('hangupcall'));
                $target = '${EXTEN:' . strlen($oncode) . '}';
                $oncode = "_" . $oncode . ".";
                $ext->add($context, $oncode, '', new ext_macro('user-callerid'));
                $ext->add($context, $oncode, '', new ext_set('CONNECTEDLINE(name-charset,i)', 'utf8'));
                $ext->add($context, $oncode, '', new ext_set('CONNECTEDLINE(name,i)', sprintf(_("Intercom from %s: Enabled"), $target)));
                $ext->add($context, $oncode, '', new ext_set('CONNECTEDLINE(num,i)', '${AMPUSER}'));
                $ext->add($context, $oncode, '', new ext_setvar('dialnumber', '${EVAL(${EXTEN:' . strlen(substr($oncode, 1, -1)) . '})}'));
                // Asterisk variable for saydigits languages
                $ext->add($context, $oncode, '', new ext_answer(''));
                $ext->add($context, $oncode, '', new ext_wait('1'));
                $ext->add($context, $oncode, '', new ext_gotoif('$["${DB(AMPUSER/${AMPUSER}/intercom/' . $target . ')}" = "allow" ]}', 'unset'));
                $ext->add($context, $oncode, '', new ext_gotoif('$[${DB_EXISTS(AMPUSER/' . $target . '/device)} != 1]', 'invaliduser'));
                $ext->add($context, $oncode, '', new ext_dbput('AMPUSER/${AMPUSER}/intercom/' . $target, 'allow'));
                $ext->add($context, $oncode, '', new ext_gosub('1', 'lang-playback', $context, 'hook_1'));
                $ext->add($context, $oncode, '', new ext_macro('hangupcall'));
                $ext->add($context, $oncode, 'unset', new ext_dbdeltree('AMPUSER/${AMPUSER}/intercom/' . $target));
                $ext->add($context, $oncode, '', new ext_gosub('1', 'lang-playback', $context, 'hook_2'));
                $ext->add($context, $oncode, '', new ext_macro('hangupcall'));
                $ext->add($context, $oncode, 'invaliduser', new ext_gosub('1', 'lang-playback', $context, 'hook_3'));
                $ext->add($context, $oncode, '', new ext_macro('hangupcall'));
                $lang = 'en';
                // English
                $ext->add($context, $lang, 'hook_1', new ext_playback('intercom&from&extension&number'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_playback('enabled'));
                $ext->add($context, $lang, '', new ext_return());
                $ext->add($context, $lang, 'hook_2', new ext_playback('intercom&enabled&cancelled&for&extension&number'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_return());
                $ext->add($context, $lang, 'hook_3', new ext_playback('extension&number'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_playback('invalid'));
                $ext->add($context, $lang, '', new ext_return());
                $lang = 'ja';
                // Japanese
                $ext->add($context, $lang, 'hook_1', new ext_playback('extension'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_playback('jp-kara&jp-no&intercom&jp-wo&allow'));
                $ext->add($context, $lang, '', new ext_return());
                $ext->add($context, $lang, 'hook_2', new ext_playback('extension'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_playback('jp-kara&jp-no&intercom&setting&jp-wo&cancelled'));
                $ext->add($context, $lang, '', new ext_return());
                $ext->add($context, $lang, 'hook_3', new ext_playback('extension'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_playback('invalid'));
                $ext->add($context, $lang, '', new ext_return());
            }
            $fcc = new featurecode('paging', 'intercom-off');
            $offcode = $fcc->getCodeActive();
            unset($fcc);
            if ($offcode) {
                $ext->add($context, $offcode, '', new ext_macro('user-callerid'));
                $ext->add($context, $offcode, '', new ext_set('CONNECTEDLINE(name-charset,i)', 'utf8'));
                $ext->add($context, $offcode, '', new ext_set('CONNECTEDLINE(name,i)', _("Intercom: Disabled")));
                $ext->add($context, $offcode, '', new ext_set('CONNECTEDLINE(num,i)', '${AMPUSER}'));
                $ext->add($context, $offcode, '', new ext_answer(''));
                $ext->add($context, $offcode, '', new ext_wait('1'));
                $ext->add($context, $offcode, '', new ext_setvar('DB(AMPUSER/${AMPUSER}/intercom)', 'disabled'));
                $ext->add($context, $offcode, '', new ext_playback('intercom&disabled'));
                $ext->add($context, $offcode, '', new ext_macro('hangupcall'));
                $target = '${EXTEN:' . strlen($offcode) . '}';
                $offcode = "_" . $offcode . ".";
                $ext->add($context, $offcode, '', new ext_macro('user-callerid'));
                $ext->add($context, $offcode, '', new ext_set('CONNECTEDLINE(name-charset,i)', 'utf8'));
                $ext->add($context, $offcode, '', new ext_set('CONNECTEDLINE(name,i)', sprintf(_("Intercom from %s: Disabled"), $target)));
                $ext->add($context, $offcode, '', new ext_set('CONNECTEDLINE(num,i)', '${AMPUSER}'));
                $ext->add($context, $offcode, '', new ext_setvar('dialnumber', '${EVAL(${EXTEN:' . strlen(substr($offcode, 1, -1)) . '})}'));
                // Asterisk variable for saydigits languages
                $ext->add($context, $offcode, '', new ext_answer(''));
                $ext->add($context, $offcode, '', new ext_wait('1'));
                $ext->add($context, $offcode, '', new ext_gotoif('$["${DB(AMPUSER/${AMPUSER}/intercom/' . $target . ')}" = "deny" ]}', 'unset2'));
                $ext->add($context, $offcode, '', new ext_gotoif('$[${DB_EXISTS(AMPUSER/' . $target . '/device)} != 1]', 'invaliduser2'));
                $ext->add($context, $offcode, '', new ext_dbput('AMPUSER/${AMPUSER}/intercom/' . $target, 'deny'));
                $ext->add($context, $offcode, '', new ext_gosub('1', 'lang-playback', $context, 'hook_4'));
                $ext->add($context, $offcode, '', new ext_macro('hangupcall'));
                $ext->add($context, $offcode, 'unset2', new ext_dbdeltree('AMPUSER/${AMPUSER}/intercom/' . $target));
                $ext->add($context, $offcode, '', new ext_gosub('1', 'lang-playback', $context, 'hook_5'));
                $ext->add($context, $offcode, '', new ext_macro('hangupcall'));
                $ext->add($context, $offcode, 'invaliduser2', new ext_gosub('1', 'lang-playback', $context, 'hook_6'));
                $ext->add($context, $offcode, '', new ext_macro('hangupcall'));
                $lang = 'en';
                $ext->add($context, $lang, 'hook_4', new ext_playback('intercom&from&extension&number'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_playback('disabled'));
                $ext->add($context, $lang, '', new ext_return());
                $ext->add($context, $lang, 'hook_5', new ext_playback('intercom&disabled&cancelled&for&extension&number'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_return());
                $ext->add($context, $lang, 'hook_6', new ext_playback('extension&number'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_playback('invalid'));
                $ext->add($context, $lang, '', new ext_return());
                $lang = 'ja';
                $ext->add($context, $lang, 'hook_4', new ext_playback('extension'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_playback('jp-kara&jp-no&intercom&jp-wo&deny'));
                $ext->add($context, $lang, '', new ext_return());
                $ext->add($context, $lang, 'hook_5', new ext_playback('extension'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_playback('jp-kara&jp-no&intercom&setting&jp-wo&cancelled'));
                $ext->add($context, $lang, '', new ext_return());
                $ext->add($context, $lang, 'hook_6', new ext_playback('extension'));
                $ext->add($context, $lang, '', new ext_saydigits('${dialnumber}'));
                $ext->add($context, $lang, '', new ext_playback('invalid'));
                $ext->add($context, $lang, '', new ext_return());
            }
            /* Create macro-autoanswer that will try to intelligently set the
            			required parameters to handle paging. Eventually it will use
            				known device information.
            
            				This macro does the following:
            
            				Input:  FreePBX Device number to be called requiring autoanswer
            				Output: ${DIAL} Channel Variable with the dial string to be called
            						Appropriate SIP headers added
            								Other special requirements that may be custom for this device
            
            				1. Set ${DIAL} to the device's dial string
            				2. If there is a device specific macro defined in the DEVICE's object
            				   (DEVICE/<devicenum>/autoanswer/macro) then execute that macro and end
            				3. Try to identify endpoints by their useragents that may need known
            				   changes and make those changes. These are generated from the
            					 paging_autoanswer table so users can extend them, if any are present
            				5. Set the variables and end unless a useragent specific ANSWERMACRO is
            				   defined in which case call it and end.
            
            				This macro is called for intercoming and paging to try and enable the
            				target device to auto-answer. Devices with special needs can be handled
            				with the device specific macro. For example, if you have a device that
            				can not auto-answer except by specifically configuring a line key on
            				the device that always answers, you could use a device specific macro
            				to change the dialstring. If you had a set of such devices, you could
            				standardize on the device numbers (e.g. nnnn for normal calls and 2nnnn
            				for auto-answer calls). You could then create a general purpose macro
            				to modify the dial string accordingly. Provisioning tools will be able
            				to take advantage of setting and creating such an ability.
            				If you have a set of devices that can be identified with a SIP useragent
            				then you can use a general macro without setting info in each device.
            			 */
            $autoanswer_arr = paging_get_autoanswer_useragents();
            $macro = 'macro-autoanswer';
            // Do we already know what the correct string is? This may have been handed to us
            // by page.agi.
            $ext->add($macro, "s", '', new ext_gotoif('$["${KNOWNDIAL}" != ""]', 'knowndial'));
            // Do we have a PJSIP Endpoint?
            $ext->add($macro, "s", '', new ext_setvar('DEVICE', '${DB(DEVICE/${ARG1}/dial)}'));
            $ext->add($macro, "s", '', new ext_gotoif('$["${DEVICE:0:5}" == "PJSIP" ]', 'dopjsip'));
            // We're not pjsip, so our dial is going to be our device
            $ext->add($macro, "s", '', new ext_setvar('KNOWNDIAL', '${DEVICE}'));
            $ext->add($macro, "s", '', new ext_goto('knowndial'));
            // Handle PJSIP stuff.
            $ext->add($macro, "s", 'dopjsip', new ext_setvar('KNOWNDIAL', '${PJSIP_DIAL_CONTACTS(${ARG1})}'));
            // If there's an ampersand, there's more than one device registered to this endpoint, and we
            // need to page, rather than intercom.
            $ext->add($macro, "s", '', new ext_gotoif('$[${REGEX("&" ${KNOWNDIAL})} == 0]', 'knowndial'));
            // Bugger. However, we can hard-code some settings here that'll make our life a bit easier.
            $ext->add($macro, "s", '', new ext_gosub('1', 'ssetup', 'app-paging'));
            $ext->add($macro, "s", '', new ext_setvar('PAGEMODE', 'PAGE'));
            $ext->add($macro, "s", '', new ext_setvar('PAGE_CONF_OPTS', 'duplex'));
            $ext->add($macro, "s", '', new ext_setvar('STREAM', 'NONE'));
            $ext->add($macro, "s", '', new ext_setvar('PAGE_MEMBERS', '${ARG1}'));
            // Start the AGI to get the clients into the conf
            $ext->add($macro, "s", '', new ext_agi('page.agi'));
            // Now I need to join the conf as admin.
            $ext->add($macro, "s", '', new ext_set('CONFBRIDGE(user,template)', 'page_user_duplex'));
            $ext->add($macro, "s", '', new ext_set('CONFBRIDGE(user,admin)', 'yes'));
            $ext->add($macro, "s", '', new ext_set('CONFBRIDGE(user,marked)', 'yes'));
            $ext->add($macro, "s", '', new ext_meetme('${PAGE_CONF}', ',', 'admin_menu'));
            // ext_confbridge, actually.
            $ext->add($macro, "s", '', new ext_hangup());
            // Don't even try to continue after this.
            // Right. Bypassing all that, it's a single device, and, we know what our dial string is.
            $ext->add($macro, "s", 'knowndial', new ext_setvar('DIAL', '${KNOWNDIAL}'));
            // If we are in DAHDI compat mode, then we need to substitute DAHDI for ZAP
            if ($chan_dahdi) {
                $ext->add($macro, "s", '', new ext_execif('$["${DIAL:0:3}" = "ZAP"]', 'Set', 'DIAL=DAHDI${DIAL:3}'));
            }
            $ext->add($macro, "s", '', new ext_gotoif('$["${DB(DEVICE/${ARG1}/autoanswer/macro)}" != "" ]', 'macro'));
            // If there are no phone specific auto-answer vars, then we don't care what the phone is below
            //
            if (!empty($autoanswer_arr)) {
                global $version;
                $ext->add($macro, "s", '', new ext_gotoif('$["${DIAL:0:5}" = "PJSIP"]', 'pjsipua'));
                //http://issues.freepbx.org/browse/FREEPBX-7715
                if (version_compare($version, "12", "<")) {
                    $ext->add($macro, "s", '', new ext_setvar('USERAGENT', '${SIPPEER(${CUT(DIAL,/,2)}:useragent)}'));
                } else {
                    $ext->add($macro, "s", '', new ext_setvar('USERAGENT', '${SIPPEER(${CUT(DIAL,/,2)},useragent)}'));
                }
                $ext->add($macro, "s", '', new ext_goto('uafin'));
                $ext->add($macro, "s", 'pjsipua', new ext_setvar('AOR', '${CUT(DIAL,/,2)}'));
                $ext->add($macro, "s", '', new ext_setvar('CONTACT', '${PJSIP_AOR(${AOR},contact)}'));
                $ext->add($macro, "s", '', new ext_setvar('USERAGENT', '${PJSIP_CONTACT(${CONTACT},user_agent)}'));
                $ext->add($macro, "s", 'uafin', new ext_execif('$["${KNOWNAGENT}" != ""]', 'Set', 'USERAGENT=${KNOWNAGENT}'));
            }
            // We used to set all the variables here (ALERTINFO, CALLINFO, etc. That has been moved to each
            // paging group and the intercom main macro, since it was redundant for every phone causing a lot
            // of overhead with large page groups.
            //
            // Defaults are setup, now make specific adjustments for detected phones
            // These come from the SQL table as well where installations can make customizations
            //
            foreach ($autoanswer_arr as $autosetting) {
                $useragent = trim($autosetting['useragent']);
                $autovar = trim($autosetting['var']);
                $data = trim($autosetting['setting']);
                switch (ltrim($autovar, '_')) {
                    case 'ANSWERMACRO':
                        $has_answermacro = true;
                        // fall through - no break on purpose
                    // fall through - no break on purpose
                    case 'ALERTINFO':
                    case 'CALLINFO':
                    case 'SIPURI':
                    case 'VXML_URL':
                    case 'DOPTIONS':
                    case 'DTIME':
                    default:
                        if (trim($data) != "") {
                            $ext->add($macro, "s", '', new ext_execif('$["${USERAGENT:0:' . strlen($useragent) . '}" = "' . $useragent . '"]', 'Set', $autovar . '=' . $data));
                        }
                        break;
                }
            }
            // Now any adjustments have been made, set the headers and done
            //
            if ($has_answermacro) {
                $ext->add($macro, "s", '', new ext_gotoif('$["${ANSWERMACRO}" != ""]', 'macro2'));
            }
            $ext->add($macro, "s", '', new ext_execif('$["${SIPURI}" != ""]', 'Set', '__SIP_URI_OPTIONS=${SIPURI}'));
            $ext->add($macro, "s", 'macro', new ext_macro('${DB(DEVICE/${ARG1}/autoanswer/macro)}', '${ARG1}'), 'n', 2);
            if ($has_answermacro) {
                $ext->add($macro, "s", 'macro2', new ext_macro('${ANSWERMACRO}', '${ARG1}'), 'n', 2);
            }
            //auto answer stuff
            //set autoanswer variables
            if (!empty($custom_vars)) {
                foreach ($custom_vars as $key => $value) {
                    $ext->add($apppaging, '_AUTOASWER.', '', new ext_setvar('_' . ltrim($key, '_'), $value));
                }
                $ext->add($apppaging, '_AUTOASWER.', '', new ext_macro('autoanswer', '${EXTEN:9}'));
                $ext->add($apppaging, '_AUTOASWER.', '', new ext_return());
            }
            // Macro to apply SIP Headers to channel.
            //   function ext_gosubif($condition, $true_priority, $false_priority = false, $true_args = '', $false_args = '') {
            //
            $ext->add("autoanswer", "s", '', new ext_gosubif('$["${ARG1}" != ""]', 'func-set-sipheader,s,1', false, 'Alert-Info,${ARG1}'));
            $ext->add("autoanswer", "s", '', new ext_gosubif('$["${ARG2}" != ""]', 'func-set-sipheader,s,1', false, 'Call-Info,${ARG2}'));
            $ext->add("autoanswer", "s", '', new ext_gosub('func-apply-sipheaders,s,1'));
            $ext->add("autoanswer", "s", '', new ext_return());
            // Setup Variables before AGI script
            //
            $ext->add($apppaging, 'ssetup', '', new ext_set('_SIPURI', ''));
            if (isset($alertinfo) && trim($alertinfo) != "") {
                $ext->add($apppaging, 'ssetup', '', new ext_set('_ALERTINFO', $alertinfo));
            }
            if (isset($callinfo) && trim($callinfo) != "") {
                $ext->add($apppaging, 'ssetup', '', new ext_set('_CALLINFO', $callinfo));
            }
            if (isset($sipuri) && trim($sipuri) != "") {
                $ext->add($apppaging, 'ssetup', '', new ext_set('_SIPURI', $sipuri));
            }
            if (isset($vxml_url) && trim($vxml_url) != "") {
                $ext->add($apppaging, 'ssetup', '', new ext_set('_VXML_URL', $vxml_url));
            }
            $ext->add($apppaging, 'ssetup', '', new ext_set('_DTIME', $dtime));
            $ext->add($apppaging, 'ssetup', '', new ext_set('_ANSWERMACRO', ''));
            $page_opts = $amp_conf['ASTCONFAPP'] == 'app_confbridge' ? '1qs' : '1dqsx';
            $ext->add($apppaging, 'ssetup', '', new ext_set('PAGE_CONF', '${EPOCH}${RAND(100,999)}'));
            $ext->add($apppaging, 'ssetup', '', new ext_return());
            // Normal page version (now used for Force also)
            // If we had any custom_vars then call the AUTOASWER subroutine first, otherwise go
            // straight to macro-autoanswer
            if (!empty($custom_vars)) {
                $ext->add($apppaging, "_PAGE.", 'SKIPCHECK', new ext_gosub('AUTOASWER${EXTEN:4},1'));
            } else {
                $ext->add($apppaging, "_PAGE.", 'SKIPCHECK', new ext_macro('autoanswer', '${EXTEN:4}'));
            }
            $ext->add($apppaging, "_PAGE.", '', new ext_noop('${EXTRINGTIME}'));
            $ext->add($apppaging, "_PAGE.", '', new ext_gotoif('$["${EXTRINGTIME}" != "true"]', 'doptions'));
            $ext->add($apppaging, "_PAGE.", '', new ext_set('_DTIME', '${RINGTIMER_DEFAULT}'));
            $ext->add($apppaging, "_PAGE.", '', new ext_execif('$["${DB(AMPUSER/${EXTEN:4}/ringtimer)}" != "" & ${DB(AMPUSER/${EXTEN:4}/ringtimer)} > 0]', 'Set', '_DTIME=${DB(AMPUSER/${EXTEN:4}/ringtimer)}'));
            //strip the global Announcement out of doptions (We use our announcement variable lower --V)
            $doptions2 = preg_replace("/A\\([^\\)]*\\)/", "", $doptions);
            $ext->add($apppaging, "_PAGE.", 'doptions', new ext_execif('$["${DOPTIONS}" = ""]', 'Set', '_DOPTIONS=' . $doptions2));
            $ext->add($apppaging, "_PAGE.", '', new ext_dial('${DIAL}', '${DTIME},A(${ANNOUNCEMENT})${DOPTIONS}'));
            $ext->add($apppaging, "_PAGE.", 'skipself', new ext_hangup());
            // Try ChanSpy Version
            $ext->add($apppaging, "_SPAGE.", 'chanspy', new ext_chanspy('${SP_DEVICE}-', 'qW'));
            $ext->add($apppaging, "_SPAGE.", '', new ext_hangup());
            // If Asterisk 10 and app_confbridge:
            //
            // Common to admin:
            //  d: dynamically addd conf
            //  o: talker optimization (don't mix non-talkers)
            //  q: quiet mode no enter/leave sounds
            //  x: close conf when last marked user exits
            //
            // Not in Admin:
            //  1: ???
            //  s: present menu
            //See http://issues.freepbx.org/browse/FREEPBX-8796
            //before you even think about removing this to after checking for a page group!
            if ($amp_conf['ASTCONFAPP'] == 'app_confbridge' && isset($conferences_conf) && is_a($conferences_conf, "conferences_conf")) {
                $pu = 'page_user';
                $pud = 'page_user_duplex';
                foreach (array($pu, $pud) as $u) {
                    $conferences_conf->addConfUser($u, 'quiet', 'yes');
                    $conferences_conf->addConfUser($u, 'announce_user_count', 'no');
                    $conferences_conf->addConfUser($u, 'wait_marked', 'yes');
                    $conferences_conf->addConfUser($u, 'end_marked', 'yes');
                    $dds = \FreePBX::Paging()->getDropSilence() ? 'yes' : 'no';
                    $conferences_conf->addConfUser($u, 'dsp_drop_silence', $dds);
                    $conferences_conf->addConfUser($u, 'announce_join_leave', 'no');
                    $conferences_conf->addConfUser($u, 'admin', 'no');
                    $conferences_conf->addConfUser($u, 'marked', 'no');
                }
                $conferences_conf->addConfUser($pu, 'startmuted', 'yes');
            }
            //page playback
            $c = 'app-page-stream';
            $ext->add($c, 's', '', new ext_wait(1));
            $ext->add($c, 's', '', new ext_answer());
            // TODO: PAGE_CONF_OPTS reset in agi script so just use proper context if 10+confbridge no mute
            // x: close conf when last marked user exits
            // q: quiet mode no enter/leave sounds
            //
            // TODO: Ideally what we want is to mark the stream and wait for that, if no stream then no wait for makred user. However
            //       it seems like to end a conference you have to have the kick after last marked user since there doesn't have to be
            //       an admin as far as I can tell.
            //
            //
            if ($amp_conf['ASTCONFAPP'] == 'app_confbridge') {
                $ext->add($c, 's', '', new ext_set('CONFBRIDGE(user,template)', $pud));
                $ext->add($c, 's', '', new ext_set('CONFBRIDGE(user,marked)', 'yes'));
                $ext->add($c, 's', '', new ext_meetme('${PAGE_CONF}', '', ''));
            } else {
                $ext->add($c, 's', '', new ext_meetme('${PAGE_CONF}', '${PAGE_CONF_OPTS}'));
            }
            $ext->add($c, 's', '', new ext_hangup());
            $apppagegroups = 'app-pagegroups';
            // Now get a list of all the paging groups...
            $sql = "SELECT page_group, force_page, duplex, announcement FROM paging_config";
            $paging_groups = $db->getAll($sql, DB_FETCHMODE_ASSOC);
            if (!$paging_groups) {
                break;
                //no need to continue if we dont have any pagegroups
            }
            $extpaging = 'ext-paging';
            if (!empty($paging_groups)) {
                $ext->addInclude('from-internal-noxfer-additional', $extpaging);
            }
            foreach ($paging_groups as $thisgroup) {
                $grp = trim($thisgroup['page_group']);
                switch ($thisgroup['force_page']) {
                    case 1:
                        $pagemode = 'FPAGE';
                        break;
                    case 2:
                        $pagemode = 'SPAGE';
                        break;
                    case 0:
                    default:
                        $pagemode = 'PAGE';
                        break;
                }
                $sql = "SELECT ext FROM paging_groups WHERE page_number='{$grp}'";
                $all_exts = $db->getCol($sql);
                // Create the paging context that is used in the paging application for each phone to auto-answer
                //add ext-paging with goto's to our app-paging context and a hint for the page
                $ext->add($extpaging, $grp, '', new ext_goto($apppagegroups . ',' . $grp . ',1'));
                $ext->addHint($extpaging, $grp, 'Custom:PAGE' . $grp);
                //app-page dialplan
                $ext->add($apppagegroups, $grp, '', new ext_macro('user-callerid'));
                $ext->add($apppagegroups, $grp, '', new ext_set('_PAGEGROUP', $grp));
                //if page group it in use, goto to busy
                $ext->add($apppagegroups, $grp, 'busy-check', new ext_gotoif('$[${TRYLOCK(apppagegroups' . $grp . ')}]', '', 'busy'));
                //set blf to in use
                $ext->add($apppagegroups, $grp, 'devstate', new ext_setvar('DEVICE_STATE(Custom:PAGE' . $grp . ')', 'INUSE'));
                $ext->add($apppagegroups, $grp, '', new ext_gosub('1', 'ssetup', $apppaging));
                $ext->add($apppagegroups, $grp, '', new ext_set('PAGEMODE', $pagemode));
                $ext->add($apppagegroups, $grp, '', new ext_set('PAGE_MEMBERS', implode('-', $all_exts)));
                if ($amp_conf['ASTCONFAPP'] == 'app_confbridge') {
                    $ext->add($apppagegroups, $grp, '', new ext_set('PAGE_CONF_OPTS', $thisgroup['duplex'] ? 'duplex' : ''));
                } else {
                    $ext->add($apppagegroups, $grp, '', new ext_set('PAGE_CONF_OPTS', $page_opts . (!$thisgroup['duplex'] ? 'm' : '')));
                }
                //Default announcement is a beep
                $announcement = "beep";
                //extract our "global default announcement" from the doptions and set it to announcement
                if (preg_match("/A\\(([^\\)]*)\\)/", $doptions, $matches)) {
                    $announcement = isset($matches[1]) ? $matches[1] : "";
                }
                //get our individual page group announcement if set
                if (!empty($thisgroup['announcement'])) {
                    switch ($thisgroup['announcement']) {
                        case "beep":
                            $announcement = "beep";
                            break;
                        case "none":
                            $announcement = "";
                            break;
                        case "default":
                            //do nothing
                            break;
                        default:
                            if (function_exists('recordings_get_file')) {
                                $announcement = recordings_get_file($thisgroup['announcement']);
                            } else {
                                $announcement = "";
                            }
                            break;
                    }
                }
                $ext->add($apppagegroups, $grp, '', new ext_set('ANNOUNCEMENT', $announcement));
                $ext->add($apppagegroups, $grp, 'agi', new ext_agi('page.agi'));
                //we cant use originate from the dialplan as the dialplan command is not asynchronous
                //we would like to though...
                //this code here as a sign of hope -MB
                /*foreach ($page_members as $member) {
                				$ext->add($apppagegroups, $grp, 'page', new ext_originate($member,'app','meetme', '${PAGE_CONF}\,${PAGE_CONF_OPTS}'));
                		}*/
                // TODO this is the master so set appropriate
                //      This is what everyone else has: 1doqsx
                //      Common:
                //        d: dynamically addd conf
                //        o: talker optimization (don't mix non-talkers)
                //        q: quiet mode no enter/leave sounds
                //        x: close conf when last marked user exits
                //      Added:
                //      	w: W() wait until marked user enters conf
                //      	A: Set marked mode
                //      	G: G() Play an intro announcemend in conference
                //      Removed:
                //        1: ???
                //        s: present menu
                //
                //
                if ($amp_conf['ASTCONFAPP'] == 'app_confbridge') {
                    $ext->add($apppagegroups, $grp, '', new ext_set('CONFBRIDGE(user,template)', $pud));
                    $ext->add($apppagegroups, $grp, '', new ext_set('CONFBRIDGE(user,admin)', 'yes'));
                    $ext->add($apppagegroups, $grp, '', new ext_set('CONFBRIDGE(user,marked)', 'yes'));
                    // TODO: should I have no menu?
                    $ext->add($apppagegroups, $grp, '', new ext_answer(''));
                    $ext->add($apppagegroups, $grp, 'page', new ext_meetme('${PAGE_CONF}', ',', 'admin_menu'));
                } else {
                    $ext->add($apppagegroups, $grp, '', new ext_answer(''));
                    $ext->add($apppagegroups, $grp, 'page', new ext_meetme('${PAGE_CONF}', 'dqwxAG'));
                }
                $ext->add($apppagegroups, $grp, '', new ext_hangup());
                $ext->add($apppagegroups, $grp, 'busy', new ext_set('PAGE${PAGEGROUP}BUSY', 'TRUE'));
                $ext->add($apppagegroups, $grp, 'play-busy', new ext_busy(3));
                $ext->add($apppagegroups, $grp, 'busy-hang', new ext_goto('app-pagegroups,h,1'));
            }
            //h
            $ext->add($apppagegroups, 'h', '', new ext_execif('$[${ISNULL(${PAGE${PAGEGROUP}BUSY})}]', 'Set', 'DEVICE_STATE(Custom:PAGE${PAGEGROUP})=NOT_INUSE'));
            break;
    }
}
예제 #7
0
 private function isFrameworkOOBENeeded()
 {
     $db = FreePBX::Database();
     $count = (int) $db->query("SELECT COUNT(`username`) FROM `ampusers`")->fetchColumn();
     if ($count !== 0) {
         return false;
     }
     return true;
 }
예제 #8
0
function queues_get_config($engine)
{
    global $ext;
    // is this the best way to pass this?
    global $amp_conf;
    global $version;
    $queues_conf = queues_conf::create();
    switch ($engine) {
        case "asterisk":
            global $astman;
            //set our reset cron
            queues_set_backup_cron();
            $ast_ge_14 = version_compare($version, '1.4', 'ge');
            $ast_ge_16 = version_compare($version, '1.6', 'ge');
            $ast_ge_14_25 = version_compare($version, '1.4.25', 'ge');
            $ast_ge_18 = version_compare($version, '1.8', 'ge');
            $ast_ge_11 = version_compare($version, '11', 'ge');
            $ast_ge_12 = version_compare($version, '12', 'ge');
            $has_extension_state = $ast_ge_16;
            if ($ast_ge_14 && !$ast_ge_16) {
                $response = $astman->send_request('Command', array('Command' => 'module show like func_extstate'));
                if (preg_match('/1 modules loaded/', $response['data'])) {
                    $has_extension_state = true;
                }
            }
            if (isset($queues_conf) && is_a($queues_conf, "queues_conf")) {
                $queues_conf->addQueuesGeneral('persistentmembers', $amp_conf['QUEUES_PESISTENTMEMBERS'] ? 'yes' : 'no');
                if ($ast_ge_16) {
                    $queues_conf->addQueuesGeneral('shared_lastcall', $amp_conf['QUEUES_SHARED_LASTCALL'] ? 'yes' : 'no');
                    $queues_conf->addQueuesGeneral('updatecdr', $amp_conf['QUEUES_UPDATECDR'] ? 'yes' : 'no');
                }
                if ($amp_conf['QUEUES_MIX_MONITOR']) {
                    $queues_conf->addQueuesGeneral('monitor-type', 'MixMonitor');
                }
            }
            /* queue extensions */
            $ext->addInclude('from-internal-additional', 'ext-queues');
            /* Trial DEVSTATE */
            $ext->addGlobal('QUEDEVSTATE', 'TRUE');
            $qlist = queues_list(true);
            if (empty($qlist)) {
                return;
                //nothing to do if we dont have any queues
            }
            // $que_code = '*45';
            $fcc = new featurecode('queues', 'que_toggle');
            $que_code = $fcc->getCodeActive();
            unset($fcc);
            if ($que_code != '') {
                queue_app_toggle();
                queue_app_all_toggle();
                queue_agent_del_toggle();
                queue_agent_add_toggle();
                $ext->addGlobal('QUEUETOGGLE', $que_code);
            }
            // $que_pause_code = '*46';
            $fcc = new featurecode('queues', 'que_pause_toggle');
            $que_pause_code = $fcc->getCodeActive();
            unset($fcc);
            if ($que_pause_code != '') {
                app_queue_pause_toggle();
                app_all_queue_pause_toggle();
                $ext->addGlobal('QUEUEPAUSETOGGLE', $que_pause_code);
            }
            // $que_callers_code = '*47';
            $fcc = new featurecode('queues', 'que_callers');
            $que_callers_code = $fcc->getCodeActive();
            unset($fcc);
            $from_queue_exten_only = 'from-queue-exten-only';
            $from_queue_exten_internal = 'from-queue-exten-internal';
            $qmembers = array();
            $hint_hash = array();
            $qlist = is_array($qlist) ? $qlist : array();
            foreach ($qlist as $item) {
                $exten = $item[0];
                $q = queues_get($exten);
                $c = 'ext-queues';
                $grppre = isset($q['prefix']) ? $q['prefix'] : '';
                $alertinfo = isset($q['alertinfo']) ? $q['alertinfo'] : '';
                // Not sure why someone would ever have a ; in the regex, but since Asterisk has problems with them
                // it would need to be escaped
                $qregex = isset($q['qregex']) ? $q['qregex'] : '';
                str_replace(';', '\\;', $qregex);
                $ext->add($c, $exten, '', new ext_macro('user-callerid'));
                if (isset($q['qnoanswer']) && $q['qnoanswer'] == FALSE) {
                    $ext->add($c, $exten, '', new ext_answer(''));
                } else {
                    // TODO: should this only be set if noanswer + (!ringtones || joinannounce)???
                    $ext->add($c, $exten, '', new ext_progress());
                }
                // block voicemail until phone is answered at which point a macro should be called on the answering
                // line to clear this flag so that subsequent transfers can occur.
                if ($q['queuewait']) {
                    $ext->add($c, $exten, '', new ext_execif('$["${QUEUEWAIT}" = ""]', 'Set', '__QUEUEWAIT=${EPOCH}'));
                }
                // If extension_only don't do this and CFIGNORE
                if ($q['use_queue_context'] != '2') {
                    $ext->add($c, $exten, '', new ext_macro('blkvm-set', 'reset'));
                    $ext->add($c, $exten, '', new ext_execif('$["${REGEX("(M[(]auto-blkvm[)])" ${DIAL_OPTIONS})}" != "1"]', 'Set', '_DIAL_OPTIONS=${DIAL_OPTIONS}M(auto-blkvm)'));
                }
                // Inform all the children NOT to send calls to destinations or voicemail
                //
                $ext->add($c, $exten, '', new ext_setvar('__NODEST', '${EXTEN}'));
                /*
                 * Virtual Queue Settings, dialplan designed so these can be changed by other modules and those changes
                 * will override the configured changes here.
                 */
                // deal with group CID prefix
                $ext->add($c, $exten, '', new ext_set('QCIDPP', '${IF($[${LEN(${VQ_CIDPP})}>0]?${VQ_CIDPP}' . ':' . ($grppre == '' ? ' ' : $grppre) . ')}'));
                $ext->add($c, $exten, '', new ext_set('VQ_CIDPP', ''));
                $ext->add($c, $exten, '', new ext_execif('$["${QCIDPP}"!=""]', 'Macro', 'prepend-cid,${QCIDPP}'));
                // Set Alert_Info
                $ainfo = $alertinfo != '' ? str_replace(';', '\\;', $alertinfo) : ' ';
                $ext->add($c, $exten, '', new ext_set('QAINFO', '${IF($[${LEN(${VQ_AINFO})}>0]?${VQ_AINFO}:' . $ainfo . ')}'));
                $ext->add($c, $exten, '', new ext_set('VQ_AINFO', ''));
                $ext->add($c, $exten, '', new ext_execif('$["${QAINFO}"!=""]', 'Set', '__ALERT_INFO=${QAINFO}'));
                $joinannounce_id = isset($q['joinannounce_id']) ? $q['joinannounce_id'] : '';
                $joinannounce = $joinannounce_id ? recordings_get_file($joinannounce_id) : ' ';
                $joinansw = isset($q['qnoanswer']) && $q['qnoanswer'] == TRUE ? 'noanswer' : '';
                $cplay = $q['skip_joinannounce'] ? ' && ${QUEUE_MEMBER(' . $exten . ',' . $q['skip_joinannounce'] . ')}<1' : '';
                $ext->add($c, $exten, '', new ext_set('QJOINMSG', '${IF($[${LEN(${VQ_JOINMSG})}>0]?${IF($["${VQ_JOINMSG}"!="0"]?${VQ_JOINMSG}: )}:' . $joinannounce . ')}'));
                $ext->add($c, $exten, '', new ext_set('VQ_JOINMSG', ''));
                $options = 't';
                if (isset($q['answered_elsewhere']) && $q['answered_elsewhere'] == '1') {
                    $ext->add($c, $exten, '', new ext_set('QCANCELMISSED', 'C'));
                }
                if ($q['rtone'] == 1) {
                    $qringopts = 'r';
                } else {
                    if ($q['rtone'] == 2) {
                        $qringopts = 'R';
                    } else {
                        $qringopts = '';
                    }
                }
                if ($qringopts) {
                    $ext->add($c, $exten, '', new ext_set('QRINGOPTS', $qringopts));
                }
                $qretry = $q['retry'] == 'none' ? 'n' : ' ';
                $ext->add($c, $exten, '', new ext_set('QRETRY', '${IF($[${LEN(${VQ_RETRY})}>0]?${VQ_RETRY}:' . $qretry . ')}'));
                $ext->add($c, $exten, '', new ext_set('VQ_RETRY', ''));
                $ext->add($c, $exten, 'qoptions', new ext_set('QOPTIONS', '${IF($[${LEN(${VQ_OPTIONS})}>0]?${VQ_OPTIONS}:' . ($options != '' ? $options : ' ') . ')}${QCANCELMISSED}${QRINGOPTS}${QRETRY}'));
                $ext->add($c, $exten, '', new ext_set('VQ_OPTIONS', ''));
                // Set these up to be easily spliced into if we want to configure ability in queue modules
                //
                $ext->add($c, $exten, 'qgosub', new ext_set('QGOSUB', '${IF($[${LEN(${VQ_GOSUB})}>0]?${VQ_GOSUB}:${QGOSUB})}'));
                $ext->add($c, $exten, '', new ext_set('VQ_GOSUB', ''));
                $ext->add($c, $exten, 'qagi', new ext_set('QAGI', '${IF($[${LEN(${VQ_AGI})}>0]?${VQ_AGI}:${QAGI})}'));
                $ext->add($c, $exten, '', new ext_set('VQ_AGI', ''));
                $ext->add($c, $exten, 'qrule', new ext_set('QRULE', '${IF($[${LEN(${VQ_RULE})}>0]?${IF($["${VQ_RULE}"!="0"]?${VQ_RULE}: )}:${QRULE})}'));
                $ext->add($c, $exten, '', new ext_set('VQ_RULE', ''));
                $ext->add($c, $exten, 'qposition', new ext_set('QPOSITION', '${IF($[${LEN(${VQ_POSITION})}>0]?${VQ_POSITION}:${QPOSITION})}'));
                $ext->add($c, $exten, '', new ext_set('VQ_POSITION', ''));
                if (!isset($q['recording']) || empty($q['recording'])) {
                    $record_mode = 'dontcare';
                } else {
                    $record_mode = $q['recording'];
                }
                if ($amp_conf['QUEUES_MIX_MONITOR']) {
                    $monitor_options = '';
                    if (isset($q['monitor_type']) && $q['monitor_type'] != '') {
                        $monitor_options .= 'b';
                    }
                    if (isset($q['monitor_spoken']) && $q['monitor_spoken'] != 0) {
                        $monitor_options .= 'V(' . $q['monitor_spoken'] . ')';
                    }
                    if (isset($q['monitor_heard']) && $q['monitor_heard'] != 0) {
                        $monitor_options .= 'v(' . $q['monitor_heard'] . ')';
                    }
                    if ($monitor_options != '') {
                        $ext->add($c, $exten, '', new ext_setvar('MONITOR_OPTIONS', $monitor_options));
                    }
                }
                $ext->add($c, $exten, '', new ext_gosub('1', 's', 'sub-record-check', "q,{$exten},{$record_mode}"));
                // Set CWIGNORE  if enabled so that busy agents don't have another line key ringing and
                // stalling the ACD.
                if ($q['cwignore'] == 1 || $q['cwignore'] == 2) {
                    $ext->add($c, $exten, '', new ext_setvar('__CWIGNORE', 'TRUE'));
                }
                if ($q['use_queue_context']) {
                    $ext->add($c, $exten, '', new ext_setvar('__CFIGNORE', 'TRUE'));
                    $ext->add($c, $exten, '', new ext_setvar('__FORWARD_CONTEXT', 'block-cf'));
                }
                $agentannounce_id = isset($q['agentannounce_id']) ? $q['agentannounce_id'] : '';
                if ($agentannounce_id) {
                    $agentannounce = recordings_get_file($agentannounce_id);
                } else {
                    $agentannounce = ' ';
                }
                if ($q['callconfirm'] == 1) {
                    $ext->add($c, $exten, '', new ext_setvar('__FORCE_CONFIRM', '${CHANNEL}'));
                    if ($amp_conf['AST_FUNC_SHARED']) {
                        $ext->add($c, $exten, '', new ext_setvar('SHARED(ANSWER_STATUS)', 'NOANSWER'));
                    }
                    $ext->add($c, $exten, '', new ext_setvar('__CALLCONFIRMCID', '${CALLERID(number)}'));
                    $callconfirm_id = isset($q['callconfirm_id']) ? $q['callconfirm_id'] : '';
                    if ($callconfirm_id) {
                        $callconfirm = recordings_get_file($callconfirm_id);
                    } else {
                        $callconfirm = ' ';
                    }
                    $ext->add($c, $exten, '', new ext_set('__ALT_CONFIRM_MSG', '${IF($[${LEN(${VQ_CONFIRMMSG})}>0]?${IF($["${VQ_CONFIRMMSG}"!="0"]?${VQ_CONFIRMMSG}: )}:' . $callconfirm . ')}'));
                    $ext->add($c, $exten, '', new ext_set('VQ_CONFIRMMSG', ''));
                }
                $ext->add($c, $exten, '', new ext_execif('$["${QJOINMSG}"!=""' . $cplay . ']', 'Playback', '${QJOINMSG}, ' . $joinansw));
                $ext->add($c, $exten, '', new ext_queuelog($exten, '${UNIQUEID}', 'NONE', 'DID', '${FROM_DID}'));
                $ext->add($c, $exten, '', new ext_set('QAANNOUNCE', '${IF($[${LEN(${VQ_AANNOUNCE})}>0]?${IF($["${VQ_AANNOUNCE}"!="0"]?${VQ_AANNOUNCE}: )}:' . $agentannounce . ')}'));
                $ext->add($c, $exten, '', new ext_set('VQ_AANNOUNCE', ''));
                $agnc = '${QAANNOUNCE}';
                $qmoh = isset($q['music']) && $q['music'] != '' ? $q['music'] : ' ';
                $ext->add($c, $exten, '', new ext_set('QMOH', '${IF($["${VQ_MOH}"!=""]?${VQ_MOH}:' . $qmoh . ')}'));
                $ext->add($c, $exten, '', new ext_set('VQ_MOH', ''));
                $ext->add($c, $exten, '', new ext_execif('$["${QMOH}"!=""]', 'Set', '__MOHCLASS=${QMOH}'));
                $ext->add($c, $exten, '', new ext_execif('$["${MOHCLASS}"!=""]', 'Set', 'CHANNEL(musicclass)=${MOHCLASS}'));
                $ext->add($c, $exten, '', new ext_set('QMAXWAIT', '${IF($[${LEN(${VQ_MAXWAIT})}>0]?${VQ_MAXWAIT}:' . ($q['maxwait'] != '' ? $q['maxwait'] : ' ') . ')}'));
                $ext->add($c, $exten, '', new ext_set('VQ_MAXWAIT', ''));
                $ext->add($c, $exten, '', new ext_set('QUEUENUM', $exten));
                $ext->add($c, $exten, '', new ext_set('QUEUEJOINTIME', '${EPOCH}'));
                $qmaxwait = '${QMAXWAIT}';
                $options = '${QOPTIONS}';
                $qagi = '${QAGI}';
                $qmacro = '';
                $qgosub = '${QGOSUB}';
                $qrule = '${QRULE}';
                $qposition = '${QPOSITION}';
                // Queue(queuename[,options[,URL[,announceoverride[,timeout[,AGI[,macro[,gosub[,rule[,position]]]]]]]]])
                //
                $ext->add($c, $exten, 'qcall', new ext_queue($exten, $options, '', $agnc, $qmaxwait, $qagi, $qmacro, $qgosub, $qrule, $qposition));
                if ($q['use_queue_context'] != '2') {
                    $ext->add($c, $exten, '', new ext_macro('blkvm-clr'));
                }
                // cancel any recording previously requested
                $ext->add($c, $exten, '', new ext_gosub('1', 's', 'sub-record-cancel'));
                // If we are here, disable the NODEST as we want things to resume as normal
                $ext->add($c, $exten, '', new ext_setvar('__NODEST', ''));
                $ext->add($c, $exten, '', new ext_setvar('_QUEUE_PRIO', '0'));
                if ($q['callconfirm'] == 1) {
                    if ($amp_conf['AST_FUNC_SHARED']) {
                        $ext->add($c, $exten, '', new ext_setvar('SHARED(ANSWER_STATUS)', ''));
                    }
                    $ext->add($c, $exten, '', new ext_setvar('__FORCE_CONFIRM', ''));
                    $ext->add($c, $exten, '', new ext_setvar('__ALT_CONFIRM_MSG', ''));
                }
                if ($monitor_options != '') {
                    $ext->add($c, $exten, '', new ext_setvar('MONITOR_OPTIONS', ''));
                }
                if ($q['cwignore'] == 1 || $q['cwignore'] == 2) {
                    $ext->add($c, $exten, '', new ext_setvar('__CWIGNORE', ''));
                }
                if ($q['use_queue_context']) {
                    $ext->add($c, $exten, '', new ext_setvar('__CFIGNORE', ''));
                    $ext->add($c, $exten, '', new ext_setvar('__FORWARD_CONTEXT', 'from-internal'));
                }
                if ($qringopts) {
                    $ext->add($c, $exten, '', new ext_set('QRINGOPTS', ''));
                }
                //VQ_DEST = str_replace(',','^',$vq['goto'])
                $ext->add($c, $exten, '', new ext_set('QDEST', '${VQ_DEST}'));
                $ext->add($c, $exten, '', new ext_set('VQ_DEST', ''));
                $ext->add($c, $exten, 'gotodest', new ext_gotoif('$["${QDEST}"=""]', $q['goto'], '${CUT(QDEST,^,1)},${CUT(QDEST,^,2)},${CUT(QDEST,^,3)}'));
                //dynamic agent login/logout
                if (trim($qregex) != '') {
                    $ext->add($c, $exten . "*", '', new ext_setvar('QREGEX', $qregex));
                }
                if ($amp_conf['GENERATE_LEGACY_QUEUE_CODES']) {
                    if ($q['use_queue_context'] == '2') {
                        $ext->add($c, $exten . "*", '', new ext_macro('agent-add', $exten . "," . $q['password'] . ",EXTEN"));
                    } else {
                        $ext->add($c, $exten . "*", '', new ext_macro('agent-add', $exten . "," . $q['password']));
                    }
                    $ext->add($c, $exten . "**", '', new ext_macro('agent-del', "{$exten}"));
                }
                if ($que_code != '') {
                    $ext->add($c, $que_code . $exten, '', new ext_setvar('QUEUENO', $exten));
                    $ext->add($c, $que_code . $exten, '', new ext_goto('start', 's', 'app-queue-toggle'));
                }
                if ($que_pause_code != '') {
                    $ext->add($c, $que_pause_code . $exten, '', new ext_gosub('1', 's', 'app-queue-pause-toggle', $exten));
                }
                /* Trial Devstate */
                // Create Hints for Devices and Add Astentries for Users
                // Clean up the Members array
                if ($q['togglehint'] && $que_code != '') {
                    if (!isset($device_list)) {
                        $device_list = core_devices_list("all", 'full', true);
                        $device_list = is_array($device_list) ? $device_list : array();
                    }
                    if ($astman) {
                        if (($dynmemberonly = strtolower($astman->database_get('QPENALTY/' . $exten, 'dynmemberonly')) == 'yes') == true) {
                            $get = $astman->database_show('QPENALTY/' . $exten . '/agents');
                            if (is_array($get)) {
                                $mem = array();
                                foreach ($get as $key => $value) {
                                    $key = explode('/', $key);
                                    $mem[$key[4]] = $value;
                                }
                            }
                        }
                    } else {
                        fatal("Cannot connect to Asterisk Manager with " . $amp_conf["AMPMGRUSER"] . "/" . $amp_conf["AMPMGRPASS"]);
                    }
                    $exten_str_len = strlen($exten);
                    $exten_str_tmp = str_repeat('X', $exten_str_len);
                    $que_code_len = strlen($que_code);
                    $device_list = !empty($device_list) ? $device_list : array();
                    foreach ($device_list as $device) {
                        if ((!$dynmemberonly || $device['devicetype'] == 'adhoc' || isset($mem[$device['user']])) && ($device['tech'] == 'sip' || $device['tech'] == 'iax2' || $device['tech'] == 'pjsip')) {
                            $dev_len = strlen($device['id']);
                            $dev_len_tmp = str_repeat('X', $dev_len);
                            $exten_pat = '_' . $que_code . $dev_len_tmp . '*' . $exten_str_tmp;
                            if (!in_array($exten_pat, $hint_hash)) {
                                $hint_hash[] = $exten_pat;
                                $ext->add($c, $exten_pat, '', new ext_setvar('QUEUENO', '${EXTEN:' . ($que_code_len + $dev_len + 1) . ":{$exten_str_len}}"));
                                $ext->add($c, $exten_pat, '', new ext_setvar('QUEUEUSER', '${EXTEN:' . "{$que_code_len}:{$dev_len}" . '}'));
                                $ext->add($c, $exten_pat, '', new ext_goto('start', 's', 'app-queue-toggle'));
                                $ext->addHint($c, $exten_pat, "Custom:QUEUE" . '${EXTEN:' . "{$que_code_len}}");
                                //TODO: dynamic hints
                            }
                        }
                    }
                }
                // Add routing vector to direct which context call should go
                //
                $agent_context = isset($q['use_queue_context']) && $q['use_queue_context'] && isset($queue_context) ? $queue_context : 'from-internal';
                switch ($q['use_queue_context']) {
                    case 1:
                        $agent_context = $from_queue_exten_internal;
                        break;
                    case 2:
                        $agent_context = $from_queue_exten_only;
                        break;
                    case 0:
                    default:
                        $agent_context = 'from-internal';
                        break;
                }
                $ext->add('from-queue', $exten, '', new ext_goto('1', '${QAGENT}', $agent_context));
                $q['member'] = is_array($q['member']) ? $q['member'] : array();
                foreach ($q['member'] as $qm) {
                    if (strtoupper(substr($qm, 0, 1)) == 'L') {
                        $tm = preg_replace("/[^0-9#\\,*]/", "", $qm);
                        $tma = explode(',', $tm);
                        $qmembers[$exten][] = $tma[0];
                    }
                }
            }
            if (!$amp_conf['DYNAMICHINTS'] && ($que_code != '' || $que_pause_code != '' || $que_callers_code != '')) {
                $qpenalty = $astman->database_show('QPENALTY');
                $qc = array();
                foreach (array_keys($qpenalty) as $key) {
                    $key = explode('/', $key);
                    if ($key[3] == 'agents') {
                        $qc[$key[4]][] = $key[2];
                    }
                }
                // Make sure we have all the devices
                //
                if (!isset($device_list)) {
                    $device_list = core_devices_list("all", 'full', true);
                    $device_list = is_array($device_list) ? $device_list : array();
                }
            }
            // Create *45 all queue toggle
            //
            if ($que_code != '') {
                $ext->add($c, $que_code, '', new ext_goto('start', 's', 'app-all-queue-toggle'));
                // create a generic one for any phones that don't get a specific one created since we only
                // create them for phones we know have queues but who knows what is provisioned on the phones
                //
                $ext->add($c, '_' . $que_code . '*X.', '', new ext_goto('start', 's', 'app-all-queue-toggle'));
                // generate with #exec if we are using dynamic hints
                //
                if ($amp_conf['DYNAMICHINTS']) {
                    $ext->addExec($c, $amp_conf['AMPBIN'] . '/generate_queue_hints.php ' . $que_code);
                } else {
                    $que_code_len = strlen($que_code);
                    $hlist = '';
                    foreach ($device_list as $device) {
                        $astman->database_del("AMPUSER/" . $device['id'], "queuehint");
                        //cleanup
                        if ($device['tech'] == 'sip' || $device['tech'] == 'iax2' || $device['tech'] == 'pjsip') {
                            if ($device['user'] != '' && isset($qc[$device['user']])) {
                                $hlist = 'Custom:QUEUE' . $device['id'] . '*' . implode('&Custom:QUEUE' . $device['id'] . '*', $qc[$device['user']]);
                                $astman->database_put("AMPUSER/" . $device['id'], "queuehint", $hlist);
                            }
                        }
                    }
                    $ext->addHint($c, '_' . $que_code . '*' . 'X.', '${DB(AMPUSER/${EXTEN:' . strlen($que_code . '*') . '}/queuehint)}');
                }
            }
            // Add the static members now since so far it only has dynamic members
            foreach ($qmembers as $q => $mems) {
                $mems = is_array($mems) ? $mems : array();
                foreach ($mems as $m) {
                    // If $m is not in qc already then add them, thus avoiding duplicates
                    if (!isset($qc[$m]) || !in_array($q, $qc[$m])) {
                        $qc[$m][] = (string) $q;
                    }
                }
            }
            // Create *46 codes/hints
            //
            if ($que_pause_code != '') {
                $ext->add($c, $que_pause_code, '', new ext_goto('1', 's', 'app-all-queue-pause-toggle'));
                // create a generic one for any phones that don't get a specific one created since we only
                // create them for phones we know have queues but who knows what is provisioned on the phones
                //
                $ext->add($c, '_' . $que_pause_code . '*X.', '', new ext_goto('1', 's', 'app-all-queue-pause-toggle'));
                // TODO: There's a bug here $q_pause_Local isn't initialized and shoudl be something.
                //       Currently this can't be made into a pattern since it's the $device['user'] but the hint has the device
                //
                $q_pause_len = strlen($que_pause_code);
                $device_list = isset($device_list) && is_array($device_list) ? $device_list : array();
                foreach ($device_list as $device) {
                    $astman->database_del("AMPUSER/" . $device['id'], "pausequeuehint");
                    if ($device['user'] != '') {
                        $pause_all_hints = array();
                        if (isset($qc[$device['user']])) {
                            foreach ($qc[$device['user']] as $q) {
                                if (!$amp_conf['DYNAMICHINTS'] && ($device['tech'] == 'pjsip' || $device['tech'] == 'sip' || $device['tech'] == 'iax2')) {
                                    // Do the real hints for below
                                    //
                                    if ($ast_ge_12) {
                                        $hint = "Queue:{$q}_pause_Local/{$device['user']}@from-queue/n";
                                    } else {
                                        $hint = "qpause:{$q}:Local/{$device['user']}@from-queue/n";
                                    }
                                    $pause_all_hints[] = $hint;
                                    $dev_len = strlen($device['id']);
                                    $dev_len_tmp = str_repeat('X', $dev_len);
                                    $exten_pat = "_{$que_pause_code}*{$dev_len_tmp}*{$q}";
                                    if (!in_array($exten_pat, $hint_hash)) {
                                        $hint_hash[] = $exten_pat;
                                        /*
                                        									exten => *46*1999*90000,1,Gosub(app-queue-pause-toggle,s,1(90000,1999))
                                        									exten => *46*1999*90000,hint,Queue:90000_pause_Local/1999@from-queue/n
                                        									${DB(DEVICE/${EXTEN:4:4}/user)}
                                        */
                                        $q_tmp = '${EXTEN:' . ($q_pause_len + $dev_len + 2) . '}';
                                        $d_tmp = '${DB(DEVICE/${EXTEN:' . ($q_pause_len + 1) . ":{$dev_len}}/user)}";
                                        if ($ast_ge_12) {
                                            $hint = "Queue:{$q_tmp}_pause_Local/{$d_tmp}@from-queue/n";
                                        } else {
                                            $hint = "qpause:{$q_tmp}:Local/{$d_tmp}@from-queue/n";
                                        }
                                        $ext->add($c, $exten_pat, '', new ext_gosub('1', 's', 'app-queue-pause-toggle', $q . ',' . $device['id']));
                                        $ext->addHint($c, $exten_pat, $hint);
                                    }
                                } else {
                                    $ext->add($c, $que_pause_code . '*' . $device['id'] . '*' . $q, '', new ext_gosub('1', 's', 'app-queue-pause-toggle', $q . ',' . $device['id']));
                                }
                            }
                        }
                        //$ext->add($c, $que_pause_code . '*' . $device['id'], '', new ext_goto('1','s','app-all-queue-pause-toggle'));
                        if (!empty($pause_all_hints)) {
                            $astman->database_put("AMPUSER/" . $device['id'], "pausequeuehint", implode('&', $pause_all_hints));
                        }
                    }
                }
                $ext->addHint($c, '_' . $que_pause_code . '*X.', '${DB(AMPUSER/${EXTEN:' . strlen($que_pause_code . '*') . '}/pausequeuehint)}');
            }
            // Create *47 codes/hints
            //
            if ($que_callers_code != '') {
                $id = "app-queue-caller-count";
                $ext->addInclude('from-internal-additional', $id);
                // Add the include from from-internal
                $ext->add($id, 's', '', new ext_answer());
                $ext->add($id, 's', '', new ext_wait(1));
                $ext->add($id, 's', '', new ext_setvar('QUEUES', '${ARG1}'));
                $ext->add($id, 's', '', new ext_setvar('COUNT', '0'));
                $ext->add($id, 's', '', new ext_setvar('LOOPCNT', '${FIELDQTY(QUEUES,&)}'));
                $ext->add($id, 's', '', new ext_setvar('ITER', '1'));
                $ext->add($id, 's', 'begin1', new ext_setvar('QUEUE', '${CUT(QUEUES,&,${ITER})}'));
                $ext->add($id, 's', '', new ext_setvar('COUNT', '$[${COUNT} + ${QUEUE_WAITING_COUNT(${QUEUE})}]'));
                $ext->add($id, 's', 'end1', new ext_setvar('ITER', '$[${ITER} + 1]'));
                $ext->add($id, 's', '', new ext_gotoif('$[${ITER} <= ${LOOPCNT}]', 'begin1'));
                $ext->add($id, 's', '', new ext_saynumber('${COUNT}'));
                $ext->add($id, 's', '', new ext_playback('queue-quantity2'));
                $ext->add($id, 's', '', new ext_return());
            }
            // We need to have a hangup here, if call is ended by the caller during Playback it will end in the
            // h context and do a proper hangup and clean the blkvm if set, see #4671
            $ext->add($c, 'h', '', new ext_macro('hangupcall'));
            // NODEST will be the queue that this came from, so we will vector though an entry to determine the context the
            // agent should be delivered to. All queue calls come here, this decides if the should go direct to from-internal
            // or indirectly through from-queue-exten-only to trap extension calls and avoid their follow-me, etc.
            //
            $ext->add('from-queue', '_.', '', new ext_setvar('QAGENT', '${EXTEN}'));
            $ext->add('from-queue', '_.', '', new ext_setvar('__FROMQ', 'true'));
            //see below comments
            $ext->add('from-queue', '_.', '', new ext_goto('1', '${NODEST}'));
            //http://issues.freepbx.org/browse/FREEPBX-11871
            //Because of local channel changes in Asterisk 12+ we end up losing track of our recording file
            //This effectively "gives" back the recording file to the channel that answered the queue
            if ($ast_ge_12) {
                $ext->splice('macro-auto-blkvm', 's', 1, new ext_execif('$["${FROMQ}" = "true" & "${CALLFILENAME}" != "" & "${CDR(recordingfile)}" = ""]', 'Set', 'CDR(recordingfile)=${CALLFILENAME}.${MON_FMT}'));
            }
            $ext->addInclude($from_queue_exten_only . '-x', 'from-internal');
            $ext->add($from_queue_exten_only . '-x', 'foo', '', new ext_noop('bar'));
            $ext->addInclude($from_queue_exten_internal, $from_queue_exten_only);
            $ext->addInclude($from_queue_exten_internal, $from_queue_exten_only . '-x');
            $ext->addInclude($from_queue_exten_internal, 'from-internal');
            $ext->add($from_queue_exten_internal, 'foo', '', new ext_noop('bar'));
            /* create a context, from-queue-exten-only, that can be used for queues that want behavir similar to
             * ringgroup where only the agent's phone will be rung, no follow-me will be pursued.
             */
            $sql = "SELECT LENGTH(extension) as len FROM users GROUP BY len";
            $sth = FreePBX::Database()->prepare($sql);
            $sth->execute();
            $rows = $sth->fetchAll(\PDO::FETCH_ASSOC);
            foreach ($rows as $row) {
                //make sure exten exists
                $ext->add($from_queue_exten_only, '_' . str_repeat('X', $row['len']), '', new ext_gotoif('$[${DB_EXISTS(AMPUSER/${EXTEN}/cidnum)} = 0]', $from_queue_exten_only . '-x,${EXTEN},1'));
                $ext->add($from_queue_exten_only, '_' . str_repeat('X', $row['len']), '', new ext_set('RingGroupMethod', 'none'));
                $ext->add($from_queue_exten_only, '_' . str_repeat('X', $row['len']), '', new ext_set('QDOPTS', '${IF($["${CALLER_DEST}"!=""]?g)}${IF($["${AGENT_DEST}"!=""]?F(${AGENT_DEST}))}'));
                $ext->add($from_queue_exten_only, '_' . str_repeat('X', $row['len']), 'checkrecord', new ext_set('CALLTYPE_OVERRIDE', 'external'));
                // Make sure the call is tagged as external
                // This means:
                // If (!$fromexten) { if (!$nodest) { $fromexten = 'external' } else { $fromexten = $nodest } }
                $ext->add($from_queue_exten_only, '_' . str_repeat('X', $row['len']), '', new ext_execif('$[!${LEN(${FROMEXTEN})}]', 'Set', 'FROMEXTEN=${IF(${LEN(${NODEST})}?${NODEST}:external)}'));
                // Make sure the call is tagged as external
                $ext->add($from_queue_exten_only, '_' . str_repeat('X', $row['len']), '', new ext_gosub('1', 's', 'sub-record-check', 'exten,${EXTEN},'));
                if ($has_extension_state) {
                    $ext->add($from_queue_exten_only, '_' . str_repeat('X', $row['len']), '', new ext_macro('dial-one', ',${DIAL_OPTIONS}${QDOPTS},${EXTEN}'));
                } else {
                    $ext->add($from_queue_exten_only, '_' . str_repeat('X', $row['len']), '', new ext_macro('dial', ',${DIAL_OPTIONS}${QDOPTS},${EXTEN}'));
                }
                $ext->add($from_queue_exten_only, '_' . str_repeat('X', $row['len']), '', new ext_gotoif('$["${CALLER_DEST}"!=""&&"${DIALSTATUS}"="ANSWER"]', '${CUT(CALLER_DEST,^,1)},${CUT(CALLER_DEST,^,2)},${CUT(CALLER_DEST,^,3)}'));
                $ext->add($from_queue_exten_only, '_' . str_repeat('X', $row['len']), '', new ext_hangup());
            }
            if (!empty($rows)) {
                $ext->add($from_queue_exten_only, 'h', '', new ext_macro('hangupcall'));
            }
            /*
             * Adds a dynamic agent/member to a Queue
             * Prompts for call-back number - in not entered, uses CIDNum
             */
            if ($amp_conf['GENERATE_LEGACY_QUEUE_CODES']) {
                $c = 'macro-agent-add';
                // for i18n playback in multiple languages
                $ext->add($c, 'lang-playback', '', new ext_gosubif('$[${DIALPLAN_EXISTS(' . $c . ',${CHANNEL(language)})}]', $c . ',${CHANNEL(language)},${ARG1}', $c . ',en,${ARG1}'));
                $ext->add($c, 'lang-playback', '', new ext_return());
                $exten = 's';
                $ext->add($c, $exten, '', new ext_wait(1));
                $ext->add($c, $exten, '', new ext_set('QUEUENO', '${ARG1}'));
                $ext->add($c, $exten, '', new ext_macro('user-callerid', 'SKIPTTL'));
                $ext->add($c, $exten, 'a3', new ext_read('CALLBACKNUM', 'agent-login'));
                // get callback number from user
                $ext->add($c, $exten, '', new ext_gotoif('$[${LEN(${CALLBACKNUM})}=0]', 'a5', 'a7'));
                // if user just pressed # or timed out, use cidnum
                $ext->add($c, $exten, 'a5', new ext_set('CALLBACKNUM', '${IF($[${LEN(${AMPUSER})}=0]?${CALLERID(number)}:${AMPUSER})}'));
                $ext->add($c, $exten, '', new ext_set('THISDEVICE', '${DB(DEVICE/${REALCALLERIDNUM}/dial)}'));
                $ext->add($c, $exten, '', new ext_gotoif('$["${CALLBACKNUM}" = ""]', 'a3'));
                // if still no number, start over
                $ext->add($c, $exten, 'a7', new ext_gotoif('$["${CALLBACKNUM}" = "${QUEUENO}"]', 'invalid'));
                // Error, they put in the queue number
                // If this is an extension only queue then EXTEN is passed as ARG3 and we make sure this is a valid extension being entered
                $ext->add($c, $exten, '', new ext_gotoif('$["${ARG3}" = "EXTEN" & ${DB_EXISTS(AMPUSER/${CALLBACKNUM}/cidname)} = 0]', 'invalid'));
                // If this is a restricted dynamic agent queue then check to make sure they are allowed
                $ext->add($c, $exten, '', new ext_gotoif('$["${DB(QPENALTY/${QUEUENO}/dynmemberonly)}" = "yes" & ${DB_EXISTS(QPENALTY/${QUEUENO}/agents/${CALLBACKNUM})} != 1]', 'invalid'));
                $ext->add($c, $exten, '', new ext_execif('$["${QREGEX}" != ""]', 'GotoIf', '$["${REGEX("${QREGEX}" ${CALLBACKNUM})}" = "0"]?invalid'));
                $ext->add($c, $exten, '', new ext_execif('$["${ARG2}" != ""]', 'Authenticate', '${ARG2}'));
                $ext->add($c, $exten, '', new ext_set('STATE', 'INUSE'));
                $ext->add($c, $exten, '', new ext_gosub('1', 'sstate', 'app-queue-toggle'));
                $ext->add($c, $exten, '', new ext_execif('$[${DB_EXISTS(AMPUSER/${CALLBACKNUM}/cidname)} = 1 & "${DB(AMPUSER/${CALLBACKNUM}/queues/qnostate)}" != "ignorestate"]', 'AddQueueMember', '${QUEUENO},Local/${CALLBACKNUM}@from-queue/n,${DB(QPENALTY/${QUEUENO}/agents/${CALLBACKNUM})},,${DB(AMPUSER/${CALLBACKNUM}/cidname)},hint:${CALLBACKNUM}@ext-local'));
                $ext->add($c, $exten, '', new ext_execif('$[${DB_EXISTS(AMPUSER/${CALLBACKNUM}/cidname)} = 1 & "${DB(AMPUSER/${CALLBACKNUM}/queues/qnostate)}" = "ignorestate"]', 'AddQueueMember', '${QUEUENO},Local/${CALLBACKNUM}@from-queue/n,${DB(QPENALTY/${QUEUENO}/agents/${CALLBACKNUM})},,${DB(AMPUSER/${CALLBACKNUM}/cidname)}'));
                $ext->add($c, $exten, '', new ext_execif('$[${DB_EXISTS(AMPUSER/${CALLBACKNUM}/cidname)} = 0]', 'AddQueueMember', '${QUEUENO},Local/${CALLBACKNUM}@from-queue/n,${DB(QPENALTY/${QUEUENO}/agents/${CALLBACKNUM})}'));
                $ext->add($c, $exten, '', new ext_userevent('Agentlogin', 'Agent: ${CALLBACKNUM}'));
                $ext->add($c, $exten, '', new ext_wait(1));
                $ext->add($c, $exten, '', new ext_gosub('1', 'lang-playback', $c, 'hook_0'));
                $ext->add($c, $exten, '', new ext_hangup());
                $ext->add($c, $exten, '', new ext_macroexit());
                $ext->add($c, $exten, 'invalid', new ext_playback('pbx-invalid'));
                $ext->add($c, $exten, '', new ext_goto('a3'));
                $lang = 'en';
                // English
                $ext->add($c, $lang, 'hook_0', new ext_playback('agent-loginok&with&extension'));
                $ext->add($c, $lang, '', new ext_saydigits('${CALLBACKNUM}'));
                $ext->add($c, $lang, '', new ext_return());
                $lang = 'ja';
                // Japanese
                $ext->add($c, $lang, 'hook_0', new ext_playback('extension'));
                $ext->add($c, $lang, '', new ext_saydigits('${CALLBACKNUM}'));
                $ext->add($c, $lang, '', new ext_playback('jp-kara&agent-loginok'));
                $ext->add($c, $lang, '', new ext_return());
                /*
                 * Removes a dynamic agent/member from a Queue
                 * Prompts for call-back number - in not entered, uses CIDNum
                 */
                $c = 'macro-agent-del';
                $ext->add($c, $exten, '', new ext_wait(1));
                $ext->add($c, $exten, '', new ext_set('QUEUENO', '${ARG1}'));
                $ext->add($c, $exten, '', new ext_macro('user-callerid', 'SKIPTTL'));
                $ext->add($c, $exten, 'a3', new ext_read('CALLBACKNUM', 'agent-logoff'));
                // get callback number from user
                $ext->add($c, $exten, '', new ext_gotoif('$[${LEN(${CALLBACKNUM})}=0]', 'a5', 'a7'));
                // if user just pressed # or timed out, use cidnum
                $ext->add($c, $exten, 'a5', new ext_set('CALLBACKNUM', '${IF($[${LEN(${AMPUSER})}=0]?${CALLERID(number)}:${AMPUSER})}'));
                $ext->add($c, $exten, '', new ext_gotoif('$["${CALLBACKNUM}" = ""]', 'a3'));
                // if still no number, start over
                $ext->add($c, $exten, '', new ext_set('STATE', 'NOT_INUSE'));
                $ext->add($c, $exten, '', new ext_gosub('1', 'sstate', 'app-queue-toggle'));
                // remove from both contexts in case left over dynamic agents after an upgrade
                $ext->add($c, $exten, 'a7', new ext_removequeuemember('${QUEUENO}', 'Local/${CALLBACKNUM}@from-queue/n'));
                $ext->add($c, $exten, '', new ext_removequeuemember('${QUEUENO}', 'Local/${CALLBACKNUM}@from-internal/n'));
                $ext->add($c, $exten, '', new ext_userevent('RefreshQueue'));
                $ext->add($c, $exten, '', new ext_wait(1));
                $ext->add($c, $exten, '', new ext_playback('agent-loggedoff'));
                $ext->add($c, $exten, '', new ext_hangup());
            }
            // GENERATE_LEGACY_QUEUE_CODES
            break;
    }
}
 public function updateChanSipSettings($key, $val = false, $type = SELF::SIP_NORMAL, $seq = 10)
 {
     $db = \FreePBX::Database();
     // Delete the key we want to change
     $del = $db->prepare('DELETE FROM `sipsettings` WHERE `keyword`=? AND `type`=?');
     $del->execute(array($key, $type));
     // If val is not EXACTLY false, add it back in
     if ($val !== false) {
         $ins = $db->prepare('INSERT INTO `sipsettings` (`keyword`, `data`, `type`, `seq`) VALUES (?, ?, ?, ?)');
         $ins->execute(array($key, $val, $type, $seq));
     }
 }
예제 #10
0
function tts_del($p_id)
{
    $dbh = \FreePBX::Database();
    $sql = 'DELETE FROM tts WHERE id = ?';
    $stmt = $dbh->prepare($sql);
    return $stmt->execute(array($p_id));
}
예제 #11
0
파일: Trunks.class.php 프로젝트: lidl/core
 private function enableTrunk($id)
 {
     $db = \FreePBX::Database();
     $sql = "UPDATE trunks set disabled = 'off' WHERE trunkid = ?";
     $ob = $db->prepare($sql);
     return $ob->execute(array($id));
 }
예제 #12
0
 /**
  * Update All Groups
  * Runs through the directory to update all settings (users and naming)
  */
 private function updateAllGroups()
 {
     if (!empty($this->gcache)) {
         return true;
     }
     if (php_sapi_name() !== 'cli') {
         throw new \Exception("Can only update groups over CLI");
     }
     $this->connect();
     $this->out("Retrieving all groups...", false);
     $sr = ldap_search($this->ldap, $this->dn, "(objectCategory=Group)", array("distinguishedname", "primarygrouptoken", "objectsid", "description", "cn"));
     if ($sr === false) {
         return false;
     }
     $groups = ldap_get_entries($this->ldap, $sr);
     $this->out("Got " . $groups['count'] . " groups");
     unset($groups['count']);
     $sql = "DROP TABLE IF EXISTS msad_procs_temp";
     $sth = $this->FreePBX->Database->prepare($sql);
     $sth->execute();
     $tempsql = "CREATE TABLE msad_procs_temp (\n\t\t\t`pid` int NOT NULL,\n\t\t\t`udata` varchar(255),\n\t\t\t`gdata` varchar(255),\n\t\t\tPRIMARY KEY(pid)\n\t\t) ENGINE = MEMORY";
     $sth = $this->FreePBX->Database->prepare($tempsql);
     $sth->execute();
     $this->out("Forking child processes");
     $tpath = __DIR__ . "/tmp";
     if (!file_exists($tpath)) {
         mkdir($tpath, 0777, true);
     }
     foreach ($groups as $i => $group) {
         $pid = pcntl_fork();
         if (!$pid) {
             $iid = getmypid();
             \FreePBX::Database()->__construct();
             $db = new \DB();
             $this->connect(true);
             //http://www.rlmueller.net/CharactersEscaped.htm
             $group['distinguishedname'][0] = ldap_escape($group['distinguishedname'][0]);
             $this->out("\tGetting users from " . $group['cn'][0] . "...");
             $gs = ldap_search($this->ldap, $this->dn, "(&(objectCategory=Person)(sAMAccountName=*)(memberof=" . $group['distinguishedname'][0] . "))");
             if ($gs !== false) {
                 $users = ldap_get_entries($this->ldap, $gs);
                 $susers = serialize($users);
                 file_put_contents($tpath . "/" . $iid . "-users", $susers);
                 $sgroup = serialize($group);
                 file_put_contents($tpath . "/" . $iid . "-group", $sgroup);
                 $sql = "INSERT INTO msad_procs_temp (`pid`,`udata`,`gdata`) VALUES (?,?,?)";
                 $sth = $this->FreePBX->Database->prepare($sql);
                 $sth->execute(array($i, $iid . "-users", $iid . "-group"));
             }
             $this->out("\tFinished Getting users from " . $group['cn'][0]);
             exit($i);
         }
     }
     \FreePBX::Database()->__construct();
     $db = new \DB();
     while (pcntl_waitpid(0, $status) != -1) {
         $status = pcntl_wexitstatus($status);
     }
     $this->out("Child processes have finished");
     $sql = "SELECT * FROM msad_procs_temp";
     $sth = $this->FreePBX->Database->prepare($sql);
     $sth->execute();
     $children = $sth->fetchAll(\PDO::FETCH_ASSOC);
     $this->out("Adding Users from non-primary groups...");
     foreach ($children as $child) {
         if (!file_exists($tpath . "/" . $child['udata']) || !file_exists($tpath . "/" . $child['gdata'])) {
             continue;
         }
         $udata = file_get_contents($tpath . "/" . $child['udata']);
         unlink($tpath . "/" . $child['udata']);
         $users = unserialize($udata);
         $gdata = file_get_contents($tpath . "/" . $child['gdata']);
         unlink($tpath . "/" . $child['gdata']);
         $group = unserialize($gdata);
         $this->out("\tFound " . $users['count'] . " users in " . $group['cn'][0]);
         unset($users['count']);
         $members = array();
         foreach ($users as $user) {
             $usid = $this->binToStrSid($user['objectsid'][0]);
             $u = $this->getUserByAuthID($usid);
             $members[] = $u['id'];
         }
         $sid = $this->binToStrSid($group['objectsid'][0]);
         $this->gcache[$sid] = $group;
         $um = $this->linkGroup($group['cn'][0], 'msad', $sid);
         if ($um['status']) {
             $this->updateGroupData($um['id'], array("description" => !empty($group['description'][0]) ? $group['description'][0] : '', "users" => $members));
             if ($um['new']) {
                 $this->groupHooks['add'][$um['id']] = array($um['id'], $group['cn'][0], !empty($group['description'][0]) ? $group['description'][0] : '', $members);
             } else {
                 $this->groupHooks['update'][$um['id']] = array($um['id'], $um['prevGroupname'], $group['cn'][0], !empty($group['description'][0]) ? $group['description'][0] : '', $members);
             }
         }
     }
     //remove users
     $fgroups = $this->getAllGroups();
     foreach ($fgroups as $group) {
         if (!isset($this->gcache[$group['authid']])) {
             $this->deleteGroupByGID($group['id'], false);
             $this->groupHooks['remove'][$group['id']] = array($group['id'], $group);
         }
     }
     $sql = "DROP TABLE msad_procs_temp";
     $sth = $this->FreePBX->Database->prepare($sql);
     $sth->execute();
     $this->out("Finished adding users from non-primary groups");
 }
예제 #13
0
 /**
  * Get the AMP User from the username
  * @param  string $username the username
  * @return mixed           False is false otherwise array of user
  */
 public function getAmpUser($username)
 {
     switch ($this->mode) {
         case "usermanager":
             try {
                 $um = FreePBX::Userman()->getUserByUsername($username);
                 $user = array();
                 $user['id'] = $um['id'];
                 $user["username"] = $um['username'];
                 $user["password_sha1"] = $um['password'];
                 $pbl = FreePBX::Userman()->getCombinedGlobalSettingByID($um['id'], 'pbx_low');
                 $user["extension_low"] = trim($pbl) !== "" ? $pbl : "";
                 $pbh = FreePBX::Userman()->getCombinedGlobalSettingByID($um['id'], 'pbx_high');
                 $user["extension_high"] = trim($pbh) !== "" ? $pbh : "";
                 $sections = FreePBX::Userman()->getCombinedGlobalSettingByID($um['id'], 'pbx_modules');
                 $user["sections"] = !empty($sections) && is_array($sections) ? $sections : array();
                 $user["opmode"] = FreePBX::Userman()->getCombinedGlobalSettingByID($um['id'], 'opmode');
                 return $user;
             } catch (Exception $e) {
             }
             //fail-through
         //fail-through
         case "database":
         default:
             $sql = "SELECT username, password_sha1, extension_low, extension_high, deptname, sections FROM ampusers WHERE username = ?";
             $sth = FreePBX::Database()->prepare($sql);
             $sth->execute(array($username));
             $results = $sth->fetchAll(\PDO::FETCH_ASSOC);
             if (count($results) > 0) {
                 $user = array();
                 $user["username"] = $results[0]['username'];
                 $user["password_sha1"] = $results[0]['password_sha1'];
                 $user["extension_low"] = $results[0]['extension_low'];
                 $user["extension_high"] = $results[0]['extension_high'];
                 $user["sections"] = explode(";", $results[0]['sections']);
                 return $user;
             } else {
                 return false;
             }
             break;
     }
 }
예제 #14
0
 public function convertDestDatabase()
 {
     $db = \FreePBX::Database();
     $res = $db->query("SELECT * FROM `custom_destinations`")->fetchAll(\PDO::FETCH_ASSOC);
     foreach ($res as $row) {
         $tmparr = array("target" => $row['custom_dest'], "notes" => $row['notes'], "description" => $row['description'], "destret" => false);
         $this->addCustomDest($tmparr);
     }
     // We're done. Delete it, now!
     $res = $db->query("DROP TABLE `custom_destinations`");
 }
예제 #15
0
function superfecta_hookProcess_core($viewing_itemid, $request)
{
    $db = \FreePBX::Database();
    // TODO: move sql to functions superfecta_did_(add, del, edit)
    if (!isset($request['action'])) {
        return;
    }
    $result = '';
    switch ($request['action']) {
        case 'addIncoming':
            if ($request['enable_superfecta'] == 'yes') {
                $sql = "REPLACE INTO superfecta_to_incoming (extension, cidnum, scheme) values (:extension, :cidnum,:superfecta_scheme)";
                $q = $db->prepare($sql);
                $q->bindParam(':extension', $request['extension'], \PDO::PARAM_STR);
                $q->bindParam(':cidnum', $request['cidnum'], \PDO::PARAM_STR);
                $q->bindParam(':superfecta_scheme', $request['superfecta_scheme'], \PDO::PARAM_STR);
                $q->execute();
                $result = $db->lastInsertId();
            }
            break;
        case 'delIncoming':
            $extarray = explode('/', $request['extdisplay'], 2);
            if (count($extarray) == 2) {
                $sql = "DELETE FROM superfecta_to_incoming WHERE extension = :extension AND cidnum = :cidnum";
                $q = $db->prepare($sql);
                $q->bindParam(':extension', $extarray[0], \PDO::PARAM_STR);
                $q->bindParam(':cidnum', $extarray[1], \PDO::PARAM_STR);
                $q->execute();
                $result = $db->lastInsertId();
            }
            break;
        case 'edtIncoming':
            // deleting and adding as in core module
            $extarray = explode('/', $request['extdisplay'], 2);
            if (count($extarray) == 2) {
                $sql = "DELETE FROM superfecta_to_incoming WHERE extension = :extension AND cidnum = :cidnum";
                $q = $db->prepare($sql);
                $q->bindParam(':extension', $extarray[0], \PDO::PARAM_STR);
                $q->bindParam(':cidnum', $extarray[1], \PDO::PARAM_STR);
                $q->execute();
            }
            if ($request['enable_superfecta'] == 'yes') {
                $sql = "REPLACE INTO superfecta_to_incoming (extension, cidnum, scheme) values (:extension, :cidnum,:superfecta_scheme)";
                $q = $db->prepare($sql);
                $q->bindParam(':extension', $request['extension'], \PDO::PARAM_STR);
                $q->bindParam(':cidnum', $request['cidnum'], \PDO::PARAM_STR);
                $q->bindParam(':superfecta_scheme', $request['superfecta_scheme'], \PDO::PARAM_STR);
                $q->execute();
                $result = $db->lastInsertId();
            }
            break;
    }
    return $result;
}
예제 #16
0
function callforward_get_config($engine)
{
    $modulename = 'callforward';
    // This generates the dialplan
    global $ext;
    global $amp_conf;
    switch ($engine) {
        case "asterisk":
            // If Using CF then set this so AGI scripts can determine
            //
            if ($amp_conf['USEDEVSTATE']) {
                $ext->addGlobal('CFDEVSTATE', 'TRUE');
            }
            if (is_array($featurelist = featurecodes_getModuleFeatures($modulename))) {
                foreach ($featurelist as $item) {
                    $featurename = $item['featurename'];
                    $fname = $modulename . '_' . $featurename;
                    if (function_exists($fname)) {
                        $fcc = new featurecode($modulename, $featurename);
                        $fc = $fcc->getCodeActive();
                        unset($fcc);
                        if ($fc != '') {
                            $fname($fc);
                        }
                    } else {
                        $ext->add('from-internal-additional', 'debug', '', new ext_noop($modulename . ": No func {$fname}"));
                        var_dump($item);
                    }
                }
            }
            // Create hints context for CF codes so a device can subscribe to the DND state
            //
            $fcc = new featurecode($modulename, 'cf_toggle');
            $cf_code = $fcc->getCodeActive();
            unset($fcc);
            if ($amp_conf['USEDEVSTATE'] && $cf_code != '') {
                $ext->addInclude('from-internal-additional', 'ext-cf-hints');
                $contextname = 'ext-cf-hints';
                $device_list = core_devices_list("all", 'full', true);
                $base_offset = strlen($cf_code);
                if (!empty($device_list) && is_array($device_list)) {
                    foreach ($device_list as $device) {
                        if ($device['tech'] == 'pjsip' || $device['tech'] == 'sip' || $device['tech'] == 'iax2') {
                            $offset = $base_offset + strlen($device['id']);
                            $ext->add($contextname, '_' . $cf_code . $device['id'] . '.', '', new ext_set("toext", '${EXTEN:' . $offset . '}'));
                            $ext->add($contextname, '_' . $cf_code . $device['id'] . '.', '', new ext_goto("setdirect", $cf_code, "app-cf-toggle"));
                        }
                    }
                }
                $sql = "SELECT LENGTH(id) as len FROM devices GROUP BY len";
                $sth = FreePBX::Database()->prepare($sql);
                $sth->execute();
                $rows = $sth->fetchAll(\PDO::FETCH_ASSOC);
                foreach ($rows as $row) {
                    $offset = $base_offset + $row['len'];
                    $ext->add($contextname, '_' . $cf_code . str_repeat('X', $row['len']), '', new ext_goto("1", $cf_code, "app-cf-toggle"));
                }
                $ext->addHint($contextname, "_{$cf_code}" . 'X.', "Custom:DEVCF" . '${EXTEN:' . strlen($cf_code) . '}');
            }
            break;
    }
}
예제 #17
0
 public function prune_backup_cache()
 {
     $dbh = \FreePBX::Database();
     // We want to delete anything that's older than 90 days.
     $date = new \DateTime("90 days ago");
     // Get the utime of that
     $purgebefore = $date->format("U");
     // Prepare statement
     $del = 'DELETE FROM `backup_cache` WHERE `id`=?';
     $delstmt = $dbh->prepare($del);
     // Find old ones
     $ret = $dbh->query('SELECT `id` FROM `backup_cache`')->fetchAll();
     foreach ($ret as $row) {
         $id = $row[0];
         // Avoid bad tables. This would be fixed by a mysqlcheck, but
         // it'll cause an exception in the interim.
         if (empty($id)) {
             continue;
         }
         // Explode it into sections. It's currently YYYYMMDD-HHMMSS-utime-....
         $sections = explode("-", $id);
         // If it's incorrectly formatted, or, its old, delete it.
         if (!isset($sections[2]) || $sections[2] < $purgebefore) {
             $delstmt->execute(array($id));
         }
     }
 }
예제 #18
0
파일: functions.inc.php 프로젝트: lidl/core
function core_routing_updatetrunks($route_id, &$trunks, $delete = false)
{
    global $db;
    $dbh = \FreePBX::Database();
    $insert_trunk = array();
    $seq = 0;
    foreach ($trunks as $trunk) {
        $insert_trunk[] = array($route_id, $trunk, $seq);
        $seq++;
    }
    if ($delete) {
        sql('DELETE FROM `outbound_route_trunks` WHERE `route_id`=' . q($route_id));
    }
    $stmt = $dbh->prepare('INSERT INTO `outbound_route_trunks` (`route_id`, `trunk_id`, `seq`) VALUES (?,?,?)');
    $ret = array();
    foreach ($insert_trunk as $t) {
        $ret[] = $stmt->execute($t);
    }
    return $ret;
}
예제 #19
0
 /**
  * Update gpg Signature check for a single module
  * @param {string} $modulename Raw Module Name
  */
 public function updateSignature($modulename)
 {
     try {
         $mod = FreePBX::GPG()->verifyModule($modulename);
         $revoked = $mod['status'] & GPG::STATE_REVOKED;
         //if revoked then disable
         if ($revoked) {
             $this->disable($modulename);
         }
         $sql = "UPDATE `modules` SET signature = ? WHERE modulename = ?";
         $sth = FreePBX::Database()->prepare($sql);
         $sth->execute(array(json_encode($mod), $modulename));
     } catch (\Exception $e) {
         $mod = null;
     }
     return $mod;
 }
예제 #20
0
<?php

if (!defined('FREEPBX_IS_AUTH')) {
    die('No direct script access allowed');
}
$dbh = \FreePBX::Database();
global $db;
global $amp_conf;
$sql = "\nCREATE TABLE IF NOT EXISTS `ringgroups`\n(\n\t`grpnum` VARCHAR( 20 ) NOT NULL ,\n\t`strategy` VARCHAR( 50 ) NOT NULL ,\n\t`grptime` SMALLINT NOT NULL ,\n\t`grppre` VARCHAR( 100 ) NULL ,\n\t`grplist` VARCHAR( 255 ) NOT NULL ,\n\t`annmsg_id` INTEGER,\n\t`postdest` VARCHAR( 255 ) NULL ,\n\t`description` VARCHAR( 35 ) NOT NULL ,\n\t`alertinfo` VARCHAR ( 255 ) NULL ,\n\t`remotealert_id` INTEGER,\n\t`needsconf` VARCHAR ( 10 ),\n\t`progress` VARCHAR ( 10 ),\n\t`toolate_id` INTEGER,\n  `ringing` VARCHAR( 80 ) NULL,\n\t`cwignore` VARCHAR ( 10 ),\n\t`cfignore` VARCHAR ( 10 ),\n\t`cpickup` VARCHAR ( 10 ),\n\t`recording` VARCHAR ( 10 ) default 'dontcare',\n\tPRIMARY KEY  (`grpnum`)\n)\n";
$check = $db->query($sql);
if (DB::IsError($check)) {
    die_freepbx("Can not create ringgroups table");
}
// The following updates were all pre-2.5 when sqlite3 was not supported)
//
if ($amp_conf["AMPDBENGINE"] != "sqlite3") {
    // Version 1.1 upgrade
    $sql = "SELECT description FROM ringgroups";
    $check = $db->getRow($sql, DB_FETCHMODE_ASSOC);
    if (DB::IsError($check)) {
        // add new field
        $sql = "ALTER TABLE ringgroups ADD description VARCHAR( 35 ) NULL ;";
        $result = $db->query($sql);
        if (DB::IsError($result)) {
            die_freepbx($result->getDebugInfo());
        }
        // update existing groups
        $sql = "UPDATE ringgroups SET description = CONCAT('Ring Group ', grpnum) WHERE description IS NULL ;";
        $result = $db->query($sql);
        if (DB::IsError($result)) {
            die_freepbx($result->getDebugInfo());