/**
 * Admin Permissions
 * 
 * Performs a control against the database if current Admin credentials sessions belong to an existent administrator.
 * Also defines admin superadmin  wrights if not defined.
 * 
 * On failure destroys current session, echoes Admin login form and returns false.
 * 
 * @uses req()
 * @return bool|string 
 */
function admin_permissions()
{
    if (isset($_SESSION[LOCAL_IDENTIFIER . '_ADMIN_NAME']) && isset($_SESSION[LOCAL_IDENTIFIER . '_ADMIN_PASS'])) {
        $query = "  \n            SELECT\n                `username`,\n                `password`,\n                `superadmin`\n            FROM `" . DBT_PREFIX . "administrators`\n            WHERE\n                `username` ='" . process_plain_text($_SESSION[LOCAL_IDENTIFIER . '_ADMIN_NAME']) . "'\n                AND `password` ='" . process_plain_text($_SESSION[LOCAL_IDENTIFIER . '_ADMIN_PASS']) . "'\n                LIMIT 1";
        sql_select($query, $results);
        if (mysql_num_rows($results) > 0) {
            $row = mysql_fetch_array($results);
            if (!defined(LOCAL_IDENTIFIER . '_SUPERADMIN')) {
                define(LOCAL_IDENTIFIER . '_SUPERADMIN', $row['superadmin']);
            }
            return true;
        } else {
            $_SESSION = array();
            session_destroy();
            echo ADMIN_LOGIN_FORM;
            return false;
        }
    } else {
        if (isset($_POST['login_name']) || isset($_POST['login_pass'])) {
            if (req("login_name", "POST", $sanitise = false) == "exit" && req("login_pass", "POST", $sanitise = false) == "exit") {
                echo "<br> <h2>" . translate("logged_out") . "</strong></h2>";
            } else {
                echo "<br>" . ALERT_BOX_OPEN . translate("error_username_password") . " " . translate("ammend") . ALERT_BOX_CLOSE;
            }
            echo ADMIN_LOGIN_FORM;
            return false;
        } else {
            echo ADMIN_LOGIN_FORM;
            return false;
        }
    }
}
 /**
  * @return Boolean
  */
 public function save()
 {
     $query = "\n            INSERT IGNORE INTO\n                `seedclima_sensor_info`\n            SET\n                `f_station_code` = " . check_null_val(process_plain_text($this->_fStationCode)) . ",\n                `f_sensor_ch` = " . check_null_val(process_plain_text($this->_fSensorCh)) . ",\n                `f_sensor_code` = " . check_null_val(process_plain_text($this->_fSensorCode)) . ",\n                `f_chain_code` = " . check_null_val(process_plain_text($this->_fChainCode)) . ",\n                `f_group_code` = " . check_null_val(process_plain_text($this->_fGroupCode)) . ",\n                `f_unit_code` = " . check_null_val(process_plain_text($this->_fUnitCode)) . ",\n                `f_name` = " . check_null_val(process_plain_text($this->_fName)) . ",\n                `f_unit` = " . check_null_val(process_plain_text($this->_fUnit)) . ",\n                `f_div` = " . check_null_val(process_plain_text($this->_fDiv)) . ",\n                `f_mul` = " . check_null_val(process_plain_text($this->_fMul)) . ",\n                `f_val_neg` = " . check_null_val(process_plain_text($this->_fValNeg)) . ",\n                `f_val_log` = " . check_null_val(process_plain_text($this->_fValLog)) . ",\n                `f_val_last` = " . check_null_val(process_plain_text($this->_fValLast)) . ",\n                `f_val_sum` = " . check_null_val(process_plain_text($this->_fValSum)) . ",\n                `f_val_aver` = " . check_null_val(process_plain_text($this->_fValAver)) . ",\n                `f_val_min` = " . check_null_val(process_plain_text($this->_fValMin)) . ",\n                `f_val_max` = " . check_null_val(process_plain_text($this->_fValMax)) . ",\n                `f_val_time` = " . check_null_val(process_plain_text($this->_fValTime)) . ",\n                `f_val_user` = " . check_null_val(process_plain_text($this->_fValUser)) . ",\n                `f_create_time` = " . check_null_val(process_plain_text($this->_fCreateTime)) . ",\n                `f_val_axilary` = " . check_null_val(process_plain_text($this->_fValAxilary)) . ",\n                `f_user_app` = " . check_null_val(process_plain_text($this->_fUserApp)) . ",\n                `f_color` = " . check_null_val(process_plain_text($this->_fColor)) . ",\n                `f_sensor_user_name` = " . check_null_val(process_plain_text($this->_fSensorUserName)) . ",\n                `f_user_unit_code` = " . check_null_val(process_plain_text($this->_fUserUnitCode)) . ",\n                `graph_type` = " . check_null_val(process_plain_text($this->_graphType)) . ",\n                `min_expected` = " . check_null_val(process_plain_text($this->_minExpected)) . ",\n                `max_expected` = " . check_null_val(process_plain_text($this->_maxExpected)) . ",\n                `custom_name` = " . check_null_val(process_plain_text($this->_customName)) . ",\n                `custom_desc` = " . check_null_val(process_plain_text($this->_customDesc)) . ",\n                `custom_image` = " . check_null_val(process_plain_text($this->_customImage)) . ",\n                `enable_sensor` = " . check_null_val(process_plain_text($this->_enableSensor)) . ",\n                `chilling_hours_related` = " . check_null_val(process_plain_text($this->_chillingOursRelated)) . ",\n                `degrees_day_related` = " . check_null_val(process_plain_text($this->_degreesDayRelated)) . ",\n                `wind_rose_related` = " . check_null_val(process_plain_text($this->_windRoseRelated)) . ",\n                `priority` = " . check_null_val(process_plain_text($this->_priority)) . ",\n                `last_edition_time` = UNIX_TIMESTAMP(),\n                `last_update_date` = UNIX_TIMESTAMP(),\n                `last_editor` = " . check_null_val(process_plain_text($this->_lastEditor)) . "\n            ";
     return sql_select($query, $results);
 }
 /**
  *
  * @param <type> $sensorDataByDatetime
  * @param <type> $f_station_code
  */
 private function _buildInsertSensorDataQuery($sensorDataByDatetime, $f_station_code)
 {
     $f_date = $sensorDataByDatetime->f_date;
     $sensor = false;
     $sensorId = false;
     $lastSensorDataRetrieveInfoTable = '';
     foreach ($sensorDataByDatetime as $key => $val) {
         if (preg_match("#sens_#i", $key)) {
             $fields = explode("_", $key);
             /* Cargar Sensor */
             if (!$sensor || $sensor->getId() != $sensorId) {
                 if (array_key_exists($f_station_code . '_' . $fields['3'] . '_' . $fields['2'], $this->_loadedSensors)) {
                     $sensor = $this->_loadedSensors[$f_station_code . '_' . $fields['3'] . '_' . $fields['2']];
                 } else {
                     $sensor = Sensor::load(false, false, $f_station_code, $fields['3'], $fields['2']);
                     $this->_loadedSensors[$f_station_code . '_' . $fields['3'] . '_' . $fields['2']] = $sensor;
                 }
             }
             /* Si no se puede cargar el sensor, saltar una iteracion */
             if (!$sensor) {
                 continue;
             }
             /**
              * IF NO DATA THEN CONTINUE
              */
             if (check_null_val(process_plain_text($val)) == 'NULL') {
                 continue;
             }
             /**
              * Value is out of range?
              */
             $mixExpected = is_numeric($sensor->getMinExpected()) ? $sensor->getMinExpected() : false;
             $maxExpected = is_numeric($sensor->getMaxExpected()) ? $sensor->getMaxExpected() : false;
             if ($mixExpected !== false && $maxExpected !== false) {
                 if ($val >= $mixExpected && $val <= $maxExpected) {
                     $outOfRange = 0;
                 } else {
                     $outOfRange = 1;
                 }
             } else {
                 $outOfRange = 0;
             }
             /**
              * Update retrieved sensors data info
              */
             $tableSuffix = date('Y_m', strtotime($f_date));
             $currentSensorDataRetrieveInfoTable = DBT_PREFIX . "sensor_data_retrieve_info_{$tableSuffix}";
             if ($lastSensorDataRetrieveInfoTable != $currentSensorDataRetrieveInfoTable) {
                 $createTableQuery = "\n                    CREATE TABLE IF NOT EXISTS `{$currentSensorDataRetrieveInfoTable}` (\n                        `row_id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n                        `f_station_code` int(11) unsigned NOT NULL,\n                        `f_sensor_type` varchar(6) COLLATE utf8_unicode_ci NOT NULL,\n                        `f_sensor_code` int(11) unsigned NOT NULL,\n                        `f_sensor_ch` int(11) unsigned NOT NULL,\n                        `f_read_time` int(11) unsigned NOT NULL,\n                        `f_write_time` int(11) unsigned NOT NULL,\n                        `f_data_retrieved` decimal(15,4) NOT NULL,\n                        `f_unit` int(11) DEFAULT NULL,\n                        `out_of_range` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT 'si la lectura està fuera de los parametros asignados por el admin en los detalles del sensor',\n                        `wind_direction_vector` decimal(15,4) DEFAULT NULL,\n                        PRIMARY KEY (`row_id`),\n                        UNIQUE KEY `station_code_sensor_type_sensor_code_sensor_ch_read_time` (`f_station_code`,`f_sensor_type`,`f_sensor_code`,`f_sensor_ch`,`f_read_time`),\n                        KEY `f_station_code` (`f_station_code`),\n                        KEY `f_sensor_code` (`f_sensor_code`),\n                        KEY `f_read_time` (`f_read_time`),\n                        KEY `out_of_range` (`out_of_range`),\n                        KEY `f_sensor_type` (`f_sensor_type`),\n                        KEY `wind_direction_vector` (`wind_direction_vector`),\n                        KEY `f_read_time_combined` (`f_read_time`,`f_station_code`,`f_sensor_code`,`f_sensor_type`)\n                        ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci\n                        ";
                 if (!sql_select($createTableQuery, $createTableQueryResults)) {
                     return false;
                 }
                 usleep(50);
             }
             /**
              * Fix, ETo debe mostrarse como SUM y no como AVER como declara el server remoto
              */
             $fields['1'] = $sensor->getSensorCode() == 1201 ? 'sum' : $fields['1'];
             $queryString = "\n                    INSERT IGNORE INTO\n                        `{$currentSensorDataRetrieveInfoTable}`\n                    SET\n                        `f_station_code` = {$sensor->getStationCode()},\n                        `f_sensor_type` = " . check_null_val(process_plain_text($fields['1'])) . ",\n                        `f_sensor_code` = {$sensor->getSensorCode()},\n                        `f_sensor_ch` = {$sensor->getSensorCh()},\n                        `f_read_time` = " . (int) strtotime($f_date) . ",\n                        `f_write_time` = UNIX_TIMESTAMP(),\n                        `f_data_retrieved` = " . check_null_val(process_plain_text($val)) . ",\n                        `f_unit` = '" . process_plain_text($sensor->getUnit()) . "',\n                        `out_of_range` = {$outOfRange},\n                        `wind_direction_vector` = " . ($sensor->isWindDirectionSensor() ? deg2cpd($val, true) : 'NULL') . "\n                        ";
             if (sql_select($queryString, $results)) {
                 /**
                  * Update retrieved info index
                  */
                 $updateStationDataRetrieveInfo = "\n                        INSERT IGNORE INTO\n                            `" . DBT_PREFIX . "station_data_retrieve_info`\n                        SET\n                            `f_station_code` = " . process_plain_text($f_station_code) . ",\n                            `last_read_time` = " . strtotime($f_date) . ",\n                            `last_read_time_success` = 1\n                        ";
                 sql_select($updateStationDataRetrieveInfo, $results);
                 usleep(1000);
             } else {
                 $this->_proccessOutput("something goes wrong with function _buildInsertSensorDataQuery()");
             }
         }
     }
     unset($sensorDataByDatetime);
 }
 /**
  *
  * @return Boolean
  */
 public function save()
 {
     $query = "\n            INSERT IGNORE INTO\n                `seedclima_station_info`\n            SET\n                `f_station_code` = " . check_null_val(process_plain_text($this->_fStationCode)) . ",\n                `f_date` = " . check_null_val(process_plain_text($this->_fDate)) . ",\n                `f_dev_id` = " . check_null_val(process_plain_text($this->_fDevId)) . ",\n                `f_name` = " . check_null_val(process_plain_text($this->_fName)) . ",\n                `f_descr` = " . check_null_val(process_plain_text($this->_fDescr)) . ",\n                `f_info` = " . check_null_val(process_plain_text($this->_fInfo)) . ",\n                `f_uid` = " . check_null_val(process_plain_text($this->_fUid)) . ",\n                `f_status` = " . check_null_val(process_plain_text($this->_fStatus)) . ",\n                `f_create_time` = " . check_null_val(process_plain_text($this->_fCreateTime)) . ",\n                `f_master_name` = " . check_null_val(process_plain_text($this->_fMasterName)) . ",\n                `f_date_min` = " . check_null_val(process_plain_text($this->_fDateMin)) . ",\n                `f_date_max` = " . check_null_val(process_plain_text($this->_fDateMax)) . ",\n                `f_date_last_down` = " . check_null_val(process_plain_text($this->_fDateLastDown)) . ",\n                `f_date_sens` = " . check_null_val(process_plain_text($this->_fDateSens)) . ",\n                `f_date_data` = " . check_null_val(process_plain_text($this->_fDateData)) . ",\n                `f_date_conf` = " . check_null_val(process_plain_text($this->_fDateConf)) . ",\n                `f_measure_int` = " . check_null_val(process_plain_text($this->_fMeasureInt)) . ",\n                `f_data_int` = " . check_null_val(process_plain_text($this->_fDataInt)) . ",\n                `f_timezone` = " . check_null_val(process_plain_text($this->_fTimezone)) . ",\n                `f_latitude` = " . check_null_val(process_plain_text($this->_fLatitude)) . ",\n                `f_longitude` = " . check_null_val(process_plain_text($this->_fLongitude)) . ",\n                `f_altitude` = " . check_null_val(process_plain_text($this->_fAltitude)) . ",\n                `f_hw_ver_major` = " . check_null_val(process_plain_text($this->_fHwVerMajor)) . ",\n                `f_hw_ver_minor` = " . check_null_val(process_plain_text($this->_fHwVerMinor)) . ",\n                `f_sw_ver_major` = " . check_null_val(process_plain_text($this->_fSwVerMajor)) . ",\n                `f_sw_ver_minor` = " . check_null_val(process_plain_text($this->_fSwVerMinor)) . ",\n                `f_sms_warn_numbers` = " . check_null_val(process_plain_text($this->_fSmsWarnNumbers)) . ",\n                `f_sms_warn_values` = " . check_null_val(process_plain_text($this->_fSmsWarnValues)) . ",\n                `f_gsm_mcc` = " . check_null_val(process_plain_text($this->_fGsmMcc)) . ",\n                `f_gsm_mnc` = " . check_null_val(process_plain_text($this->_fGsmMnc)) . ",\n                `f_gprs_apn` = " . check_null_val(process_plain_text($this->_fGprsApn)) . ",\n                `f_gprs_user_id` = " . check_null_val(process_plain_text($this->_fGprsUserId)) . ",\n                `f_gprs_passw` = " . check_null_val(process_plain_text($this->_fGprsPassw)) . ",\n                `f_sernum` = " . check_null_val(process_plain_text($this->_fSernum)) . ",\n                `f_date_comm` = " . check_null_val(process_plain_text($this->_fDateComm)) . ",\n                `f_user_station_name` = " . check_null_val(process_plain_text($this->_fUserStationName)) . ",\n                `f_user_name` = " . check_null_val(process_plain_text($this->_fUserName)) . ",\n                `custom_name` = " . check_null_val(process_plain_text($this->_customName)) . ",\n                `custom_desc` = " . check_null_val(process_plain_text($this->_customDesc)) . ",\n                `custom_image` = " . check_null_val(process_plain_text($this->_customImage)) . ",\n                `enable_station` = " . check_null_val(process_plain_text($this->_enableStation)) . ",\n                `show_in_home` = " . check_null_val(process_plain_text($this->_showInHome)) . ",\n                `priority` = " . check_null_val(process_plain_text($this->_priority)) . ",\n                `last_update_date` = UNIX_TIMESTAMP(),\n                `last_edition_time` = UNIX_TIMESTAMP(),\n                `last_editor` = " . check_null_val(process_plain_text($this->_lastEditor)) . "\n                 ";
     return sql_select($query, $results);
 }