function guifi_devices_select($filters, $action = '')
{
    guifi_log(GUIFILOG_TRACE, 'function guifi_devices_select()', $filters);
    $var = array();
    $found = FALSE;
    if ($filters['type'] == 'cable') {
        if ($filters['mode'] != 'cable-router') {
            $query = sprintf("\n        SELECT\n          l.lat, l.lon, r.nick ssid, r.id, r.nid, z.id zone_id\n        FROM {guifi_devices} r,{guifi_location} l, {guifi_zone} z\n        WHERE\n          l.id=%d\n          AND r.nid=l.id\n          AND l.zone_id=z.id", $filters['from_node']);
        } else {
            $query = sprintf("\n        SELECT\n          l.lat, l.lon, r.nick ssid, r.id r.nid, z.id zone_id, r.type,\n          r.fund_required, r.fund_amount, r.fund_currency\n        FROM {guifi_devices} r,{guifi_location} l, {guifi_zone} z\n        WHERE r.type IN ('radio','nat')\n          AND l.id=%d AND r.nid=l.id\n          AND l.zone_id=z.id", $filters['from_node']);
        }
    } else {
        $query = sprintf("\n      SELECT\n        l.lat, l.lon, r.id, r.clients_accepted, r.nid, z.id zone_id,\n        r.radiodev_counter, r.ssid, r.mode, r.antenna_mode,\n        r.fund_required, r.fund_amount, r.fund_currency\n      FROM {guifi_radios} r,{guifi_location} l, {guifi_zone} z\n      WHERE l.id<>%d\n        AND r.nid=l.id\n        AND l.zone_id=z.id", $filters['from_node']);
    }
    $devdist = array();
    $devarr = array();
    $k = 0;
    $devsq = db_query($query);
    while ($device = db_fetch_object($devsq)) {
        $k++;
        $l = FALSE;
        if ($filters['type'] != 'cable') {
            $oGC = new GeoCalc();
            $node = db_fetch_object(db_query('
        SELECT lat, lon
        FROM {guifi_location}
        WHERE id=%d', $filters['from_node']));
            $distance = round($oGC->EllipsoidDistance($device->lat, $device->lon, $node->lat, $node->lon), 3);
            if ($distance > $filters['dmax'] or $distance < $filters['dmin']) {
                continue;
            }
            if ($filters['azimuth']) {
                foreach (explode('-', $filters['azimuth']) as $minmax) {
                    list($min, $max) = explode(',', $minmax);
                    $Az = round($oGC->GCAzimuth($device->lat, $device->lon, $node->lat, $node->lon));
                    if ($Az <= $max and $Az >= $min) {
                        $l = TRUE;
                    }
                }
            } else {
                $l = TRUE;
            }
        }
        if ($l) {
            $devdist[$k] = $distance;
            $devarr[$k] = $device;
            $devarr[$k]->distance = $distance;
        }
    }
    asort($devdist);
    //  ob_start();
    //  print "Query: $query \n<br />";
    //  print_r($devdist);
    //  $txt = ob_get_contents();
    //  ob_end_clean();
    if (!empty($devdist)) {
        foreach ($devdist as $id => $foo) {
            $device = $devarr[$id];
            switch ($filters['type']) {
                case 'ap/client':
                    if ($filters['mode'] == 'ap' and $device->mode == 'client') {
                        $cr = guifi_count_radio_links($device->id);
                        if ($cr['ap'] < 1) {
                            _set_value($device, $node, $var, $filters['from_device'], $filters['from_radio'], $filters['search']);
                        }
                    } else {
                        if ($filters['mode'] == 'client' and $device->mode == 'ap') {
                            _set_value($device, $node, $var, $filters['from_device'], $filters['from_radio'], $filters['search']);
                        }
                    }
                    break;
                case 'wds':
                    if ($device->mode == 'ap') {
                        _set_value($device, $node, $var, $filters['from_device'], $filters['from_radio'], $filters['search']);
                    }
                    break;
                case 'cable':
                    _set_value($device, $node, $var, $filters['from_device'], $filters['from_radio'], $filters['search']);
                    break;
            }
            // eof switch link_type
        }
    }
    // eof while query device,node,zone
    $form = array('#type' => 'fieldset', '#collapsible' => FALSE, '#collapsed' => FALSE, '#prefix' => '<div id="list-devices">', '#suffix' => '</div>');
    if (count($var) == 0) {
        $form['d'] = array('#type' => 'item', '#parents' => array('dummy'), '#title' => t('No devices available'), '#value' => t('There are no devices to link within the given criteria, you can use the filters to get more results.'));
        $form['dbuttons'] = guifi_device_buttons(TRUE, $action, 0);
        return $form;
    }
    $form['d'] = array('#type' => 'radios', '#parents' => array('linked'), '#title' => t('select the device which do you like to link with'), '#options' => $var, '#attributes' => array('class' => 'required'));
    $form['dbuttons'] = guifi_device_buttons(TRUE, $action, 1);
    return $form;
}
Example #2
0
function guifi_cnml_home($cnmlid)
{
    if ($cnmlid == 0) {
        $vid = 1;
    } else {
        $vid = $cnmlid;
    }
    $CNML = new SimpleXMLElement('<cnml></cnml>');
    $CNML->addAttribute('version', '0.1');
    $CNML->addAttribute('server_id', '1');
    $CNML->addAttribute('server_url', 'http://guifi.net');
    $CNML->addAttribute('generated', date('Ymd hi', time()));
    switch ($vid) {
        case 1:
            //Home Avui
            $oGC = new GeoCalc();
            $btime = microtime(TRUE);
            $result = db_query("select COUNT(*) as num from {guifi_location} where status_flag='Working'");
            $classXML = $CNML->addChild('total_working_nodes');
            if ($record = db_fetch_object($result)) {
                $classXML->addAttribute('nodes', number_format($record->num, 0, ',', '.'));
            }
            // link statistics
            $dTotals = array();
            $dTotals['dTotal'] = 0;
            $dTotals['count'] = 0;
            $qlinks = db_query('
      SELECT
      l1.id, n1.id nid1, n2.id nid2, l1.link_type, n1.lat lat1,
      n1.lon lon1, n2.lat lat2, n2.lon lon2
      FROM guifi_links l1
      LEFT JOIN guifi_links l2 ON l1.id=l2.id
      LEFT JOIN guifi_location n1 ON l1.nid=n1.id
      LEFT JOIN guifi_location n2 ON l2.nid=n2.id
    WHERE l1.nid != l2.nid AND l1.device_id != l2.device_id');
            unset($listed);
            while ($link = db_fetch_object($qlinks)) {
                if (!isset($listed[$link->id])) {
                    $listed[$link->id] = $link;
                } else {
                    continue;
                }
                $d = round($oGC->EllipsoidDistance($link->lat1, $link->lon1, $link->lat2, $link->lon2), 1);
                if ($d < 100) {
                    $dTotals['dTotal'] += $d;
                    $dTotals['count']++;
                } else {
                    guifi_log(GUIFILOG_TRACE, sprintf('Probable DISTANCE error between nodes (%d and %d) %d kms.', $link->nid1, $link->nid2, $d));
                }
            }
            $classXML = $CNML->addChild('total_links');
            $classXML->addAttribute('num', number_format($dTotals['count'], 0, ',', '.'));
            $classXML->addAttribute('kms', number_format($dTotals['dTotal'], 1, ',', '.'));
            //add nodes last week
            $afecha = getdate();
            $tiempomax = mktime($afecha[hours], $afecha[minutes], $afecha[seconds], $afecha[mon], $afecha[mday], $afecha[year]);
            $tiempomin = $tiempomax - 604800;
            $qnodes = "select COUNT(*) as num from {guifi_location}\n      where status_flag!='Dropped'\n      and timestamp_created>" . $tiempomin . " and timestamp_created<=" . $tiempomax;
            $result = db_query($qnodes);
            $classXML = $CNML->addChild('nodes_last_week');
            if ($record = db_fetch_object($result)) {
                $classXML->addAttribute('total_nodes', number_format($record->num, 0, ',', '.'));
            }
            $qnodes = "select COUNT(*) as num from {guifi_location}\n      where status_flag='Working'\n      and timestamp_created>" . $tiempomin . " and timestamp_created<=" . $tiempomax;
            $result = db_query($qnodes);
            if ($record = db_fetch_object($result)) {
                $classXML->addAttribute('working_nodes', number_format($record->num, 0, ',', '.'));
            }
            $etime = microtime(TRUE);
            $classXML = $CNML->addChild('control');
            $classXML->addAttribute('in_seconds', number_format($etime - $btime, 4));
            break;
        case 2:
            //Home services
            //$result=db_query("select service_type as service,COUNT(*) as num from guifi_services where status_flag='Working' group by service_type");
            $result = db_query("select service_type as service,description as description,COUNT(*) as num from guifi_services as t1\n    inner join guifi_types as t2 on t2.type = 'service' and t1.service_type = t2.text\n    where status_flag='Working'\n    group by service_type");
            $classXML = $CNML->addChild('working_services');
            $num_type_services = 0;
            $total_services = 0;
            while ($record = db_fetch_object($result)) {
                $num_type_services++;
                $total_services += $record->num;
                $classXML2 = $classXML->addChild('service');
                $classXML2->addAttribute("type", $record->service);
                $classXML2->addAttribute("description", t($record->description));
                $classXML2->addAttribute("total", $record->num);
            }
            $classXML->addAttribute("types", $num_type_services);
            $classXML->addAttribute("total", $total_services);
            break;
        case 3:
            //Home budgets
            $classXML = $CNML->addChild('general_open_budgets');
            if (module_exists('budgets')) {
                $today = getdate();
                $qbudgets = db_query("SELECT b.id, b.expires " . "FROM {budgets} b " . "WHERE b.budget_status = 'Open' and b.zone_id = 3671 and b.expires >= " . $today[0] . " " . "ORDER BY b.id DESC");
                while ($budget = db_fetch_object($qbudgets)) {
                    $b = node_load(array('nid' => $budget->id));
                    $classXML2 = $classXML->addChild('budget');
                    $classXML2->addAttribute("id", $budget->id);
                    $classXML2->addAttribute("title", $b->title);
                    $classXML2->addAttribute("amount", $b->total);
                    $classXML2->addAttribute("funded", $b->covered);
                    $classXML2->addAttribute("currency_symbol", $b->currency_symbol);
                }
            }
    }
    return $CNML;
}
function guifi_device_link_list($id = 0, $ltype = '%')
{
    $oGC = new GeoCalc();
    $total = 0;
    if ($ltype == '%') {
        $title = t('links');
    } else {
        $title = t('links') . ' (' . $ltype . ')';
    }
    $header = array(t('type'), t('linked devices'), t('ip'), t('status'), t('routing'), t('kms.'), t('az.'));
    $queryloc1 = db_query("\n    SELECT\n      c.id, c.link_type, c.routing, l.nick, c.device_id, d.nick\n      device_nick, a.ipv4 ip, i.interface_type itype, c.flag,\n      l.lat, l.lon\n    FROM {guifi_links} c\n      LEFT JOIN {guifi_devices} d ON c.device_id=d.id\n      LEFT JOIN {guifi_interfaces} i ON c.interface_id = i.id\n      LEFT JOIN {guifi_ipv4} a ON i.id=a.interface_id AND a.id=c.ipv4_id\n      LEFT JOIN {guifi_location} l ON d.nid = l.id\n    WHERE c.device_id = %d\n      AND link_type like '%s'\n    ORDER BY c.link_type, c.device_id", $id, $ltype);
    if (db_num_rows($queryloc1)) {
        while ($loc1 = db_fetch_object($queryloc1)) {
            $queryloc2 = db_query("\n        SELECT\n          c.id, l.nick, r.ssid, c.device_id, d.nick device_nick,\n          a.ipv4 ip, i.interface_type itype, l.lat, l.lon\n        FROM {guifi_links} c\n          LEFT JOIN {guifi_devices} d ON c.device_id=d.id\n          LEFT JOIN {guifi_interfaces} i ON c.interface_id = i.id\n          LEFT JOIN {guifi_ipv4} a ON i.id=a.interface_id\n            AND a.id=c.ipv4_id\n          LEFT JOIN {guifi_location} l ON d.nid = l.id\n          LEFT JOIN {guifi_radios} r ON d.id=r.id\n            AND i.radiodev_counter=r.radiodev_counter\n        WHERE c.id = %d\n          AND c.device_id != %d", $loc1->id, $loc1->device_id);
            while ($loc2 = db_fetch_object($queryloc2)) {
                $gDist = round($oGC->EllipsoidDistance($loc1->lat, $loc1->lon, $loc2->lat, $loc2->lon), 3);
                if ($gDist) {
                    $total = $total + $gDist;
                    $dAz = round($oGC->GCAzimuth($loc1->lat, $loc1->lon, $loc2->lat, $loc2->lon));
                    // Calculo orientacio
                    if ($dAz < 23) {
                        $dOr = t("N");
                    } else {
                        if ($dAz < 68) {
                            $dOr = t("NE");
                        } else {
                            if ($dAz < 113) {
                                $dOr = t("E");
                            } else {
                                if ($dAz < 158) {
                                    $dOr = t("SE");
                                } else {
                                    if ($dAz < 203) {
                                        $dOr = t("S");
                                    } else {
                                        if ($dAz < 248) {
                                            $dOr = t("SW");
                                        } else {
                                            if ($dAz < 293) {
                                                $dOr = t("W");
                                            } else {
                                                if ($dAz < 338) {
                                                    $dOr = t("NW");
                                                } else {
                                                    $dOr = t("N");
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    $gDist = 'n/a';
                }
                $cr = db_fetch_object(db_query("SELECT count(*) count FROM {guifi_radios} r WHERE id=%d", $loc2->device_id));
                if ($cr->count > 1) {
                    $dname = $loc2->device_nick . '/' . $loc2->ssid;
                } else {
                    $dname = $loc2->device_nick;
                }
                $rows[] = array($loc1->id . '-' . $loc1->link_type . ' (' . $loc1->itype . '-' . $loc2->itype . ')', '<a href="' . base_path() . 'guifi/device/' . $loc2->device_id . '">' . $dname . '</a>', $loc1->ip . '/' . $loc2->ip, array('data' => t($loc1->flag), 'class' => $loc1->flag), array('data' => $gDist, 'class' => 'number'), $loc1->routing, $dAz . '-' . $dOr);
            }
        }
        $output .= theme('table', $header, $rows);
        $output = theme('box', $title, $output);
        if ($total) {
            $output .= t('Total:') . '&nbsp;' . $total . '&nbsp;' . t('kms.');
        }
        return $output;
    }
    return NULL;
}
Example #4
0
     if (!empty($_REQUEST['lat']) && !empty($_REQUEST['lng'])) {
         if (!is_numeric($_REQUEST['lat'])) {
             $gBitSystem->fatalError('Invalid latitude submitted, please check the lat value');
         }
         if (!is_numeric($_REQUEST['lng'])) {
             $gBitSystem->fatalError('Invalid longitude submitted, please check the lng value');
         }
         $dLat = $_REQUEST['lat'];
         $dLng = $_REQUEST['lng'];
         // if we have lat lng values for the user we use it as the center
     } elseif (is_numeric($gBitUser->getField('lat'))) {
         $dLat = $gBitUser->getField('lat');
         $dLng = $gBitUser->getField('lng');
     }
     require_once UTIL_PKG_PATH . 'geocalc/GeoCalc.class.php';
     $oGC = new GeoCalc();
     // distance in kilometers
     // @TODO turn this into a package config default
     $dRadius = $_REQUEST['distance'];
     // Calculate the boundary distance in degrees longitude / latitude
     $dAddLat = $oGC->getLatPerKm() * $dRadius;
     $dAddLon = $oGC->getLonPerKmAtLat($dLat) * $dRadius;
     // trip the geo service
     $_REQUEST['up_lat'] = $dLat + $dAddLat;
     $_REQUEST['right_lng'] = $dLng + $dAddLon;
     $_REQUEST['down_lat'] = $dLat - $dAddLat;
     $_REQUEST['left_lng'] = $dLng - $dAddLon;
 }
 // can force a general lookup using Any param if distance is not specified
 if (!empty($_REQUEST['content_type_guid']) && $_REQUEST['content_type_guid'] == 'Any') {
     $_REQUEST['content_type_guid'] = NULL;
Example #5
0
function theme_guifi_node_links_by_type($id = 0, $ltype = '%')
{
    $oGC = new GeoCalc();
    $total = 0;
    if ($ltype == '%') {
        $titlebox = t('links');
    } else {
        $titlebox = t('links') . ' (' . $ltype . ')';
    }
    $header = array(t('linked nodes (device)'), t('ip'), t('status'), t('kms.'), t('az.'));
    $listed = array('0');
    $queryloc1 = db_query("SELECT c.id, l.id nid, l.nick, c.device_id, d.nick device_nick, a.ipv4 ip," . "  c.flag, l.lat, l.lon, r.ssid " . "FROM {guifi_links} c " . "  LEFT JOIN {guifi_devices} d ON c.device_id=d.id " . "  LEFT JOIN {guifi_interfaces} i ON c.interface_id = i.id " . "  LEFT JOIN {guifi_location} l ON d.nid = l.id " . "  LEFT JOIN {guifi_ipv4} a ON i.id=a.interface_id " . "    AND a.id=c.ipv4_id " . "  LEFT JOIN {guifi_radios} r ON d.id=r.id " . "    AND i.radiodev_counter=r.radiodev_counter " . "WHERE d.nid = %d AND link_type like '%s' " . "ORDER BY c.device_id, i.id", $id, $ltype);
    $devant = ' ';
    while ($loc1 = db_fetch_object($queryloc1)) {
        $queryloc2 = db_query("SELECT c.id, l.id nid, l.nick, r.ssid, c.device_id, d.nick device_nick, " . "  a.ipv4 ip, l.lat, l.lon " . "FROM {guifi_links} c " . "  LEFT JOIN {guifi_devices} d ON c.device_id=d.id " . "  LEFT JOIN {guifi_interfaces} i ON c.interface_id = i.id " . "  LEFT JOIN {guifi_location} l ON d.nid = l.id " . "  LEFT JOIN {guifi_ipv4} a ON i.id=a.interface_id " . "    AND a.id = c.ipv4_id " . "  LEFT JOIN {guifi_radios} r ON d.id=r.id " . "    AND i.radiodev_counter=r.radiodev_counter " . "WHERE c.id = %d " . "  AND c.device_id <> %d " . "  AND c.id NOT IN (%s)", $loc1->id, $loc1->device_id, implode(",", $listed));
        $listed[] = $loc1->device_id;
        $devact = $loc1->device_nick;
        if ($loc1->ssid) {
            $devact .= ' - ' . $loc1->ssid;
        }
        while ($loc2 = db_fetch_object($queryloc2)) {
            $gDist = round($oGC->EllipsoidDistance($loc1->lat, $loc1->lon, $loc2->lat, $loc2->lon), 3);
            if ($gDist) {
                $total = $total + $gDist;
                $dAz = round($oGC->GCAzimuth($loc1->lat, $loc1->lon, $loc2->lat, $loc2->lon));
                // Calculo orientacio
                if ($dAz < 23) {
                    $dOr = t("N");
                } else {
                    if ($dAz < 68) {
                        $dOr = t("NE");
                    } else {
                        if ($dAz < 113) {
                            $dOr = t("E");
                        } else {
                            if ($dAz < 158) {
                                $dOr = t("SE");
                            } else {
                                if ($dAz < 203) {
                                    $dOr = t("S");
                                } else {
                                    if ($dAz < 248) {
                                        $dOr = t("SW");
                                    } else {
                                        if ($dAz < 293) {
                                            $dOr = t("W");
                                        } else {
                                            if ($dAz < 338) {
                                                $dOr = t("NW");
                                            } else {
                                                $dOr = t("N");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                $gDist = 'n/a';
            }
            if ($loc1->nid != $loc2->nid) {
                $cr = db_fetch_object(db_query("SELECT count(*) count FROM {guifi_radios} r WHERE id=%d", $loc2->device_id));
                if ($cr->count > 1) {
                    $dname = $loc2->device_nick . '/' . $loc2->ssid;
                } else {
                    $dname = $loc2->device_nick;
                }
                $linkname = $loc1->id . '-' . '<a href=' . base_path() . 'node/' . $loc2->nid . '>' . $loc2->nick . '</a> (<a href=' . base_path() . 'guifi/device/' . $loc2->device_id . '>' . $dname . '</a>)';
            } else {
                $linkname = $loc1->id . '-' . '<a href=' . base_path() . 'guifi/device/' . $loc1->device_id . '>' . $loc1->device_nick . '</a>/<a href=' . base_path() . 'guifi/device/' . $loc2->device_id . '>' . $loc2->device_nick . '</a>';
            }
            $status_url = guifi_cnml_availability(array('device' => $loc2->device_id, 'format' => 'short'));
            if ($devant != $devact) {
                $devant = $devact;
                $rows[] = array(array('data' => '<b><a href=' . base_path() . 'guifi/device/' . $loc1->device_id . '>' . $devact . '</a></b>', 'colspan' => 5));
            }
            $rows[] = array($linkname, $loc1->ip . '/' . $loc2->ip, array('data' => t($loc1->flag) . $status_url, 'class' => $loc1->flag), array('data' => $gDist, 'class' => 'number'), $dAz . '-' . $dOr);
        }
        // whhile loc2
    }
    // while loc1
    if (count($rows)) {
        $output .= theme('table', $header, $rows, array('class' => 'device-data'));
        if ($total) {
            $output .= t('Total:') . '&nbsp;' . $total . '&nbsp;' . t('kms.');
        }
    } else {
        if ($ltype == '%') {
            $output .= '<p align="right">' . t('No links defined') . '</p>';
        } else {
            return;
        }
    }
    //      $output .= '<p align="right">'.
    //        t('No %type links defined',
    //          array('%type' => $ltype)).
    //        '</p>';
    return theme('box', $titlebox, $output);
}
Example #6
0
/**
 *
 * @param GuifiAPI $gapi GuifiAPI object
 *
 * @param mixed[] $parameters
 *
 * @return
 */
function guifi_api_radio_nearest($gapi, $parameters)
{
    if (!guifi_api_check_fields($gapi, array('node_id'), $parameters)) {
        return FALSE;
    }
    $node = node_load($parameters['node_id']);
    if (!$node->id) {
        $gapi->addError(500, "node not found: {$parameters['node_id']}");
        return FALSE;
    }
    if ($node->type != 'guifi_node') {
        $gapi->addError(500, "zone_id = {$node->id} is not a node");
        return FALSE;
    }
    if (empty($parameters['dmax'])) {
        $parameters['dmax'] = 15;
    }
    if (empty($parameters['dmin'])) {
        $parameters['dmin'] = 0;
    }
    $query = sprintf("\n      SELECT\n        l.lat, l.lon, r.id, r.radiodev_counter, r.nid, z.id zone_id,\n        r.radiodev_counter, r.ssid, r.mode, r.antenna_mode\n      FROM {guifi_radios} r, {guifi_location} l, {guifi_zone} z\n      WHERE l.id <> %d\n        AND r.nid = l.id\n        AND r.mode = 'ap'\n        AND l.zone_id = z.id", $node->id);
    $devdist = array();
    $devarr = array();
    $k = 0;
    $devsq = db_query($query);
    while ($device = db_fetch_object($devsq)) {
        $k++;
        $l = FALSE;
        $oGC = new GeoCalc();
        $distance = round($oGC->EllipsoidDistance($device->lat, $device->lon, $node->lat, $node->lon), 3);
        if ($distance > $parameters['dmax'] or $distance < $parameters['dmin']) {
            continue;
        }
        $l = TRUE;
        if ($l) {
            $devdist[$k] = $distance;
            $devarr[$k] = $device;
            $devarr[$k]->distance = $distance;
        }
    }
    asort($devdist);
    $devices = array();
    foreach ($devdist as $id => $foo) {
        $device = $devarr[$id];
        $devices[] = array('device_id' => $device->id, 'radiodev_counter' => $device->radiodev_counter, 'ssid' => $device->ssid, 'distance' => $device->distance);
        if (count($devices) == 50) {
            break;
        }
    }
    $gapi->addResponseField('radios', $devices);
}
Example #7
0
function guifi_gml_links($zid, $type)
{
    $oGC = new GeoCalc();
    $minx = 180;
    $miny = 90;
    $maxx = -180;
    $maxy = -90;
    $res = db_query("SELECT id,link_type,flag " . "FROM {guifi_links} " . "WHERE link_type != 'cable' " . "GROUP BY 1,2 " . "HAVING count(*) = 2");
    $zchilds = guifi_zone_childs($zid);
    $zchilds[$zid] = 'Top';
    while ($row = db_fetch_object($res)) {
        $resnode = db_query("SELECT n.id, n.zone_id, n.nick,n.lat, n.lon, n.status_flag " . "FROM {guifi_links} l, {guifi_location} n " . "WHERE l.id = %d AND l.nid=n.id", $row->id);
        $nl = array();
        while ($n = db_fetch_object($resnode)) {
            $nl[] = $n;
        }
        if (count($nl) == 2) {
            if (in_array($nl[0]->zone_id, $zchilds) || in_array($nl[1]->zone_id, $zchilds)) {
                $distance = round($oGC->EllipsoidDistance($nl[0]->lat, $nl[0]->lon, $nl[1]->lat, $nl[1]->lon), 3);
                $status = $row->flag;
                if ($type == 'gml') {
                    $output .= '
          <gml:featureMember>
          <dlinks fid="' . $row->id . '">
          <NODE1_ID>' . $nl[0]->id . '</NODE1_ID>
          <NODE1_NAME>' . $nl[0]->nick . '</NODE1_NAME>
          <NODE2_ID>' . $nl[1]->id . '</NODE2_ID>
          <NODE2_NAME>' . $nl[1]->nick . '</NODE2_NAME>
          <KMS>' . $distance . '</KMS>
          <LINK_TYPE>' . $row->link_type . '</LINK_TYPE>
          <STATUS>' . $status . '</STATUS>
          <ogr:geometryProperty><gml:LineString><gml:coordinates>' . $nl[0]->lon . ',' . $nl[0]->lat . ' ' . $nl[1]->lon . ',' . $nl[1]->lat . '</gml:coordinates></gml:LineString></ogr:geometryProperty>
          </dlinks>
          </gml:featureMember>';
                } else {
                    $output .= $row->id . ',' . $nl[0]->id . ',' . $nl[0]->nick . ',' . $nl[1]->id . ',' . $nl[1]->nick . ',' . $distance . ',' . $row->link_type . ',' . $status . ',' . $nl[0]->lon . ',' . $nl[0]->lat . ',' . $nl[1]->lon . ',' . $nl[1]->lat . "\n";
                }
                if ($nl[0]->lon > $maxx) {
                    $maxx = $nl[0]->lon;
                }
                if ($nl[0]->lat > $maxy) {
                    $maxy = $nl[0]->lat;
                }
                if ($nl[0]->lon < $minx) {
                    $minx = $nl[0]->lon;
                }
                if ($nl[0]->lat < $miny) {
                    $miny = $nl[0]->lat;
                }
                if ($nl[1]->lon > $maxx) {
                    $maxx = $nl[1]->lon;
                }
                if ($nl[1]->lat > $maxy) {
                    $maxy = $nl[1]->lat;
                }
                if ($nl[1]->lon < $minx) {
                    $minx = $nl[1]->lon;
                }
                if ($nl[1]->lat < $miny) {
                    $miny = $nl[1]->lat;
                }
            }
        }
    }
    drupal_set_header('Content-Type: application/xml; charset=utf-8');
    if ($type == 'gml') {
        print '<?xml version="1.0" encoding="utf-8" ?>
<ogr:FeatureCollection
     xmlns:xsi="http://www.w3c.org/2001/XMLSchema-instance"
     xsi:schemaLocation=". dlinks.xsd"
     xmlns:ogr="http://ogr.maptools.org/"
     xmlns:gml="http://www.opengis.net/gml">
  <gml:boundedBy>
    <gml:Box>
<gml:coord><gml:X>' . $minx . '</gml:X><gml:Y>' . $miny . '</gml:Y></gml:coord>
<gml:coord><gml:X>' . $maxx . '</gml:X><gml:Y>' . $maxy . '</gml:Y></gml:coord>
   </gml:Box>
</gml:boundedBy>';
    }
    print $output;
    if ($type == 'gml') {
        print '</ogr:FeatureCollection>';
    }
}
function sortResellersByDistance($zip, $resellers)
{
    global $debug;
    if (empty($zip) || !isset($zip)) {
        if ($debug) {
            echo "<br />no zip code provided";
        }
        return false;
    }
    if (empty($resellers)) {
        if ($debug) {
            echo "<br />no resellers were provided";
        }
        return false;
    }
    $rSorted = array();
    if ($debug) {
        echo "Init sorting resellers by distance: <br />calculating distances...<br />";
        var_dump($resellers);
        echo "<br />";
    }
    // process through all indexes of the $resellers array
    foreach ($resellers as $reseller) {
        //calculate the distance between the home zip and this resellers zip
        $userZiplat = getZipsLat($zip);
        $userZipLong = getZipsLong($zip);
        $resellersLat = getResellerLat($reseller);
        $resellersLong = getResellerLong($reseller);
        $oGC = new GeoCalc();
        $distance = $oGC->EllipsoidDistance($userZiplat, $userZipLong, $resellersLat, $resellersLong);
        //add that distance to the array
        $rSorted[$reseller] = $distance;
    }
    if ($debug) {
        echo "new array: <br />";
        print_r($rSorted);
        echo "<br />";
    }
    //sort the resellers by distance and return the sorted array
    asort($rSorted);
    //keep key index references (where we're storing the reseller id records from the resellers table)
    if ($debug) {
        echo "<br />sorted list: <br />";
        print_r($rSorted);
        echo "<br />";
    }
    $resellers = array();
    //reset the resellers array
    foreach ($rSorted as $r => $distance) {
        $resellers[] = $r;
    }
    if ($debug) {
        echo "<br />resellers array before being returned: <br/>";
        print_r($resellers);
        echo "<br />";
    }
    return $resellers;
}
function guifi_traceroute_dataexport($route, $nRoute, &$linkslist, &$nodeslist)
{
    $oGC = new GeoCalc();
    $tDist = 0;
    $nLink = 0;
    $nReg = 0;
    $output = '';
    foreach ($route as $did => $hop) {
        if (isset($hop['to'])) {
            $linkslist[$nReg]['todevicename'] = guifi_get_devicename($did, 'nick');
            $linkslist[$nReg]['todevicelink'] = 'guifi/device/' . $did;
            $linkslist[$nReg]['tonode'] = $hop['to'][0];
            $ip = db_fetch_object(db_query('SELECT ipv4, netmask FROM {guifi_ipv4} WHERE id=%d AND interface_id=%d', $hop['to'][2], $hop['to'][1]));
            $linkslist[$nReg]['toipv4'] = $ip->ipv4 . '/' . guifi_ipcalc_get_maskbits($ip->netmask);
            if (!isset($nodeslist[$hop['to'][0]])) {
                $nodeslist[$hop["to"][0]] = guifi_get_location($hop["to"][0]);
                $nodeslist[$hop["to"][0]][nodename] = guifi_get_nodename($hop['to'][0]);
                $nodeslist[$hop["to"][0]][nodelink] = $hop['to'][0];
            }
        }
        if (isset($hop['from'])) {
            $nLink++;
            $nReg = $nRoute * 100 + $nLink;
            $linkslist[$nReg]['route'] = $nRoute;
            $linkslist[$nReg]['nlink'] = $nLink;
            $linkslist[$nReg]['idlink'] = $hop['from'][0];
            $linkslist[$nReg]['fromdevicename'] = guifi_get_devicename($did, 'nick');
            $linkslist[$nReg]['fromdevicelink'] = 'guifi/device/' . $did;
            $linkslist[$nReg]['fromnode'] = $hop['from'][5];
            $ip = db_fetch_object(db_query('SELECT ipv4, netmask FROM {guifi_ipv4} WHERE id=%d AND interface_id=%d', $hop['from'][4], $hop['from'][3]));
            $linkslist[$nReg]['fromipv4'] = $ip->ipv4 . '/' . guifi_ipcalc_get_maskbits($ip->netmask);
            $linkslist[$nReg]['type'] = $hop['from'][1];
            $linkslist[$nReg]['status'] = $hop['from'][2];
            if (!isset($nodeslist[$hop['from'][5]])) {
                $nodeslist[$hop["from"][5]] = guifi_get_location($hop["from"][5]);
                $nodeslist[$hop["from"][5]][nodename] = guifi_get_nodename($hop['from'][5]);
                $nodeslist[$hop["from"][5]][nodelink] = $hop['from'][5];
            }
        }
        // if not same location, give the distance
        if ($hop['from'][1] != 'cable') {
            $qry = db_query('SELECT n.id nid, lat, lon
         FROM {guifi_location} n, {guifi_links} l
         WHERE l.id=%d
           AND l.nid=n.id', $hop['from'][0]);
            $loc1 = db_fetch_object($qry);
            $loc2 = db_fetch_object($qry);
            $gDist = round($oGC->EllipsoidDistance($loc1->lat, $loc1->lon, $loc2->lat, $loc2->lon), 3);
            if ($gDist) {
                $linkslist[$nReg]['distance'] = $gDist;
            }
        }
    }
    return $output;
}
Example #10
0
/**
 * Get candidate zones to be inside a given point
 * @param $lat Latitude of the point
 * @param $lon Longitude of the point
 * @param $max_distance Maximum distance to be considered a candidate
 * @param $zones Zones to be looked after
 * @return mixed[] Array of zone which can contain a point and are small enough
 */
function guifi_zone_get_nearest_candidates($lat, $lon, $max_distance = 15, $zones = NULL)
{
    if ($zones == NULL) {
        $zones = guifi_zone_get_containing($lat, $lon);
    }
    if (!$zones) {
        return FALSE;
    }
    $candidates = array();
    foreach ($zones as $zone) {
        $oGC = new GeoCalc();
        $d1 = $oGC->EllipsoidDistance($lat, $lon, $zone['max_lat'], $zone['max_lon']);
        $d2 = $oGC->EllipsoidDistance($lat, $lon, $zone['min_lat'], $zone['min_lon']);
        $zone['d'] = sqrt($d1 * $d1 + $d2 * $d2);
        if ($zone['d'] < $max_distance) {
            $candidates[] = $zone;
        }
    }
    return $candidates;
}