Ejemplo n.º 1
0
 /**
  * action_save
  * @return save widget (make active)
  */
 public function action_save()
 {
     // save only changed values
     if ($this->request->post()) {
         //deleting the fragment cache...a bit ugly but works.
         View::delete_fragment('sidebar_front');
         View::delete_fragment('footer_front');
         //get place holder name
         $placeholder = core::post('placeholder');
         //get widget class
         $widget = core::post('widget_class');
         //widget name
         $widget_name = core::post('widget_name');
         //$data = array();
         //extract all the data and prepare array
         foreach ($this->request->post() as $name => $value) {
             if ($name != 'placeholder' and $name != 'widget_class' and $name != 'widget_name') {
                 $data[$name] = $value;
             }
         }
         $old_placeholder = NULL;
         $widget = new $widget();
         //the widget exists, we load it since we need the previous placeholder
         if ($widget_name != NULL) {
             $widget->load($widget_name);
             $old_placeholder = $widget->placeholder;
         }
         $widget->placeholder = $placeholder;
         $widget->data = $data;
         try {
             $widget->save($old_placeholder);
             //clean cache config
             $c = new ConfigDB();
             $c->reload_config();
             if ($widget_name != NULL) {
                 Alert::set(Alert::SUCCESS, sprintf(__('Widget %s saved in %s'), $widget_name, $placeholder));
             } else {
                 Alert::set(Alert::SUCCESS, sprintf(__('Widget created in %s'), $placeholder));
             }
         } catch (Exception $e) {
             //throw 500
             throw HTTP_Exception::factory(500, $e->getMessage());
         }
         $this->redirect(Route::url('oc-panel', array('controller' => 'widget', 'action' => 'index')));
     }
 }
Ejemplo n.º 2
0
 /**
  * Comprobar si el usuario tiene actualizada la clave maestra actual.
  *
  * @param string $login opcional con el login del usuario
  * @return bool
  */
 public static function checkUserUpdateMPass($login = null)
 {
     $userId = !is_null($login) ? UserUtil::getUserIdByLogin($login) : Session::getUserId();
     if ($userId === 0) {
         return false;
     }
     $configMPassTime = ConfigDB::getValue('lastupdatempass');
     if ($configMPassTime === false) {
         return false;
     }
     $query = 'SELECT user_lastUpdateMPass FROM usrData WHERE user_id = :id LIMIT 1';
     $data['id'] = $userId;
     $queryRes = DB::getResults($query, __FUNCTION__, $data);
     $ret = $queryRes !== false && $queryRes->user_lastUpdateMPass > $configMPassTime;
     return $ret;
 }
Ejemplo n.º 3
0
 /**
  * 
  * Loads the configs from database to the cache
  * @return boolean
  */
 private function load_config()
 {
     //we don't read the config cache in development
     self::$data = Kohana::$environment === Kohana::DEVELOPMENT ? NULL : Core::cache('config_db');
     //only load if empty
     if (self::$data === NULL) {
         // Load all the config data to cache
         $query = DB::select('group_name')->select('config_key')->select('config_value')->from($this->_table_name)->order_by('group_name', 'asc')->order_by('config_key', 'asc')->execute();
         $configs = $query->as_array();
         foreach ($configs as $config) {
             self::$data[$config['group_name']][$config['config_key']] = $config['config_value'];
         }
         //caching all the results
         Core::cache('config_db', self::$data, 60 * 60 * 24);
         return TRUE;
     } else {
         //was already cached
         return FALSE;
     }
 }
Ejemplo n.º 4
0
 /**
  * Actualizar la clave maestra del usuario en la BBDD.
  *
  * @param string $masterPwd con la clave maestra
  * @return bool
  */
 public function updateUserMPass($masterPwd)
 {
     $configHashMPass = ConfigDB::getValue('masterPwd');
     if ($configHashMPass === false) {
         return false;
     }
     if (is_null($configHashMPass)) {
         $configHashMPass = Crypt::mkHashPassword($masterPwd);
         ConfigDB::setValue('masterPwd', $configHashMPass);
     }
     if (Crypt::checkHashPass($masterPwd, $configHashMPass, true)) {
         $cryptMPass = Crypt::mkCustomMPassEncrypt(self::getCypherPass(), $masterPwd);
         if (!$cryptMPass) {
             return false;
         }
     } else {
         return false;
     }
     $query = 'UPDATE usrData SET ' . 'user_mPass = :mPass,' . 'user_mIV = :mIV,' . 'user_lastUpdateMPass = UNIX_TIMESTAMP() ' . 'WHERE user_id = :id LIMIT 1';
     $data['mPass'] = $cryptMPass[0];
     $data['mIV'] = $cryptMPass[1];
     $data['id'] = $this->_userId;
     return DB::getQuery($query, __FUNCTION__, $data);
 }
Ejemplo n.º 5
0
 /**
  * Comprobar el hash de una clave.
  *
  * @param string $pwd          con la clave a comprobar
  * @param string $checkedHash con el hash a comprobar
  * @param bool   $isMPass      si es la clave maestra
  * @return bool
  */
 public static function checkHashPass($pwd, $checkedHash, $isMPass = false)
 {
     // Obtenemos el salt de la clave
     $salt = substr($checkedHash, 0, 72);
     // Obtenemos el hash SHA256
     $validHash = substr($checkedHash, 72);
     // Re-hash de la clave a comprobar
     $testHash = crypt($pwd, $salt);
     // Comprobar si el hash está en formato anterior a 12002
     if ($isMPass && strlen($checkedHash) === 128) {
         $check = hash("sha256", substr($checkedHash, 0, 64) . $pwd) == substr($checkedHash, 64, 64);
         if ($check) {
             ConfigDB::setValue('masterPwd', self::mkHashPassword($pwd));
             Log::writeNewLog(_('Aviso'), _('Se ha regenerado el HASH de clave maestra. No es necesaria ninguna acción.'));
         }
         return $check;
     }
     // Si los hashes son idénticos, la clave es válida
     return $testHash == $validHash;
 }
Ejemplo n.º 6
0
 closeMpdSocket($mpd);
 $currentsong = _parseMpdCurrentSong($resp);
 // TC (Tim Curtis) 2015-07-31: updated logic
 // Logic modeled after player_lib.js getPlaylist();
 // RADIO STATION
 if (isset($currentsong['Name']) || substr($currentsong['file'], 0, 4) == "http" && !isset($currentsong['Artist'])) {
     if (!isset($currentsong['Title'])) {
         $title = "Streaming source";
     } else {
         $title = $currentsong['Title'];
         $searchStr = str_replace('-', ' ', $title);
         $searchStr = str_replace('&', ' ', $searchStr);
         $searchStr = preg_replace('!\\s+!', '+', $searchStr);
     }
     $artist = "<i class=\"icon-microphone\"></i>";
     $result = ConfigDB::read('cfg_radio', $currentsong['file']);
     if (0 == count($result)) {
         // station not in db
         $album = isset($currentsong['Name']) ? $currentsong['Name'] : "Unknown station";
     } else {
         $album = $result[0]['name'];
     }
     // SONG FILE OR UPNP SONG URL
 } else {
     $title = isset($currentsong['Title']) ? $currentsong['Title'] : pathinfo($currentsong['file'], PATHINFO_FILENAME);
     $artist = isset($currentsong['Artist']) ? $currentsong['Artist'] : "Unknown artist";
     $album = isset($currentsong['Album']) ? $currentsong['Album'] : "Unknown album";
     // search string
     if ($artist == "Unknown artist" && $album == "Unknown album") {
         $searchStr = $title;
     } else {
Ejemplo n.º 7
0
 /**
  * everytime we save the config we relad the cache
  * @return boolean 
  */
 public function reload_config()
 {
     $c = new ConfigDB();
     return $c->reload_config();
 }
Ejemplo n.º 8
0
}
// Handle manual config
if (isset($_POST['mpdconf']) && !empty($_POST['mpdconf'])) {
    // tell worker to write new MPD config
    if ($workerSuccess = workerPushTask('mpdcfgman', $_POST['mpdconf'])) {
        uiSetNotification('MPD config modified', 'Restarting MPD server...');
    }
}
// could not start worker job
if (false === $workerSuccess) {
    uiSetNotification('Job failed', 'Background worker is busy');
}
Session::close();
// Wait for worker
waitWorker();
$mpdconf = ConfigDB::read('', 'mpdconf');
// Prepare array
$_mpd = array('port' => '', 'gapless_mp3_playback' => '', 'auto_update' => '', 'samplerate_converter' => '', 'auto_update_depth' => '', 'zeroconf_enabled' => '', 'zeroconf_name' => '', 'audio_output_format' => '', 'mixer_type' => '', 'audio_buffer_size' => '', 'buffer_before_play' => '', 'dsd_usb' => '', 'device' => '', 'volume_normalization' => '');
// Parse output for template $_mpdconf
foreach ($mpdconf as $key => $value) {
    foreach ($_mpd as $key2 => $value2) {
        if ($value['param'] == $key2) {
            $_mpd[$key2] = $value['value_player'];
        }
    }
}
function getDeviceName($file)
{
    $dev = rtrim(@file_get_contents($file));
    switch ($dev) {
        case "":
Ejemplo n.º 9
0
function wrk_sourcecfg($queueargs)
{
    $action = $queueargs['mount']['action'];
    unset($queueargs['mount']['action']);
    switch ($action) {
        case 'reset':
            $source = ConfigDB::read('cfg_source');
            foreach ($source as $mp) {
                sysCmd("umount -f '/mnt/NAS/" . $mp['name'] . "'");
                sysCmd("rmdir '/mnt/NAS/" . $mp['name'] . "'");
            }
            $return = ConfigDB::delete('cfg_source') ? 1 : 0;
            break;
        case 'add':
            print_r($queueargs);
            unset($queueargs['mount']['id']);
            // write new entry
            $newmountID = ConfigDB::write('cfg_source', array_values($queueargs['mount']));
            $return = wrk_sourcemount('mount', $newmountID) ? 1 : 0;
            break;
        case 'edit':
            $mp = ConfigDB::read('cfg_source', '', $queueargs['mount']['id']);
            ConfigDB::update('cfg_source', '', $queueargs['mount']);
            sysCmd("umount -f '/mnt/NAS/" . $mp[0]['name'] . "'");
            if ($mp[0]['name'] != $queueargs['mount']['name']) {
                sysCmd("rmdir '/mnt/NAS/" . $mp[0]['name'] . "'");
                sysCmd("mkdir '/mnt/NAS/" . $queueargs['mount']['name'] . "'");
            }
            $return = wrk_sourcemount('mount', $queueargs['mount']['id']) ? 1 : 0;
            break;
        case 'delete':
            $mp = ConfigDB::read('cfg_source', '', $queueargs['mount']['id']);
            sysCmd("umount -f '/mnt/NAS/" . $mp[0]['name'] . "'");
            sysCmd("rmdir '/mnt/NAS/" . $mp[0]['name'] . "'");
            $return = ConfigDB::delete('cfg_source', $queueargs['mount']['id']) ? 1 : 0;
            break;
    }
    return $return;
}
Ejemplo n.º 10
0
function _parseMpdConf()
{
    // prepare array
    $_mpd = array('port' => '', 'gapless_mp3_playback' => '', 'auto_update' => '', 'samplerate_converter' => '', 'auto_update_depth' => '', 'zeroconf_enabled' => '', 'zeroconf_name' => '', 'audio_output_format' => '', 'mixer_type' => '', 'audio_buffer_size' => '', 'buffer_before_play' => '', 'dsd_usb' => '', 'device' => '', 'volume_normalization' => '');
    // read in mpd conf settings
    $mpdconf = ConfigDB::read('', 'mpdconf');
    // parse output for template
    foreach ($mpdconf as $key => $value) {
        if (in_array($value['param'], array_keys($_mpd))) {
            $_mpd[$value['param']] = $value['value_player'];
        }
    }
    // parse audio output format, ex "44100:16:2"
    $_mpd += parseAudioFormat($_mpd['audio_output_format']);
    return $_mpd;
}
Ejemplo n.º 11
0
            uiSetNotification('Job failed', 'Background worker is busy');
        }
    }
    // create job for background worker
    if (workerPushTask('netcfg', $wlan0 . $eth0)) {
        uiSetNotification('Network config', isset($_GET['reset']) && $_GET['reset'] == 1 ? 'Network config reset' : 'Network config modified');
    } else {
        uiSetNotification('Job failed', 'Background worker is busy');
    }
    // unlock session file
    Session::close();
}
// wait for worker
waitWorker();
$net = ConfigDB::read('cfg_lan');
$wifisec = ConfigDB::read('cfg_wifisec');
// eth0
$_eth0 = isset($_SESSION['netconf']['eth0']) && !empty($_SESSION['netconf']['eth0']) ? $_SESSION['netconf']['eth0']['ip'] : "Not used";
$_int0dhcp = "<option value=\"true\" " . (isset($net[0]['dhcp']) && $net[0]['dhcp'] == "true" ? "selected" : "") . " >enabled (Auto)</option>\n";
$_int0dhcp .= "<option value=\"false\" " . (isset($net[0]['dhcp']) && $net[0]['dhcp'] == "false" ? "selected" : "") . " >disabled (Static)</option>\n";
$_int0 = $net[0];
// wlan0
$_wlan0 = isset($_SESSION['netconf']['wlan0']) && !empty($_SESSION['netconf']['wlan0']) ? $_SESSION['netconf']['wlan0']['ip'] : "Not used";
$_wlan0ssid = $wifisec[0]['ssid'];
// TC (Tim Curtis) 2015-04-29: reorder so WPA/WPA2 is first
$_wlan0security = "<option value=\"wpa\"" . ($wifisec[0]['security'] == 'wpa' ? "selected" : "") . ">WPA/WPA2 Personal</option>\n";
$_wlan0security .= "<option value=\"wep\"" . ($wifisec[0]['security'] == 'wep' ? "selected" : "") . ">WEP</option>\n";
$_wlan0security .= "<option value=\"none\"" . ($wifisec[0]['security'] == 'none' ? "selected" : "") . ">No security</option>\n";
// unlock session files
Session::close();
render("net-config");
Ejemplo n.º 12
0
 /**
  * Devuelve la clave maestra que ha sido encriptada con la clave temporal
  *
  * @param $pass string con la clave utilizada para encriptar
  * @return string con la clave maestra desencriptada
  */
 public static function getTempMasterPass($pass)
 {
     $passLogin = hex2bin(ConfigDB::getValue('tempmaster_pass'));
     $passLoginIV = hex2bin(ConfigDB::getValue('tempmaster_passiv'));
     return Crypt::getDecrypt($passLogin, $passLoginIV, $pass);
 }
Ejemplo n.º 13
0
 /**
  * Actualiza el hash de las cuentas en el histórico.
  *
  * @param $newHash string El nuevo hash de la clave maestra
  * @return bool
  */
 public static function updateAccountsMPassHash($newHash)
 {
     $query = 'UPDATE accHistory SET ' . 'acchistory_mPassHash = :newHash ' . 'WHERE acchistory_mPassHash = :oldHash';
     $data['newHash'] = $newHash;
     $data['oldHash'] = ConfigDB::getValue('masterPwd');
     return DB::getQuery($query, __FUNCTION__, $data);
 }
Ejemplo n.º 14
0
 /**
  * Crear el usuario admin de sysPass.
  * Esta función crea el grupo, perfil y usuario 'admin' para utilizar sysPass.
  *
  * @throws SPException
  */
 private static function createAdminAccount()
 {
     // Datos del grupo
     Groups::$groupName = "Admins";
     Groups::$groupDescription = "Admins";
     if (!Groups::addGroup()) {
         self::rollback();
         throw new SPException(SPException::SP_CRITICAL, _('Error al crear el grupo "admin"'), _('Informe al desarrollador'));
     }
     $User = new User();
     // Establecer el id de grupo del usuario al recién creado
     $User->setUserGroupId(Groups::$queryLastId);
     $Profile = new Profile();
     $Profile->setName('Admin');
     $Profile->setAccAdd(true);
     $Profile->setAccView(true);
     $Profile->setAccViewPass(true);
     $Profile->setAccViewHistory(true);
     $Profile->setAccEdit(true);
     $Profile->setAccEditPass(true);
     $Profile->setAccDelete(true);
     $Profile->setConfigGeneral(true);
     $Profile->setConfigEncryption(true);
     $Profile->setConfigBackup(true);
     $Profile->setMgmCategories(true);
     $Profile->setMgmCustomers(true);
     $Profile->setMgmUsers(true);
     $Profile->setMgmGroups(true);
     $Profile->setMgmProfiles(true);
     $Profile->setEvl(true);
     if (!$Profile->profileAdd()) {
         self::rollback();
         throw new SPException(SPException::SP_CRITICAL, _('Error al crear el perfil "admin"'), _('Informe al desarrollador'));
     }
     // Datos del usuario
     $User->setUserLogin(self::$_username);
     $User->setUserPass(self::$_password);
     $User->setUserName('Admin');
     $User->setUserProfileId($Profile->getId());
     $User->setUserIsAdminApp(true);
     $User->setUserIsAdminAcc(false);
     $User->setUserIsDisabled(false);
     if (!$User->addUser()) {
         self::rollback();
         throw new SPException(SPException::SP_CRITICAL, _('Error al crear el usuario "admin"'), _('Informe al desarrollador'));
     }
     // Guardar el hash de la clave maestra
     ConfigDB::setCacheConfigValue('masterPwd', Crypt::mkHashPassword(self::$_masterPassword));
     ConfigDB::setCacheConfigValue('lastupdatempass', time());
     ConfigDB::writeConfig(true);
     if (!$User->updateUserMPass(self::$_masterPassword)) {
         self::rollback();
         throw new SPException(SPException::SP_CRITICAL, _('Error al actualizar la clave maestra del usuario "admin"'), _('Informe al desarrollador'));
     }
 }
Ejemplo n.º 15
0
        if (workerPushTask('sourcecfg', $_POST)) {
            uiSetNotification('Mount point modified', 'MPD database update initiated...');
        } else {
            uiSetNotification('Job failed', 'Background worker is busy');
        }
    }
}
Session::close();
// wait for worker
waitWorker();
// update MPD db after worker finishes
if (false !== ($mpd = openMpdSocket(MPD_HOST, 6600))) {
    execMpdCommand($mpd, 'update');
    closeMpdSocket($mpd);
}
$source = ConfigDB::read('cfg_source');
$_mounts = '';
foreach ($source as $mp) {
    $icon = wrk_checkStrSysfile('/proc/mounts', $mp['name']) ? "<i class='icon-ok green sx'></i>" : "<i class='icon-remove red sx'></i>";
    $_mounts .= "<p><a href=\"sources.php?p=edit&id=" . $mp['id'] . "\" class='btn btn-large' style='width: 240px;'> " . $icon . " " . $mp['name'] . " (" . $mp['address'] . ") </a></p>";
}
$tpl = "sources";
if (isset($_GET['p']) && !empty($_GET['p'])) {
    if (isset($_GET['id']) && !empty($_GET['id'])) {
        $_id = $_GET['id'];
        foreach ($source as $mount) {
            if ($mount['id'] == $_id) {
                $_name = $mount['name'];
                $_address = $mount['address'];
                $_remotedir = $mount['remotedir'];
                $_username = $mount['username'];
Ejemplo n.º 16
0
 /**
  * Crear un nuevo registro de histório de cuenta en la BBDD.
  *
  * @param int  $id       el id de la cuenta primaria
  * @param bool $isDelete indica que la cuenta es eliminada
  * @return bool
  */
 public static function addHistory($id, $isDelete = false)
 {
     $query = 'INSERT INTO accHistory ' . '(acchistory_accountId,' . 'acchistory_categoryId,' . 'acchistory_customerId,' . 'acchistory_name,' . 'acchistory_login,' . 'acchistory_url,' . 'acchistory_pass,' . 'acchistory_IV,' . 'acchistory_notes,' . 'acchistory_countView,' . 'acchistory_countDecrypt,' . 'acchistory_dateAdd,' . 'acchistory_dateEdit,' . 'acchistory_userId,' . 'acchistory_userGroupId,' . 'acchistory_userEditId,' . 'acchistory_otherUserEdit,' . 'acchistory_otherGroupEdit,' . 'acchistory_isModify,' . 'acchistory_isDeleted,' . 'acchistory_mPassHash) ' . 'SELECT account_id,' . 'account_categoryId,' . 'account_customerId,' . 'account_name,' . 'account_login,' . 'account_url,' . 'account_pass,' . 'account_IV,' . 'account_notes,' . 'account_countView,' . 'account_countDecrypt,' . 'account_dateAdd,' . 'account_dateEdit,' . 'account_userId,' . 'account_userGroupId,' . 'account_userEditId,' . 'account_otherUserEdit,' . 'account_otherGroupEdit,' . ':isModify,' . ':isDelete,' . ':masterPwd ' . 'FROM accounts WHERE account_id = :account_id';
     $data['account_id'] = $id;
     $data['isModify'] = $isDelete === false ? 1 : 0;
     $data['isDelete'] = $isDelete === false ? 0 : 1;
     $data['masterPwd'] = ConfigDB::getValue('masterPwd');
     return DB::getQuery($query, __FUNCTION__, $data);
 }
Ejemplo n.º 17
0
        echo "Background worker is busy";
    }
    // Display template if not clock radio reload or tcmods conf reload
    if (isset($tpl)) {
        render($tpl);
    }
    exit;
}
/*
 * Json commands
 */
if (isset($_GET['cmd']) && $_GET['cmd'] != '') {
    header('Content-type: application/json');
    switch ($cmd = $_GET['cmd']) {
        case 'getaudiodevdesc':
            $result = ConfigDB::read('cfg_audiodev', $_POST['audiodev']);
            $res = $result[0];
            break;
        case 'getupnpcoverurl':
            $rtn = sysCmd('upexplorer --album-art "' . $_SESSION['upnp_name'] . '"');
            $res = array('coverurl' => $rtn[0]);
            break;
        case 'readtcmconf':
            $res = getTcmodsConf();
            break;
        case 'updatetcmconf':
            $res = _updTcmodsConf($_POST);
            break;
        case 'getmpdstatus':
            $res = _parseStatusResponse(mpdStatus($mpd));
            break;
Ejemplo n.º 18
0
 /**
  * Update session and config table
  */
 public static function update($key, $val)
 {
     $_SESSION[$key] = $val;
     ConfigDB::update('cfg_engine', $key, $val);
 }