function _module_backtrace()
{
    $trace = debug_backtrace();
    $function = $trace[1]['function'];
    $line = $trace[1]['line'];
    $file = $trace[1]['file'];
    freepbx_log(FPBX_LOG_WARNING, 'Depreciated Function ' . $function . ' detected in ' . $file . ' on line ' . $line);
}
Example #2
0
function framework_print_errors($src, $dst, $errors)
{
    out("error copying files:");
    out(sprintf(_("'cp -rf' from src: '%s' to dst: '%s'...details follow"), $src, $dst));
    freepbx_log(FPBX_LOG_ERROR, sprintf(_("framework couldn't copy file to %s"), $dst));
    foreach ($errors as $error) {
        out("{$error}");
        freepbx_log(FPBX_LOG_ERROR, _("cp error output: {$error}"));
    }
}
 public function showPage()
 {
     $media = $this->FreePBX->Media();
     $action = !empty($_REQUEST['action']) ? $_REQUEST['action'] : "";
     switch ($action) {
         case "edit":
             $data = $this->getRecordingById($_REQUEST['id']);
             $fcc = new \featurecode("recordings", 'edit-recording-' . $_REQUEST['id']);
             $rec_code = $fcc->getCode();
             $data['rec_code'] = $rec_code != '' ? $rec_code : $this->fcbase . $_REQUEST['id'];
         case "add":
             $data = isset($data) ? $data : array();
             $supported = $media->getSupportedFormats();
             ksort($supported['in']);
             ksort($supported['out']);
             $langs = $this->FreePBX->Soundlang->getLanguages();
             $default = $this->FreePBX->Soundlang->getLanguage();
             $sysrecs = $this->getSystemRecordings();
             $jsonsysrecs = json_encode($sysrecs);
             $message = '';
             if (json_last_error() !== JSON_ERROR_NONE) {
                 $message = sprintf(_("There was an error reading system recordings (%s)"), json_last_error_msg());
                 freepbx_log(FPBX_LOG_WARNING, "JSON decode error: " . json_last_error_msg());
                 $jsonsysrecs = array();
                 $sysrecs = array();
             }
             $supportedHTML5 = $media->getSupportedHTML5Formats();
             $convertto = array_intersect($supported['out'], $this->convert);
             $html = load_view(__DIR__ . "/views/form.php", array("message" => $message, "jsonsysrecs" => $jsonsysrecs, "convertto" => $convertto, "supportedHTML5" => implode(",", $supportedHTML5), "data" => $data, "default" => $default, "supported" => $supported, "langs" => $langs, "sysrecs" => $sysrecs));
             break;
         case "delete":
             $this->delRecording($_REQUEST['id']);
         default:
             $html = load_view(__DIR__ . "/views/grid.php", array());
             break;
     }
     return $html;
 }
Example #4
0
        $confs = $db_cdr->getRow($sql, DB_FETCHMODE_ASSOC);
        outn(_("checking if recordingfile file field needed in cdr.."));
        if (DB::IsError($confs)) {
            // no error... Already done
            $sql = "ALTER TABLE cdr ADD recordingfile VARCHAR ( 255 ) NOT NULL default ''";
            $results = $db_cdr->query($sql);
            if (DB::IsError($results)) {
                out(_("failed"));
                freepbx_log(FPBX_LOG_ERROR, "failed to add recordingfile field to cdr table during migration");
            }
            out(_("added"));
        } else {
            out(_("already there"));
        }
        $sql = "SELECT did FROM cdr";
        $confs = $db_cdr->getRow($sql, DB_FETCHMODE_ASSOC);
        outn(_("checking if did file field needed in cdr.."));
        if (DB::IsError($confs)) {
            // no error... Already done
            $sql = "ALTER TABLE cdr ADD did VARCHAR ( 50 ) NOT NULL default ''";
            $results = $db_cdr->query($sql);
            if (DB::IsError($results)) {
                out(_("failed"));
                freepbx_log(FPBX_LOG_ERROR, "failed to add did field to cdr table during migration");
            }
            out(_("added"));
        } else {
            out(_("already there"));
        }
    }
}
Example #5
0
//connect to cdrdb if requestes
if ($bootstrap_settings['cdrdb']) {
    $dsn = array('phptype' => $amp_conf['CDRDBTYPE'] ? $amp_conf['CDRDBTYPE'] : $amp_conf['AMPDBENGINE'], 'hostspec' => $amp_conf['CDRDBHOST'] ? $amp_conf['CDRDBHOST'] : $amp_conf['AMPDBHOST'], 'username' => $amp_conf['CDRDBUSER'] ? $amp_conf['CDRDBUSER'] : $amp_conf['AMPDBUSER'], 'password' => $amp_conf['CDRDBPASS'] ? $amp_conf['CDRDBPASS'] : $amp_conf['AMPDBPASS'], 'port' => $amp_conf['CDRDBPORT'] ? $amp_conf['CDRDBPORT'] : '3306', 'database' => $amp_conf['CDRDBNAME'] ? $amp_conf['CDRDBNAME'] : 'asteriskcdrdb');
    $cdrdb = DB::connect($dsn);
}
$bootstrap_settings['astman_connected'] = false;
if (!$bootstrap_settings['skip_astman']) {
    require_once $dirname . '/libraries/php-asmanager.php';
    $astman = new AGI_AsteriskManager($bootstrap_settings['astman_config'], $bootstrap_settings['astman_options']);
    // attempt to connect to asterisk manager proxy
    if (!$amp_conf["ASTMANAGERPROXYPORT"] || !($res = $astman->connect($amp_conf["ASTMANAGERHOST"] . ":" . $amp_conf["ASTMANAGERPROXYPORT"], $amp_conf["AMPMGRUSER"], $amp_conf["AMPMGRPASS"], $bootstrap_settings['astman_events']))) {
        // attempt to connect directly to asterisk, if no proxy or if proxy failed
        if (!($res = $astman->connect($amp_conf["ASTMANAGERHOST"] . ":" . $amp_conf["ASTMANAGERPORT"], $amp_conf["AMPMGRUSER"], $amp_conf["AMPMGRPASS"], $bootstrap_settings['astman_events']))) {
            // couldn't connect at all
            unset($astman);
            freepbx_log(FPBX_LOG_CRITICAL, "Connection attmempt to AMI failed");
        } else {
            $bootstrap_settings['astman_connected'] = true;
        }
    }
} else {
    $bootstrap_settings['astman_connected'] = true;
}
//Because BMO was moved upward we have to inject this lower
if (isset($astman)) {
    FreePBX::create()->astman = $astman;
}
//include gui functions + auth if nesesarry
// If set to freepbx_auth but we are in a cli mode, then don't bother authenticating either way.
// TODO: is it ever possible through an apache or httplite configuration to run a web launched php script
//       as 'cli' ? Also, from a security perspective, should we just require this always be set to false
Example #6
0
 function output()
 {
     global $version;
     if (version_compare($version, "12.5", "<")) {
         global $chan_dahdi;
         if ($chan_dahdi) {
             $command = 'DAHDIBarge';
         } else {
             $command = 'ZapBarge';
         }
         return "{$command}(" . $this->data . ")";
     } else {
         $trace = debug_backtrace();
         $function = $trace[1]['function'];
         $line = $trace[1]['line'];
         $file = $trace[1]['file'];
         freepbx_log(FPBX_LOG_WARNING, 'Depreciated Asterisk Function ' . $function . ' detected in ' . $file . ' on line ' . $line);
         $n = new ext_noop('Using zapbarge or DAHDibarge has been removed');
         $n->data = 'Using zapbarge or DAHDibarge has been removed';
         return $n->output();
     }
 }
 /** prepares a value to be inserted into the configuration settings using the
  * type information and any provided validation rules. Integers that are out
  * of range will be set to the lowest or highest values. Validation issues
  * are recorded and can be examined with the get_last_update_status() method.
  *
  * @param mixed   integer, string or boolean to be prepared
  * @param type    the type being validated
  * @param bool    emptyok attribute of this setting
  * @param mixed   options string or array used for validating the type
  *
  * @return string value to be inserted into the store
  *                last_update_status is updated with any relevant issues
  */
 function _prepare_conf_value($value, $type, $emptyok, $options = false)
 {
     switch ($type) {
         case CONF_TYPE_BOOL:
             $ret = $value ? 1 : 0;
             $this->_last_update_status['validated'] = true;
             break;
         case CONF_TYPE_SELECT:
             $val_arr = explode(',', $options);
             if (in_array($value, $val_arr)) {
                 $ret = $value;
                 $this->_last_update_status['validated'] = true;
             } else {
                 $ret = null;
                 $this->_last_update_status['validated'] = false;
                 $this->_last_update_status['msg'] = _("Invalid value supplied to select");
                 $this->_last_update_status['saved_value'] = $ret;
                 $this->_last_update_status['saved'] = false;
                 //
                 // NOTE: returning from function early!
                 return $ret;
             }
             break;
         case CONF_TYPE_FSELECT:
             if (!is_array($options)) {
                 $options = unserialize($options);
             }
             if (array_key_exists($value, $options)) {
                 $ret = $value;
                 $this->_last_update_status['validated'] = true;
             } else {
                 $ret = null;
                 $this->_last_update_status['validated'] = false;
                 $this->_last_update_status['msg'] = _("Invalid value supplied to select");
                 $this->_last_update_status['saved_value'] = $ret;
                 $this->_last_update_status['saved'] = false;
                 //
                 // NOTE: returning from function early!
                 return $ret;
             }
             break;
         case CONF_TYPE_DIR:
             // we don't consider trailing '/' in a directory an error for validation purposes
             $value = rtrim($value, '/');
             // NOTE: fallthrough to CONF_TYPE_TEXT, NO break on purpose!
             //       |
             //       |
             //       V
         // NOTE: fallthrough to CONF_TYPE_TEXT, NO break on purpose!
         //       |
         //       |
         //       V
         case CONF_TYPE_TEXT:
         case CONF_TYPE_TEXTAREA:
             if ($value == '' && !$emptyok) {
                 $this->_last_update_status['validated'] = false;
                 $this->_last_update_status['msg'] = _("Empty value not allowed for this field");
             } else {
                 if ($options != '' && $value != '') {
                     if (preg_match($options, $value)) {
                         $ret = $value;
                         $this->_last_update_status['validated'] = true;
                     } else {
                         $ret = null;
                         $this->_last_update_status['validated'] = false;
                         $this->_last_update_status['msg'] = sprintf(_("Invalid value supplied violates the validation regex: %s"), $options);
                         $this->_last_update_status['saved_value'] = $ret;
                         $this->_last_update_status['saved'] = false;
                         //
                         // NOTE: returning from function early!
                         return $ret;
                     }
                 } else {
                     $ret = $value;
                     $this->_last_update_status['validated'] = true;
                 }
             }
             //if cli then dont echo out newlines its confusing
             if (php_sapi_name() === 'cli' && $type === CONF_TYPE_TEXTAREA) {
                 //$ret = str_replace(array("\r", "\n", "\r\n"), ",", $ret);
             }
             break;
         case CONF_TYPE_INT:
             $ret = !is_numeric($value) && $value != '' ? '' : $value;
             $ret = $emptyok && (string) trim($ret) === '' ? '' : (int) $ret;
             if ($options != '' && (string) $ret !== '') {
                 $range = is_array($options) ? $options : explode(',', $options);
                 switch (true) {
                     case $ret < $range[0]:
                         $ret = $range[0];
                         $this->_last_update_status['validated'] = false;
                         $this->_last_update_status['msg'] = sprintf(_("Value [%s] out of range, changed to [%s]"), $value, $ret);
                         break;
                     case $ret > $range[1]:
                         $ret = $range[1];
                         $this->_last_update_status['validated'] = false;
                         $this->_last_update_status['msg'] = sprintf(_("Value [%s] out of range, changed to [%s]"), $value, $ret);
                         break;
                     default:
                         $this->_last_update_status['validated'] = (string) $ret === (string) $value;
                         break;
                 }
             } else {
                 $this->_last_update_status['validated'] = (string) $ret === (string) $value;
             }
             break;
         default:
             $this->_last_update_status['validated'] = false;
             freepbx_log(FPBX_LOG_ERROR, sprintf(_("unknown type: [%s]"), $type));
             break;
     }
     $this->_last_update_status['saved_value'] = $ret;
     $this->_last_update_status['saved'] = true;
     return $ret;
 }
Example #8
0
function show_deprecated($message = "", $dismisable = true, $logit = false)
{
    if ($dismisable) {
        $html = '<div class="alert alert-warning alert-dismissable hidden depnotice" data-for="dep">';
        $html .= '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
    } else {
        $html = '<div class="alert alert-warning hidden">';
    }
    $html .= '<h3><i class="fa fa-warning"></i> ' . _("This Module has been deprecated") . '</h3>';
    $html .= $message;
    $html .= '</div>';
    $html .= '<script>';
    $html .= '$( document ).ready(function() {';
    $html .= 'if($.cookie(res[2]+"depdis") != "1"){$(".depnotice").each(function(){$(this).removeClass("hidden")})}';
    $html .= '$(".alert").bind("closed.bs.alert", function(){if($(this).data("for") == "dep"){$.cookie(res[2]+"depdis", "1")}});';
    $html .= '});';
    $html .= '</script>';
    if ($logit) {
        freepbx_log($message);
        dbug($message);
    }
    return $html;
}
Example #9
0
    $result = $db->query($sql);
    if (DB::IsError($result)) {
        out(_("Unable to add index to tech field in devices"));
        freepbx_log(FPBX_LOG_ERROR, "Failed to add index to tech field in the devices table");
    } else {
        out(_("Adding index to tech field in the devices"));
    }
}
$sql = "SHOW KEYS FROM users WHERE Key_name='extension'";
$check = $db->getOne($sql);
if (empty($check)) {
    $sql = "ALTER TABLE users ADD KEY `extension` (`extension`)";
    $result = $db->query($sql);
    if (DB::IsError($result)) {
        out(_("Unable to add index to extensions field in users"));
        freepbx_log(FPBX_LOG_ERROR, "Failed to add index to extensions field in the users table");
    } else {
        out(_("Adding index to extensions field in the users"));
    }
}
// The following are from General Settings that may need to be migrated.
// We will first create them all, the define_conf_settings() method will
// not change the value if already set. We will update the settings
// to the currently configured values from the globals table afer defining
// them here and then remove them from the globals table.
$globals_convert['VMX_CONTEXT'] = 'from-internal';
$globals_convert['VMX_PRI'] = '1';
$globals_convert['VMX_TIMEDEST_CONTEXT'] = '';
$globals_convert['VMX_TIMEDEST_EXT'] = 'dovm';
$globals_convert['VMX_TIMEDEST_PRI'] = '1';
$globals_convert['VMX_LOOPDEST_CONTEXT'] = '';
Example #10
0
 /**
  * FreePBX Logging
  *
  * @param const $level Notification Level to show (can be blank for all)
  * @param string $module Raw name of the module requesting
  * @param string $id ID of the notification
  * @param string $display_text The text that will be displayed as the subject/header of the message
  * @ignore
  */
 function _freepbx_log($level, $module, $id, $display_text, $extended_text = null)
 {
     global $amp_conf;
     if ($amp_conf['LOG_NOTIFICATIONS']) {
         if ($extended_text) {
             $display_text .= " ({$extended_text})";
         }
         freepbx_log($level, "[NOTIFICATION]-[{$module}]-[{$id}] - {$display_text}");
     }
 }
Example #11
0
function backup_migrate_legacy($bu)
{
    global $amp_conf;
    $legacy_name = '';
    $name = pathinfo($bu, PATHINFO_BASENAME);
    if (substr($name, -7) != '.tar.gz') {
        return false;
    }
    //get legacy name based on the directory the legacy backup was origionally created in
    //were expcecting to see something like: /tmp/ampbackups.20110310.16.00.00/
    //in the tarball
    $cmd[] = fpbx_which('tar');
    $cmd[] = 'tf';
    $cmd[] = $bu;
    exec(implode(' ', $cmd), $res);
    unset($cmd);
    foreach ($res as $r) {
        if (preg_match('/\\/tmp\\/ampbackups\\.([\\d]{8}(\\.[\\d]{2}){3})\\//', $r, $legacy_name)) {
            if (isset($legacy_name[1])) {
                $legacy_name = $legacy_name[1];
                break;
            }
        }
    }
    if (!$legacy_name) {
        return false;
    }
    //create directory where tarball will be exctracted to
    $dir = $amp_conf['ASTSPOOLDIR'] . '/tmp/' . $legacy_name;
    mkdir($dir, 0755, true);
    $cmd[] = fpbx_which('tar');
    $cmd[] = '-zxf';
    $cmd[] = $bu;
    $cmd[] = ' -C ' . $dir;
    exec(implode(' ', $cmd));
    unset($cmd);
    $dir2 = $dir . '/tmp/ampbackups.' . $legacy_name;
    //exctract sub tarballs
    foreach (scandir($dir2) as $file) {
        if (substr($file, -7) == '.tar.gz') {
            $cmd[] = fpbx_which('tar');
            $cmd[] = '-zxf';
            $cmd[] = $dir2 . '/' . $file;
            $cmd[] = ' -C ' . $dir2;
            exec(implode(' ', $cmd));
            unset($cmd);
            unlink($dir2 . '/' . $file);
        }
    }
    //add files to manifest
    $ret['file_list'] = scandirr($dir2);
    $ret['file_count'] = count($ret['file_list'], COUNT_RECURSIVE);
    $ret['fpbx_db'] = '';
    $ret['fpbx_cdrdb'] = '';
    //format db's + add to manifest
    if (is_file($dir2 . '/astdb.dump')) {
        //rename file
        rename($dir2 . '/astdb.dump', $dir2 . '/astdb');
        //remove it from the file_list
        unset($ret['file_list'][array_search('astdb.dump', $ret['file_list'])]);
        //set the manifest
        $ret['astdb'] = 'astdb';
    } elseif (is_file($dir2 . '/tmp/ampbackups.' . $legacy_name . '/astdb.dump')) {
        rename($dir2 . '/tmp/ampbackups.' . $legacy_name . '/astdb.dump', $dir2 . '/astdb');
        $ret['astdb'] = 'astdb';
    }
    //serialize the astdb
    if (!empty($ret['astdb'])) {
        $astdb = array();
        foreach (file($dir2 . '/astdb') as $line) {
            $line = explode('] [', trim($line, '[]/'));
            //chuck the bad values
            if ($line[1] == '<bad value>') {
                continue;
            }
            //expldoe the key
            list($family, $key) = explode('/', $line[0], 2);
            //add to astdb array
            $astdb[$family][$key] = trim(trim($line[1]), ']');
        }
        file_put_contents($dir2 . '/astdb', serialize($astdb));
    }
    //migrate mysql files to a format that we can restore from
    $src = $dir2 . '/asterisk.sql';
    if (is_file($src)) {
        $dst = $dir2 . '/mysql-db.sql';
        unset($ret['file_list'][array_search('asterisk.sql', $ret['file_list'])]);
        //remove from manifest
        $ret['fpbx_db'] = 'mysql-db';
        $ret['mysql']['db'] = array('file' => 'mysql-db.sql');
        // remove SET and comments that later break restores when using pear
        $cmd[] = fpbx_which('grep');
        $cmd[] = "-v '^\\/\\*\\|^SET\\|^--'";
        $cmd[] = $src;
        $cmd[] = ' > ' . $dst;
        exec(implode(' ', $cmd), $file, $status);
        if ($status) {
            // The grep failed, if there is a $dst file remove it and either way rename the $src
            freepbx_log(FPBX_LOG_ERROR, _("Failed converting asterisk.sql to proper format, renaming to mysql-db.sql in current state"));
            if (is_file($dst)) {
                unlink($dst);
            }
            rename($src, $dst);
        } else {
            unlink($src);
        }
        unset($cmd, $file);
    }
    $src = $dir2 . '/asteriskcdr.sql';
    if (is_file($src)) {
        $dst = $dir2 . '/mysql-cdr.sql';
        unset($ret['file_list'][array_search('asteriskcdr.sql', $ret['file_list'])]);
        //remove from manifest
        $ret['fpbx_cdrdb'] = 'mysql-cdr';
        $ret['mysql']['cdr'] = array('file' => 'mysql-cdr.sql');
        // remove SET and comments that later break restores when using pear
        $cmd[] = fpbx_which('grep');
        $cmd[] = "-v '^\\/\\*\\|^SET\\|^--'";
        $cmd[] = $src;
        $cmd[] = ' > ' . $dst;
        exec(implode(' ', $cmd), $file, $status);
        if ($status) {
            // The grep failed, if there is a $dst file remove it and either way rename the $src
            freepbx_log(FPBX_LOG_ERROR, _("Failed converting asteriskcdr.sql to proper format, renaming to mysql-cdr.sql in current state"));
            if (is_file($dst)) {
                unlink($dst);
            }
            rename($src, $dst);
        } else {
            unlink($src);
        }
        unset($cmd, $file);
    }
    $ret['mysql_count'] = $ret['mysql'] ? count($ret['mysql']) : 0;
    $ret['astdb_count'] = $ret['astdb'] ? count($ret['astdb']) : 0;
    //delete legacy's tmp dir
    system('rm -rf ' . $dir2 . '/tmp');
    unset($ret['file_list']['tmp']);
    //store manifest
    file_put_contents($dir2 . '/manifest', serialize($ret));
    //build new tarball
    $dest = $amp_conf['ASTSPOOLDIR'] . '/tmp/' . 'backuptmp-slegacy-' . time() . '-' . $legacy_name . '.tgz';
    $cmd[] = fpbx_which('tar');
    $cmd[] = '-zcf';
    $cmd[] = $dest;
    $cmd[] = '-C ' . $dir2;
    $cmd[] = '.';
    exec(implode(' ', $cmd));
    unset($cmd);
    //remove tmp working dir
    system('rm -rf ' . $dir);
    return $dest;
}
Example #12
0
/** Include additional files requested in module.xml for install and uninstall
 * @param array   The modulexml array
 * @param string  The action to perform, either 'install' or 'uninstall'
 * @return boolean   If the action was successful, currently TRUE so we don't prevent the install
 */
function _module_runscripts_include($modulexml, $type)
{
    global $amp_conf;
    foreach ($modulexml as $modulename => $items) {
        $moduledir = $amp_conf["AMPWEBROOT"] . "/admin/modules/" . $modulename;
        if (isset($items['fileinclude'][$type]) && !empty($items['fileinclude'][$type])) {
            if (!is_array($items['fileinclude'][$type])) {
                $ret = _modules_doinclude($moduledir . '/' . $items['fileinclude'][$type], $modulename);
                if (!$ret) {
                    freepbx_log(FPBX_LOG_WARNING, sprintf(_("failed to include %s during %s of the %s module."), $items['fileinclude'][$type], $type, $modulename));
                }
            } else {
                foreach ($items['fileinclude'][$type] as $key => $filename) {
                    $ret = _modules_doinclude($moduledir . '/' . $filename, $modulename);
                    if (!$ret) {
                        freepbx_log(FPBX_LOG_WARNING, sprintf(_("failed to include %s during %s of the %s module."), $filename, $type, $modulename));
                    }
                }
            }
        }
    }
    return true;
}
Example #13
0
}
if (!function_exists("out")) {
    function out($text)
    {
        echo $text . "<br />";
    }
}
// Remove this section in FreePBX 14
$sql = "SHOW KEYS FROM `{$db_name}`.`{$db_table_name}` WHERE Key_name='did'";
$check = $dbcdr->getOne($sql);
if (empty($check)) {
    $sql = "ALTER TABLE `{$db_name}`.`{$db_table_name}` ADD INDEX `did` (`did` ASC)";
    $result = $dbcdr->query($sql);
    if (DB::IsError($result)) {
        out(_("Unable to add index to did field in the cdr table"));
        freepbx_log(FPBX_LOG_ERROR, "Failed to add index to did field in the cdr table");
    } else {
        out(_("Adding index to did field in the cdr table"));
    }
}
// Remove this section in FreePBX 14
$db_name = FreePBX::Config()->get('CDRDBNAME');
$db_host = FreePBX::Config()->get('CDRDBHOST');
$db_port = FreePBX::Config()->get('CDRDBPORT');
$db_user = FreePBX::Config()->get('CDRDBUSER');
$db_pass = FreePBX::Config()->get('CDRDBPASS');
$db_table = FreePBX::Config()->get('CDRDBTABLENAME');
$dbt = FreePBX::Config()->get('CDRDBTYPE');
$db_hash = array('mysql' => 'mysql', 'postgres' => 'pgsql');
$dbt = !empty($dbt) ? $dbt : 'mysql';
$db_type = $db_hash[$dbt];
    public function install()
    {
        global $db;
        global $amp_conf;
        $sql[] = 'CREATE TABLE IF NOT EXISTS `restapi_general` (
		  `keyword` varchar(50),
		  `value` varchar(150) default NULL,
		  UNIQUE KEY `keyword` (`keyword`)
		);';
        $sql[] = 'CREATE TABLE IF NOT EXISTS `restapi_log_event_details` (
		  `id` int(11) default NULL AUTO_INCREMENT,
		  `e_id` int(11) default NULL,
		  `time` int(11) default NULL,
		  `event` varchar(150) default NULL,
		  `data` text,
		  `trigger` text,
		   UNIQUE KEY `id` (`id`),
		   KEY `e_id` (`e_id`)
		);';
        $sql[] = 'CREATE TABLE IF NOT EXISTS `restapi_log_events` (
		  `id` int(11) default NULL AUTO_INCREMENT,
		  `time` int(11) default NULL,
		  `token` varchar(75) default NULL,
		  `signature` varchar(150) default NULL,
		  `ip` varchar(20) default NULL,
		  `server` varchar(75) default NULL,
		   UNIQUE KEY `id` (`id`),
		   KEY `time` (`time`),
		   KEY `token` (`token`)
		);';
        $sql[] = 'CREATE TABLE IF NOT EXISTS `restapi_token_details` (
		  `token_id` int(11) default NULL,
		  `key` varchar(50) default NULL,
		  `value` text default NULL
		);';
        $sql[] = 'CREATE TABLE IF NOT EXISTS `restapi_tokens` (
		  `id` int(11) default NULL AUTO_INCREMENT,
		  `name` varchar(150) default NULL,
		  `desc` varchar(250) default NULL,
		  UNIQUE KEY `id` (`id`)
		);';
        $sql[] = 'CREATE TABLE IF NOT EXISTS `restapi_token_user_mapping` (
		  `user` varchar(25) default NULL,
		  `token_id` int(11) default NULL
		);';
        $firstinstall = false;
        $q = $db->query('SELECT * FROM restapi_general;');
        if (\DB::isError($q)) {
            $firstinstall = true;
            $sql[] = 'INSERT IGNORE INTO `restapi_general` VALUES
			  ("status", "normal"),
			  ("token", "' . restapi_tokens_generate() . '"),
			  ("tokenkey", "' . restapi_tokens_generate() . '");';
        }
        foreach ($sql as $statement) {
            $check = $db->query($statement);
            if (\DB::IsError($check)) {
                die_freepbx("Can not execute {$statement} : " . $check->getMessage() . "\n");
            }
        }
        $sql = "SHOW KEYS FROM restapi_log_event_details WHERE Key_name='e_id'";
        $check = $db->getOne($sql);
        if (empty($check)) {
            $sql = "ALTER TABLE restapi_log_event_details ADD KEY `e_id` (`e_id`)";
            $result = $db->query($sql);
            if (\DB::IsError($result)) {
                out(_("Unable to add index to e_id field in restapi_log_event_details table"));
                freepbx_log(FPBX_LOG_ERROR, "Failed to add index to e_id field in the restapi_log_event_details table");
            } else {
                out(_("Adding index to e_id field in the restapi_log_event_details table"));
            }
        }
        $sql = "SHOW KEYS FROM restapi_log_events WHERE Key_name='time'";
        $check = $db->getOne($sql);
        if (empty($check)) {
            $sql = "ALTER TABLE restapi_log_events ADD KEY `time` (`time`), ADD KEY `token` (`token`)";
            $result = $db->query($sql);
            if (\DB::IsError($result)) {
                out(_("Unable to add index to time field in restapi_log_events table"));
                freepbx_log(FPBX_LOG_ERROR, "Failed to add index to time field in the restapi_log_events table");
            } else {
                out(_("Adding index to time field in the restapi_log_events table"));
            }
        }
        $sql = "SELECT data_type FROM information_schema.columns WHERE table_name = 'restapi_token_details' AND column_name = 'value' AND data_type = 'varchar'";
        $check = $db->getOne($sql);
        if (!empty($check)) {
            $sql = "ALTER TABLE restapi_token_details MODIFY `value` TEXT";
            $result = $db->query($sql);
            if (\DB::IsError($result)) {
                out(_("Unable to modify data type of value field in restapi_token_details table"));
            } else {
                out(_("Modifying data type of value field in the restapi_token_details table"));
            }
        }
        if (!file_exists($amp_conf['AMPWEBROOT'] . '/restapi')) {
            @mkdir($amp_conf['AMPWEBROOT'] . '/restapi');
        }
        if (!file_exists($amp_conf['AMPWEBROOT'] . '/restapi/rest.php')) {
            @symlink(dirname(__FILE__) . '/rest.php', $amp_conf['AMPWEBROOT'] . '/restapi/rest.php');
        }
        $mod_info = module_getinfo('restapi');
        if (!empty($mod_info['restapi']) && version_compare($mod_info['restapi']['dbversion'], '2.11.1.2', '<')) {
            out('Migrating Token Users to User Manager');
            $sql = 'SELECT * FROM restapi_token_user_mapping';
            $users = sql($sql, 'getAll', DB_FETCHMODE_ASSOC);
            if (!empty($users)) {
                $usermapping = array();
                $userman = $this->freepbx->Userman;
                $umusers = array();
                $umusersn = array();
                foreach ($userman->getAllUsers() as $user) {
                    $umusersn[] = $user['username'];
                    if ($user['default_extension'] == 'none') {
                        continue;
                    }
                    $umusers[$user['default_extension']] = $user['id'];
                }
                foreach ($users as $user) {
                    $sql = "SELECT * FROM restapi_tokens WHERE `id` = " . $user['token_id'];
                    $tokenDetails = sql($sql, 'getAll', DB_FETCHMODE_ASSOC);
                    $ucpuser = $user['user'];
                    out('Found Token ' . $tokenDetails[0]['name']);
                    if (empty($usermapping[$user['user']]['id'])) {
                        if (isset($umusers[$user['user']])) {
                            $id = $umusers[$user['user']];
                            $uInfo = $userman->getUserByID($id);
                            try {
                                $userman->updateUser($id, $uInfo['username'], $uInfo['username'], $uInfo['default_extension'], $tokenDetails[0]['desc']);
                            } catch (\Exception $e) {
                                continue;
                            }
                        } else {
                            out('Creating a User Manager User called ' . $ucpuser . ' for token ' . $tokenDetails[0]['name']);
                            try {
                                $output = $userman->addUser($ucpuser, bin2hex(openssl_random_pseudo_bytes(6)), $user['user'], $tokenDetails[0]['desc']);
                            } catch (\Exception $e) {
                                $output['status'] = false;
                            }
                            if (!$output['status']) {
                                out('User confliction detected, attempting to autogenerate a username for token ' . $tokenDetails[0]['name']);
                                try {
                                    $output = $userman->addUser(bin2hex(openssl_random_pseudo_bytes(6)), bin2hex(openssl_random_pseudo_bytes(6)), $user['user'], $tokenDetails[0]['desc']);
                                } catch (\Exception $e) {
                                    $output['status'] = false;
                                }
                                if (!$output['status']) {
                                    out('Username auto generation failed, skipping token ' . $tokenDetails[0]['name']);
                                    continue;
                                }
                            }
                            $id = $output['id'];
                        }
                    } else {
                        out('Adding token ' . $tokenDetails[0]['name'] . ' to  User ' . $ucpuser);
                        $id = $usermapping[$user['user']]['id'];
                    }
                    $sql = "UPDATE restapi_token_user_mapping SET user = '******' WHERE user = '******'user'] . "'";
                    sql($sql);
                    $sql = "SELECT value FROM restapi_token_details WHERE `key` = 'users' AND token_id = " . $user['token_id'];
                    $uljson = sql($sql, 'getOne');
                    $ul = json_decode($uljson, true);
                    if ($ul[0] == "*") {
                        $ul = array();
                        foreach (core_users_list() as $list) {
                            $ul[] = $list[0];
                        }
                    }
                    $devices = $userman->getAssignedDevices($id);
                    $devices = !empty($devices) ? $devices : array();
                    foreach ($ul as $d) {
                        if (!in_array($d, $devices)) {
                            $devices[] = $d;
                        }
                    }
                    out('Attaching devices ' . implode(',', $ul) . ' from token ' . $tokenDetails[0]['name'] . ' to user ' . $ucpuser);
                    $userman->setAssignedDevices($id, $devices);
                    $usermapping[$user['user']]['id'] = $id;
                }
            }
        }
        //migrate to valid settings
        //this needs more work.
        if (function_exists('restapi_user_get_user_tokens') && function_exists('restapi_tokens_put')) {
            $users = $this->userman->getAllUsers();
            foreach ($users as $user) {
                $tokens = \restapi_user_get_user_tokens($user['id']);
                foreach ($tokens as $id => $token) {
                    $data = \restapi_tokens_get($token);
                    if (!empty($data['users']) && in_array("*", $data['users'])) {
                        $data['users'] = array($user['default_extension']);
                        \restapi_tokens_put($data);
                    }
                }
            }
        }
    }
Example #15
0
 /**
  * Sends a password reset email
  * @param {int} $id The userid
  */
 public function sendPassResetEmail($id)
 {
     global $amp_conf;
     $user = $this->getUserByID($id);
     if (empty($user) || empty($user['email'])) {
         return false;
     }
     $token = $this->Userman->generatePasswordResetToken($id);
     if (empty($token)) {
         freepbx_log(FPBX_LOG_NOTICE, sprintf(_("A token has already been generated for %s, not sending email again"), $user['username']));
         return false;
     }
     $user['token'] = $token['token'];
     $user['brand'] = $this->brand;
     $user['host'] = (!empty($_SERVER["HTTPS"]) ? 'https://' : 'http://') . $_SERVER["SERVER_NAME"];
     $user['link'] = $user['host'] . "/ucp/?forgot=" . $user['token'];
     $user['valid'] = date("h:i:s A", $token['valid']);
     $ports = array();
     if ($this->FreePBX->Modules->moduleHasMethod("sysadmin", "getPorts")) {
         $ports = \FreePBX::Sysadmin()->getPorts();
     } else {
         if (!function_exists('sysadmin_get_portmgmt') && $this->FreePBX->Modules->checkStatus('sysadmin') && file_exists($this->FreePBX->Config()->get('AMPWEBROOT') . '/admin/modules/sysadmin/functions.inc.php')) {
             include $this->FreePBX->Config()->get('AMPWEBROOT') . '/admin/modules/sysadmin/functions.inc.php';
         }
         if (function_exists('sysadmin_get_portmgmt')) {
             $ports = sysadmin_get_portmgmt();
         }
     }
     if (!empty($ports['ucp'])) {
         $user['host'] = $user['host'] . ":" . $ports['ucp'];
         $user['link'] = $user['host'] . "/?forgot=" . $user['token'];
     }
     $template = file_get_contents(__DIR__ . '/views/emails/reset_text.tpl');
     preg_match_all('/%([\\w|\\d]*)%/', $template, $matches);
     foreach ($matches[1] as $match) {
         $replacement = !empty($user[$match]) ? $user[$match] : '';
         $template = str_replace('%' . $match . '%', $replacement, $template);
     }
     $this->Userman->sendEmail($user['id'], $this->brand . " password reset", $template);
 }
Example #16
0
 /**
  * Retrieve a remote file
  * Stores file into memory
  * @param  string $path The full path to said file
  * @return string       binary representation of file
  */
 private function getRemoteFile($path)
 {
     $modulef =& \module_functions::create();
     $contents = null;
     $mirrors = $modulef->generate_remote_urls($path, true);
     $params = $mirrors['options'];
     $params['sv'] = 2;
     foreach ($mirrors['mirrors'] as $url) {
         set_time_limit($this->maxTimeLimit);
         try {
             $pest = \FreePBX::Curl()->pest($url);
             $contents = $pest->post($url . $path, $params);
             if (isset($pest->last_headers['x-regenerate-id'])) {
                 $modulef->_regenerate_unique_id();
             }
             if (!empty($contents)) {
                 return $contents;
             }
         } catch (\Exception $e) {
             freepbx_log(FPBX_LOG_ERROR, sprintf(_('Failed to get remote file, error was:'), (string) $e->getMessage()));
         }
     }
 }
Example #17
0
 /**
  * Actually run GPG
  * @param string Params to pass to gpg
  * @param fd File Descriptor to feed to stdin of gpg
  * @return array returns assoc array consisting of (array)status, (string)stdout, (string)stderr and (int)exitcode
  */
 public function runGPG($params, $stdin = null)
 {
     $fds = array(array("file", "/dev/null", "r"), array("pipe", "w"), array("pipe", "w"), array("pipe", "w"));
     // If we need to send stuff to stdin, then do it!
     if ($stdin) {
         $fds[0] = $stdin;
     }
     $webuser = FreePBX::Freepbx_conf()->get('AMPASTERISKWEBUSER');
     $home = $this->getGpgLocation();
     // We need to ensure that our environment variables are sane.
     // Luckily, we know just the right things to say...
     if (!isset($this->gpgenv)) {
         $this->gpgenv['PATH'] = "/bin:/usr/bin";
         $this->gpgenv['USER'] = $webuser;
         $this->gpgenv['HOME'] = "/tmp";
         $this->gpgenv['SHELL'] = "/bin/bash";
     }
     $homedir = "--homedir {$home}";
     $cmd = $this->gpg . " {$homedir} " . $this->gpgopts . " --status-fd 3 {$params}";
     $proc = proc_open($cmd, $fds, $pipes, "/tmp", $this->gpgenv);
     if (!is_resource($proc)) {
         // Unable to start!
         freepbx_log(FPBX_LOG_FATAL, "Tried to run command and failed: " . $cmd);
         throw new \Exception(sprintf(_("Unable to start GPG, the command was: [%s]"), $cmd));
     }
     // Wait $timeout seconds for it to finish.
     $tmp = null;
     $r = array($pipes[3]);
     if (!stream_select($r, $tmp, $tmp, $this->timeout)) {
         freepbx_log(FPBX_LOG_FATAL, "Tried to run command and failed: " . $cmd);
         throw new \RuntimeException(sprintf(_("GPG took too long to run the command: [%s]"), $cmd));
     }
     // We grab stdout and stderr first, as the status fd won't
     // have completed and closed until those FDs are emptied.
     $retarr['stdout'] = stream_get_contents($pipes[1]);
     $retarr['stderr'] = stream_get_contents($pipes[2]);
     $status = explode("\n", stream_get_contents($pipes[3]));
     array_pop($status);
     // Remove trailing blank line
     $retarr['status'] = $status;
     $exitcode = proc_close($proc);
     $retarr['exitcode'] = $exitcode;
     return $retarr;
 }
Example #18
0
 function generate_queues_additional($ast_version)
 {
     global $db;
     global $amp_conf;
     $additional = "";
     $output = "";
     // Asterisk 1.4 does not like blank assignments so just don't put them there
     //
     $ver12 = version_compare($ast_version, '1.4', 'lt');
     $ver16 = version_compare($ast_version, '1.6', 'ge');
     $ast_ge_14_25 = version_compare($ast_version, '1.4.25', 'ge');
     $ast_ge_18 = version_compare($ast_version, '1.8', 'ge');
     $ast_ge_120 = version_compare($ast_version, '12', 'ge');
     // legacy but in case someone was using this we will leave it
     //TODO: abstract getters/setters from business logic
     $sql = "SELECT keyword,data FROM queues_details WHERE id='-1' AND keyword <> 'account'";
     $results = $db->getAll($sql, DB_FETCHMODE_ASSOC);
     if ($db->IsError($results)) {
         die($results->getMessage());
     }
     foreach ($results as $result) {
         if (!$ver12 && trim($result['data']) == '') {
             continue;
         }
         $additional .= $result['keyword'] . "=" . $result['data'] . "\n";
     }
     if ($ast_ge_14_25) {
         $devices = array();
         $device_results = core_devices_list('all', 'full', true);
         if (is_array($device_results)) {
             foreach ($device_results as $device) {
                 if (!isset($devices[$device['user']]) && $device['devicetype'] == 'fixed') {
                     $devices[$device['user']] = $device['dial'];
                 }
             }
             unset($device_results);
         }
     }
     if ($amp_conf['USEQUEUESTATE'] || $ast_ge_14_25) {
         $users = array();
         $user_results = core_users_list();
         if (is_array($user_results)) {
             foreach ($user_results as $user) {
                 $users[$user[0]] = $user[1];
             }
             unset($user_results);
         }
     }
     $results = queues_list(true);
     foreach ($results as $result) {
         $output .= "[" . $result[0] . "]\n";
         // passing 2nd param 'true' tells queues_get to send back only queue_conf required params
         // and nothing else
         //
         $results2 = queues_get($result[0], true);
         if (empty($results2['context'])) {
             $results2['context'] = "";
         }
         // memebers is an array of members so we set it asside and remove it
         // and then generate each later
         //
         $members = $results2['member'];
         unset($results2['member']);
         // Queues cannot control their own recordings, it must now be
         // done through sub-record-check
         unset($results2['monitor-format']);
         unset($results2['recording']);
         //Unset Old commands Resolves FREEPBX-8610.
         unset($results2['monitor-join']);
         unset($results2['answered_elsewhere']);
         unset($results2['skip_joinannounce']);
         //These items still exist for backwards compatibility but are useless in 12+
         if ($ast_ge_120) {
             unset($results2['eventwhencalled']);
             unset($results2['eventmemberstatus']);
         }
         foreach ($results2 as $keyword => $data) {
             if (trim($data) == '' && $keyword != "context" || substr($keyword, 0, 4) == "cron") {
                 // Skip anything that's empty or not required
                 continue;
             }
             // Some old commands have been removed. Make sure we
             // don't add them.
             switch ($keyword) {
                 case 'monitor-join':
                 case 'answered_elsewhere':
                 case 'skip_joinannounce':
                     continue;
                     break;
                 case 'music':
                     $keyword = 'musicclass';
                     break;
             }
             if ($keyword == "retry" && $data == "none") {
                 $data = 0;
             }
             $output .= $keyword . "=" . $data . "\n";
         }
         // Now pull out all the memebers, one line for each
         //
         if ($ast_ge_18 || $amp_conf['USEQUEUESTATE']) {
             foreach ($members as $member) {
                 preg_match("/^Local\\/([\\d]+)\\@*/", $member, $matches);
                 if (isset($matches[1]) && isset($users[$matches[1]])) {
                     $name = sprintf('"%s"', $users[$matches[1]]);
                     //str_replace(',','\,',$name);
                     $qnostate = queues_get_qnostate($matches[1]);
                     if ($qnostate == 'ignorestate') {
                         freepbx_log(FPBX_LOG_NOTICE, "Ignoring State information for Queue Member: " . $matches[1]);
                         $output .= "member={$member},{$name}\n";
                     } else {
                         $output .= "member={$member},{$name},hint:" . $matches[1] . "@ext-local\n";
                     }
                 } else {
                     $output .= "member=" . $member . "\n";
                 }
             }
         } else {
             if ($ast_ge_14_25) {
                 foreach ($members as $member) {
                     preg_match("/^Local\\/([\\d]+)\\@*/", $member, $matches);
                     if (isset($matches[1]) && isset($devices[$matches[1]])) {
                         $name = sprintf('"%s"', $users[$matches[1]]);
                         //str_replace(',','\,',$name);
                         $qnostate = queues_get_qnostate($matches[1]);
                         if ($qnostate == 'ignorestate') {
                             freepbx_log(FPBX_LOG_NOTICE, "Ignoring State information for Queue Member: " . $matches[1]);
                             $output .= "member={$member},{$name}\n";
                         } else {
                             $output .= "member={$member},{$name}," . $devices[$matches[1]] . "\n";
                         }
                     } else {
                         $output .= "member=" . $member . "\n";
                     }
                 }
             } else {
                 foreach ($members as $member) {
                     $output .= "member=" . $member . "\n";
                 }
             }
         }
         if (isset($this->_queues_additional[$result[0]])) {
             foreach ($this->_queues_additional[$result[0]] as $qsetting) {
                 $output .= $qsetting['key'] . "=" . $qsetting['value'] . "\n";
             }
         }
         $output .= $additional . "\n";
     }
     // Before returning the results, do an integrity check to see
     // if there are any truncated compound recrodings and if so
     // crate a noticication.
     //
     $nt = notifications::create($db);
     $compound_recordings = queues_check_compoundrecordings();
     if (empty($compound_recordings)) {
         $nt->delete('queues', 'COMPOUNDREC');
     } else {
         $str = _('Warning, there are compound recordings configured in ' . 'one or more Queue configurations. Queues can not play these ' . 'so they have been truncated to the first sound file. You ' . 'should correct this problem.<br />Details:<br /><br />');
         foreach ($compound_recordings as $item) {
             $str .= sprintf(_("Queue - %s (%s): %s<br />"), $item['extension'], $item['descr'], $item['error']);
         }
         $nt->add_error('queues', 'COMPOUNDREC', _("Compound Recordings in Queues Detected"), $str);
     }
     return $output;
 }
Example #19
0
/**
 * Update AMI credentials in manager.conf
 *
 * @author Philippe Lindheimer
 * @pram mixed $user false means don't change
 * @pram mixed $pass password false means don't change
 * @pram mixed $writetimeout false means don't change
 * @returns boolean
 *
 * allows FreePBX to update the manager credentials primarily used by Advanced Settings and Backup and Restore.
 */
function fpbx_ami_update($user = false, $pass = false, $writetimeout = false)
{
    global $amp_conf, $astman, $db, $bootstrap_settings;
    $conf_file = $amp_conf['ASTETCDIR'] . '/manager.conf';
    $ret = $ret2 = $ret3 = 0;
    $output = array();
    if (strpos($amp_conf['ASTETCDIR'], "..") === false && !file_exists($conf_file)) {
        return;
    }
    if ($user !== false && $user != '') {
        $sed_arg = escapeshellarg('s/\\s*\\[general\\].*$/TEMPCONTEXT/;s/\\[.*\\]/\\[' . $amp_conf['AMPMGRUSER'] . '\\]/;s/^TEMPCONTEXT$/\\[general\\]/');
        exec("sed -i.bak {$sed_arg} {$conf_file}", $output, $ret);
        if ($ret) {
            freepbx_log(FPBX_LOG_ERROR, sprintf(_("Failed changing AMI user to [%s], internal failure details follow:"), $amp_conf['AMPMGRUSER']));
            foreach ($output as $line) {
                freepbx_log(FPBX_LOG_ERROR, sprintf(_("AMI failure details:"), $line));
            }
        }
    }
    if ($pass !== false && $pass != '') {
        unset($output);
        $sed_arg = escapeshellarg('s/secret\\s*=.*$/secret = ' . $amp_conf['AMPMGRPASS'] . '/');
        exec("sed -i.bak {$sed_arg} {$conf_file}", $output2, $ret2);
        if ($ret2) {
            freepbx_log(FPBX_LOG_ERROR, sprintf(_("Failed changing AMI password to [%s], internal failure details follow:"), $amp_conf['AMPMGRPASS']));
            foreach ($output as $line) {
                freepbx_log(FPBX_LOG_ERROR, sprintf(_("AMI failure details:"), $line));
            }
        }
        // We've changed the password, let's update the notification
        //
        $nt = notifications::create($db);
        $freepbx_conf =& freepbx_conf::create();
        if ($amp_conf['AMPMGRPASS'] == $freepbx_conf->get_conf_default_setting('AMPMGRPASS')) {
            if (!$nt->exists('core', 'AMPMGRPASS')) {
                $nt->add_warning('core', 'AMPMGRPASS', _("Default Asterisk Manager Password Used"), _("You are using the default Asterisk Manager password that is widely known, you should set a secure password"));
            }
        } else {
            $nt->delete('core', 'AMPMGRPASS');
        }
    }
    //attempt to set writetimeout
    unset($output);
    if ($writetimeout) {
        $sed_arg = escapeshellarg('s/writetimeout\\s*=.*$/writetimeout = ' . $amp_conf['ASTMGRWRITETIMEOUT'] . '/');
        exec("sed -i.bak {$sed_arg} {$conf_file}", $output3, $ret3);
        if ($ret3) {
            freepbx_log(FPBX_LOG_ERROR, sprintf(_("Failed changing AMI writetimout to [%s], internal failure details follow:"), $amp_conf['ASTMGRWRITETIMEOUT']));
            foreach ($output as $line) {
                freepbx_log(FPBX_LOG_ERROR, sprintf(_("AMI failure details:"), $line));
            }
        }
    }
    if ($ret || $ret2 || $ret3) {
        dbug("aborting early because previous errors");
        return false;
    }
    if (is_object($astman) && method_exists($astman, "connected") && $astman->connected()) {
        $ast_ret = $astman->Command('module reload manager');
    } else {
        unset($output);
        dbug("no astman connection so trying to force through linux command line");
        exec(fpbx_which('asterisk') . " -rx 'module reload manager'", $output, $ret2);
        if ($ret2) {
            freepbx_log(FPBX_LOG_ERROR, _("Failed to reload AMI, manual reload will be necessary, try: [asterisk -rx 'module reload manager']"));
        }
    }
    if (is_object($astman) && method_exists($astman, "connected") && $astman->connected()) {
        $astman->disconnect();
    }
    if (!is_object($astman) || !method_exists($astman, "connected")) {
        //astman isn't initiated so escape
        return true;
    }
    if (!($res = $astman->connect($amp_conf["ASTMANAGERHOST"] . ":" . $amp_conf["ASTMANAGERPORT"], $amp_conf["AMPMGRUSER"], $amp_conf["AMPMGRPASS"], $bootstrap_settings['astman_events']))) {
        // couldn't connect at all
        freepbx_log(FPBX_LOG_CRITICAL, "Connection attmempt to AMI failed");
    } else {
        $bmo = FreePBX::create();
        $bmo->astman = $astman;
    }
    return true;
}
Example #20
0
/**
 * Update AMI credentials in manager.conf
 *
 * @author Philippe Lindheimer
 * @pram mixed $user false means don't change
 * @pram mixed $pass password false means don't change
 * @pram mixed $writetimeout false means don't change
 * @returns boolean
 *
 * allows FreePBX to update the manager credentials primarily used by Advanced Settings and Backup and Restore.
 */
function fpbx_ami_update($user = false, $pass = false, $writetimeout = false)
{
    global $amp_conf, $astman;
    $conf_file = $amp_conf['ASTETCDIR'] . '/manager.conf';
    $ret = $ret2 = 0;
    $output = array();
    if ($user !== false && $user != '') {
        exec('sed -i.bak "s/\\s*\\[general\\].*$/TEMPCONTEXT/;s/\\[.*\\]/\\[' . $amp_conf['AMPMGRUSER'] . '\\]/;s/^TEMPCONTEXT$/\\[general\\]/" ' . $conf_file, $output, $ret);
        if ($ret) {
            dbug($output);
            dbug($ret);
            freepbx_log(FPBX_LOG_ERROR, sprintf(_("Failed changing AMI user to [%s], internal failure details follow:"), $amp_conf['AMPMGRUSER']));
            foreach ($output as $line) {
                freepbx_log(FPBX_LOG_ERROR, sprintf(_("AMI failure details:"), $line));
            }
        }
    }
    if ($pass !== false && $pass != '') {
        unset($output);
        exec('sed -i.bak "s/secret\\s*=.*$/secret = ' . $amp_conf['AMPMGRPASS'] . '/" ' . $conf_file, $output, $ret2);
        if ($ret2) {
            dbug($output);
            dbug($ret2);
            freepbx_log(FPBX_LOG_ERROR, sprintf(_("Failed changing AMI password to [%s], internal failure details follow:"), $amp_conf['AMPMGRPASS']));
            foreach ($output as $line) {
                freepbx_log(FPBX_LOG_ERROR, sprintf(_("AMI failure details:"), $line));
            }
        }
        // We've changed the password, let's update the notification
        //
        $nt = notifications::create($db);
        $freepbx_conf =& freepbx_conf::create();
        if ($amp_conf['AMPMGRPASS'] == $freepbx_conf->get_conf_default_setting('AMPMGRPASS')) {
            if (!$nt->exists('core', 'AMPMGRPASS')) {
                $nt->add_warning('core', 'AMPMGRPASS', _("Default Asterisk Manager Password Used"), _("You are using the default Asterisk Manager password that is widely known, you should set a secure password"));
            }
        } else {
            $nt->delete('core', 'AMPMGRPASS');
        }
    }
    //attempt to set writetimeout
    unset($output);
    if ($writetimeout) {
        exec('sed -i.bak "s/writetimeout\\s*=.*$/writetimeout = ' . $amp_conf['ASTMGRWRITETIMEOUT'] . '/" ' . $conf_file, $output, $ret3);
        if ($ret3) {
            dbug($output);
            dbug($ret3);
            freepbx_log(FPBX_LOG_ERROR, sprintf(_("Failed changing AMI writetimout to [%s], internal failure details follow:"), $amp_conf['ASTMGRWRITETIMEOUT']));
            foreach ($output as $line) {
                freepbx_log(FPBX_LOG_ERROR, sprintf(_("AMI failure details:"), $line));
            }
        }
    }
    if ($ret || $ret2 || $ret3) {
        dbug("aborting early because previous errors");
        return false;
    }
    if (!empty($astman)) {
        $ast_ret = $astman->Command('module reload manager');
    } else {
        unset($output);
        dbug("no astman connection so trying to force through linux command line");
        exec(fpbx_which('asterisk') . " -rx 'module reload manager'", $output, $ret2);
        if ($ret2) {
            dbug($output);
            dbug($ret2);
            freepbx_log(FPBX_LOG_ERROR, _("Failed to reload AMI, manual reload will be necessary, try: [asterisk -rx 'module reload manager']"));
        }
    }
    return true;
}
Example #21
0
 $licFileExists = glob('/etc/schmooze/license-*.zl');
 $complete_zend = !function_exists('zend_loader_install_license') || empty($licFileExists);
 try {
     if ($needs_zend && class_exists('\\Schmooze\\Zend') && file_exists($file) && \Schmooze\Zend::fileIsLicensed($file) && $complete_zend) {
         $file_exists = false;
         $zendedbroken[] = $key;
     }
     //emergency mode
     if ($needs_zend && $file_exists && !empty($bootstrap_settings['fix_zend'])) {
         $file_exists = false;
         $zended[$key] = $file;
     }
     //$file_exists = false;
 } catch (\Exception $e) {
     //Some fatal error happened
     freepbx_log(FPBX_LOG_WARNING, $e->getMessage());
     $file_exists = false;
     $zendedbroken[] = $key;
 }
 //actualy load module
 if ((!$restrict_mods_local || $is_selected) && $file_exists) {
     bootstrap_include_hooks('pre_module_load', $key);
     require_once $file;
     bootstrap_include_hooks('post_module_load', $key);
 }
 //create an array of module sections to display
 //stored as [items][$type][$category][$name] = $displayvalue
 if (isset($module['items']) && is_array($module['items'])) {
     //if asterisk isnt running, mark moduels that depend on
     //asterisk as disbaled
     foreach ($module['items'] as $itemKey => $item) {
Example #22
0
                                if (is_numeric($value) && $value > -10 && $value < 10) {
                                    $fpbx_menu[$menuitem][$key] = $value;
                                }
                                break;
                            case 'remove':
                                // parse_ini_file sets all forms of yes/true to 1 and no/false to nothing
                                if ($value == '1') {
                                    unset($fpbx_menu[$menuitem]);
                                }
                                break;
                        }
                    }
                }
            }
        } else {
            freepbx_log('FPBX_LOG_ERROR', _("Syntax error in your freepbx_menu.conf file"));
        }
    }
}
//For Localization pickup
if (false) {
    _("Admin");
    _("Applications");
    _("Connectivity");
    _("Reports");
    _("Settings");
    _("User Panel");
    _("Other");
}
if (isset($fpbx_menu) && is_array($fpbx_menu)) {
    // && freepbx_menu.conf not defined
Example #23
0
 function add_items()
 {
     foreach ($this->b['items'] as $i) {
         switch ($i['type']) {
             case 'file':
                 // substitute vars
                 $i['path'] = backup__($i['path']);
                 // Does the file exist?
                 if (!file_exists($i['path'])) {
                     // It could be a wildcard?
                     $glob = glob($i['path']);
                     if (!$glob) {
                         break;
                     }
                     // Ahha! Wildcards! That's OK then.
                     $dest = $dest = $this->b['_tmpdir'] . dirname($i['path']);
                     if (!is_dir($dest)) {
                         mkdir($dest, 0755, true);
                     }
                 } else {
                     $dest = $this->b['_tmpdir'] . $i['path'];
                     if (!is_dir(dirname($dest))) {
                         mkdir(dirname($dest), 0755, true);
                     }
                 }
                 //copy file
                 $cmd = fpbx_which('cp') . " " . $i['path'] . " {$dest}";
                 exec($cmd);
                 unset($cmd);
                 break;
             case 'dir':
                 //subsitute variable if nesesary
                 $i['path'] = backup__($i['path']);
                 // Match wildcards.
                 $dirs = glob($i['path'], \GLOB_ONLYDIR);
                 if (!isset($dirs[0])) {
                     backup_log("Skipping requested directory '" . $i['path'] . "' as it does not exist.");
                     break;
                 }
                 foreach ($dirs as $path) {
                     // Create destination directory structure
                     $dest = $this->b['_tmpdir'] . $path;
                     if (!is_dir($dest)) {
                         mkdir($dest, 0755, true);
                     }
                     // Where are we copying from? Note we explicitly use realpath here,
                     // as there could be any number of symlinks leading to the CONTENTS.
                     // But we want to just back the contents up, and pretend those links
                     // don't exist.
                     $src = realpath($path);
                     // Build our list of extra excludes (if any).
                     // Standard exclusions:
                     //   1 - node_modules - compiled for the local machine,
                     //       and are easily regenerated.
                     $excludes = " --exclude='node_modules' ";
                     //   2 - *tgz and *gpg - previously downloaded files, and can be redownloaded.
                     //       Note this ALSO excludes backups so we don't put a backup inside a backup.
                     $excludes .= "--exclude='*tgz' --exclude='*gpg' ";
                     if ($i['exclude']) {
                         if (!is_array($i['exclude'])) {
                             $xArr = explode("\n", $i['exclude']);
                         } else {
                             $xArr = $i['exclude'];
                         }
                         foreach ($xArr as $x) {
                             // Replace any __vars__ if given.
                             $x = backup__($x);
                             // Does it start with a slash? Treat that as
                             // a full path with a filter, instead of just
                             // an exclude.
                             if ($x[0] === "/") {
                                 $excludes .= " --filter='-/ {$x}'";
                             } else {
                                 // It's a normal exclude
                                 $excludes .= " --exclude='{$x}'";
                             }
                         }
                     }
                     // Use rsync to mirror $src to $dest.
                     // Note we ensure we add the trailing slash to tell rsync to copy the
                     // contents, not the targets (if the target is a link, for exmaple)
                     // Note we do NOT use 'a', as we don't want special files
                     // backed up (the -D or --special option is included in 'a')
                     // backup_log("Backing up $src");
                     $cmd = fpbx_which('rsync') . "{$excludes} -rlptgov {$src}/ {$dest}/";
                     exec($cmd);
                     unset($cmd);
                 }
                 break;
             case 'mysql':
                 //build command
                 $s = str_replace('server-', '', $i['path']);
                 $sql_file = $this->b['_tmpdir'] . '/' . 'mysql-' . $s . '.sql';
                 $cmd[] = fpbx_which('mysqldump');
                 $cmd[] = '--host=' . backup__($this->s[$s]['host']);
                 $cmd[] = '--port=' . backup__($this->s[$s]['port']);
                 $cmd[] = '--user='******'user']);
                 $cmd[] = '--password='******'password']);
                 $cmd[] = backup__($this->s[$s]['dbname']);
                 if ($i['exclude']) {
                     foreach ($i['exclude'] as $x) {
                         $cmd[] = '--ignore-table=' . backup__($this->s[$s]['dbname']) . '.' . backup__($x);
                     }
                 }
                 $cmd[] = ' --opt --skip-comments --skip-extended-insert --lock-tables=false --skip-add-locks --compatible=no_table_options ';
                 // Need to grep out leading /* comments and SET commands as they create problems
                 // restoring using the PEAR $db class
                 //
                 $cmd[] = ' | ';
                 $cmd[] = fpbx_which('grep');
                 $cmd[] = "-v '^\\/\\*\\|^SET'";
                 $cmd[] = ' > ' . $sql_file;
                 exec(implode(' ', $cmd), $file, $status);
                 unset($cmd, $file);
                 // remove file and log error information if it failed.
                 //
                 if ($status !== 0) {
                     unlink($sql_file);
                     $error_string = sprintf(_("Backup failed dumping SQL database [%s] to file [%s], " . "you have a corrupted backup from server [%s]."), backup__($this->s[$s]['dbname']), $sql_file, backup__($this->s[$s]['host']));
                     backup_log($error_string);
                     freepbx_log(FPBX_LOG_FATAL, $error_string);
                 }
                 break;
             case 'astdb':
                 $hard_exclude = array('RG', 'BLKVM', 'FM', 'dundi');
                 $exclude = array_merge($i['exclude'], $hard_exclude);
                 $astdb = astdb_get($exclude);
                 file_put_contents($this->b['_tmpdir'] . '/astdb', serialize($astdb));
                 break;
         }
     }
 }
Example #24
0
 function parse_amportal_conf($conf)
 {
     global $db;
     if (!is_object($db)) {
         $restrict_mods = true;
         $bootstrap_settings['skip_astman'] = true;
         if (!@(include_once getenv('FREEPBX_CONF') ? getenv('FREEPBX_CONF') : '/etc/freepbx.conf')) {
             include_once '/etc/asterisk/freepbx.conf';
         }
     }
     $freepbx_conf =& freepbx_conf::create();
     freepbx_log(FPBX_LOG_ERROR, 'parse_amportal_conf() is deprecated. Use of bootstrap.php creates $amp_conf');
     return $freepbx_conf->parse_amportal_conf($conf);
 }
 function url_get_contents($url, $request, $verb = 'get', $params = array())
 {
     $params['sv'] = 2;
     global $amp_conf;
     $verb = strtolower($verb);
     $contents = null;
     if (!$amp_conf['MODULEADMINWGET']) {
         $pest = new Pest($url);
         try {
             $contents = $pest->{$verb}($url . $request, $params);
             if (isset($pest->last_headers['x-regenerate-id'])) {
                 $this->_regenerate_unique_id();
             }
             return $contents;
         } catch (Exception $e) {
             freepbx_log(FPBX_LOG_ERROR, sprintf(_('Failed to get remote file, error was:'), (string) $e->getMessage()));
         }
     }
     $fn = $url . $request;
     if (empty($contents)) {
         $fn2 = str_replace('&', '\\&', $fn);
         $p = !empty($params) ? "--post-data '" . http_build_query($params) . "'" : "";
         exec("wget --tries=1 --timeout=30 {$p} -O - {$fn2} 2>> /dev/null", $data_arr, $retcode);
         if ($retcode) {
             // if server isn't available for some reason should return non-zero
             // so we return and we don't set the flag below
             freepbx_log(FPBX_LOG_ERROR, sprintf(_('Failed to get remote file, mirror site may be down: %s'), $fn));
             // We are here if contents were blank. It's possible that whatever we were getting were suppose to be blank
             // so we only auto set the WGET var if we received something so as to not false trigger. If there are issues
             // with content filters that this is designed to get around, we will eventually get a non-empty file which
             // will trigger this for now and the future.
             return null;
         } elseif (!empty($data_arr) && !$amp_conf['MODULEADMINWGET']) {
             $freepbx_conf =& freepbx_conf::create();
             $freepbx_conf->set_conf_values(array('MODULEADMINWGET' => true), true);
             $nt =& notifications::create($db);
             $text = sprintf(_("Forced %s to true"), 'MODULEADMINWGET');
             $extext = sprintf(_("The system detected a problem trying to access external server data and changed internal setting %s (Use wget For Module Admin) to true, see the tooltip in Advanced Settings for more details."), 'MODULEADMINWGET');
             $nt->add_warning('freepbx', 'MODULEADMINWGET', $text, $extext, '', false, true);
         }
         $headers = get_headers_assoc($fn2);
         if (isset($headers['x-regenerate-id'])) {
             $this->_regenerate_unique_id();
         }
         $contents = implode("\n", $data_arr);
         return $contents;
     }
 }
        //special cron manager detections
        if ($keyword == 'UIDEFAULTLANG') {
            $_COOKIE['lang'] = trim($var['value']);
        }
        if ($keyword == 'CRONMAN_UPDATES_CHECK') {
            $cm =& cronmanager::create($db);
            if ($var['value']) {
                $cm->enable_updates();
            } else {
                $cm->disable_updates();
            }
        }
        $freepbx_conf->set_conf_values(array($keyword => trim($var['value'])), true, $amp_conf['AS_OVERRIDE_READONLY']);
        $status = $freepbx_conf->get_last_update_status();
        if ($status[$keyword]['saved']) {
            freepbx_log(FPBX_LOG_INFO, sprintf(_("Advanced Settings changed freepbx_conf setting: [{$keyword}] => [%s]"), $var['value']));
            needreload();
        }
        echo json_encode($status[$keyword]);
        exit;
    }
    exit;
}
echo '<script type="text/javascript">';
echo 'userdevicewarn = "' . _("Device and User mode is unsupported by the development team. Are you sure you want to use this mode?") . '";';
echo 'amportalconf_error = "' . _("You must run 'amportal restart' from the Linux command line before you can save setting here.") . '";';
echo 'msgUnsavedChanges = "' . _("You have un-saved changes, press OK to disregard changes and reload page or Cancel to abort.") . '";';
echo 'msgChangesRefresh = "' . _("Your Display settings have been changed, click on 'Refresh Page' to view the affects of your changes once you have saved other outstanding changes that are still un-confirmed.") . '";';
echo '</script>';
echo '<div id="main_page">';
echo "<h2>" . _("FreePBX Advanced Settings") . "</h2>";