function guifi_device_get_service($id, $type, $path = FALSE)
{
    if (is_numeric($id)) {
        $z = guifi_device_load($id);
    } else {
        $z = $id;
    }
    $ret = NULL;
    if (!empty($z->{$type})) {
        $ret = $z->{$type};
    } else {
        $ret = guifi_node_get_service($z->nid, $type);
    }
    if ($path) {
        if ($ret) {
            $ret = 'node/' . $ret;
        }
    }
    return $ret;
}
function guifi_interfaces_add_cable_public_link_submit(&$form, &$form_state)
{
    $values = $form_state['clicked_button']['#parents'];
    $iid = $values[1];
    $ipv4_id = $values[3];
    $to_did = $form_state['values']['interfaces'][$iid]['ipv4'][$ipv4_id]['to_did'];
    $rdevice = guifi_device_load($to_did);
    guifi_log(GUIFILOG_TRACE, sprintf('function guifi_interfaces_add_cable_public_link_submit(%d)', $iid), $form_state['clicked_button']['#parents']);
    $ips_allocated = guifi_ipcalc_get_ips('0.0.0.0', '0.0.0.0', $form_state['values'], 1);
    // get next available ip address
    $base_ip = $form_state['values']['interfaces'][$iid]['ipv4'][$ipv4_id];
    $item = _ipcalc($base_ip['ipv4'], $base_ip['netmask']);
    $ip = guifi_ipcalc_find_ip($item['netid'], $base_ip['netmask'], $ips_allocated);
    // no IP was given, so raise a message and don't create the link'
    if (empty($ip)) {
        drupal_set_message(t('Unable to assign a free ip, link not created, ' . 'contact the administrator.'));
        return;
    }
    $newlk['new'] = TRUE;
    $newlk['interface'] = array();
    $newlk['link_type'] = 'cable';
    $newlk['flag'] = 'Planned';
    $newlk['nid'] = $form_state['values']['nid'];
    $newlk['device_id'] = $to_did;
    if ($rdevice['type'] == 'radio') {
        $newlk['routing'] = 'BGP';
    } else {
        $newlk['routing'] = 'Gateway';
    }
    $newlk['interface']['new'] = TRUE;
    $newlk['interface']['device_id'] = $to_did;
    $free = guifi_get_free_interfaces($to_did, $rdevice);
    $newlk['interface']['interface_type'] = array_shift($free);
    $newlk['interface']['ipv4']['new'] = TRUE;
    $newlk['interface']['ipv4']['ipv4_type'] = 1;
    $newlk['interface']['ipv4']['ipv4'] = $ip;
    $newlk['interface']['ipv4']['netmask'] = $base_ip['netmask'];
    $form_state['values']['interfaces'][$iid]['ipv4'][$ipv4_id]['links'][] = $newlk;
    $form_state['values']['interfaces'][$iid]['unfold'] = TRUE;
    //  print_r($form_state['values']);
    $form_state['rebuild'] = TRUE;
    return TRUE;
}
function theme_guifi_node_devices_list($node, $links = FALSE)
{
    $id = $node->id;
    $rows = array();
    $header = array('<h2>' . t('device') . '</h2>', t('type'), t('ip'), t('status'), array('data' => t('last available'), 'style' => 'text-align: right;'), t('unsolclic'));
    // Form for adding a new device
    $form = drupal_get_form('guifi_device_create_form', $node);
    $query = db_query("SELECT d.id FROM {guifi_devices} d WHERE nid=%d", $id);
    while ($d = db_fetch_object($query)) {
        $device = guifi_device_load($d->id);
        // Edit and delete buttons
        if (guifi_device_access('update', $device['id'])) {
            $edit_device = l(guifi_img_icon('edit.png'), 'guifi/device/' . $device['id'] . '/edit', array('html' => TRUE, 'attributes' => array('target' => '_blank', 'title' => t('edit device'))));
            $delete_device = l(guifi_img_icon('drop.png'), 'guifi/device/' . $device['id'] . '/delete', array('html' => TRUE, 'attributes' => array('target' => '_blank', 'title' => t('delete device'))));
        } else {
            $edit_device = '';
            $delete_device = '';
        }
        // Traceroute button
        if (user_access('create guifi nodes')) {
            $traceroute = l(guifi_img_icon('discover-routes.png'), 'guifi/menu/ip/traceroute/' . $device['id'], array('html' => TRUE, 'attributes' => array('target' => '_blank', 'title' => t('trace routes, discover services from this device'))));
        } else {
            $traceroute = '';
        }
        // Firmware text which links to unsolclic feature
        if ($device->variable['firmware'] != "n/d") {
            $unsolclic = l($device[variable]['firmware'], 'guifi/device/' . $device['id'] . '/view/unsolclic', array('attributes' => array('title' => t("Get radio configuration with singleclick"))));
        }
        // Get IP assigned to the device
        $ip = guifi_main_ip($device[id]);
        // Availability image
        $status_url = guifi_cnml_availability(array('device' => $device['id'], 'format' => 'short'));
        // Device main attributes
        if (!empty($device['manufacturer'])) {
            $mDescr = $device['manufacturer'] . '-' . $device['model'];
        } else {
            $mDescr = '';
        }
        $uCreated = db_fetch_object(db_query('SELECT u.name FROM {users} u WHERE u.uid = %d', $device[user_created]));
        $deviceAttr = $device[id] . ' ' . $mDescr . '
         ' . t('created by') . ': ' . $uCreated->name . ' ' . t('at') . ' ' . format_date($device[timestamp_created], 'small');
        if (!empty($device[timestamp_changed])) {
            $uChanged = db_fetch_object(db_query('SELECT u.name FROM {users} u WHERE u.uid = %d', $device[user_changed]));
            $deviceAttr .= '
           ' . t('updated by') . ': ' . $uChanged->name . ' ' . t('at') . ' ' . format_date($device[timestamp_changed], 'small');
        }
        // Groups all this data in an array for the theme() function
        $rows[] = array(l($device[nick], 'guifi/device/' . $device[id], array('attributes' => array('title' => $deviceAttr))), $device[type], array('data' => $ip[ipv4] . '/' . $ip[maskbits], 'align' => 'left'), empty($ip[ipv4]) ? '&nbsp;' : array('data' => t($device[flag]), 'class' => $device['flag']), empty($ip[ipv4]) ? '&nbsp;' : array('data' => $status_url, 'class' => $device['flag']), $unsolclic, $edit_device, $delete_device, empty($ip[ipv4]) ? '&nbsp;' : $traceroute);
    }
    // Creates the table with devices if any, otherwise just outputs the node has not devices
    if (count($rows)) {
        $output = '<h4>' . t('devices') . '</h4>' . theme('table', $header, $rows, array('class' => 'device-data')) . $form;
    } else {
        $output = theme('box', t('This node does not have any device'), $form);
    }
    // Again, it creates a table with the links, if they exist
    if ($links) {
        $node = node_load(array('nid' => $node->id));
        drupal_set_title(t('devices @ %node', array('%node' => $node->title)));
        drupal_set_breadcrumb(guifi_node_ariadna($node));
        $output .= theme_links(module_invoke_all('link', 'node', $node, FALSE));
        print theme('page', $output, FALSE);
        return;
    }
    return $output;
}
function guifi_api_service_update($gapi, $parameters)
{
    global $user;
    if (!guifi_api_check_fields($gapi, array('service_id'), $parameters)) {
        return FALSE;
    }
    $service = guifi_service_load($parameters['service_id']);
    $node = node_load($service->id);
    if (isset($parameters['name'])) {
        /* compte amb XSS */
        $node->title = $parameters['name'];
    }
    if (isset($parameters['status'])) {
        $types = db_fetch_object(db_query("SELECT count(*) as cnt FROM {guifi_types} WHERE type='status' AND text='%s'", $parameters['status']));
        if ($types->cnt == 0) {
            //This status_flag is not defined in guifi_db.
            $gapi->addError(403, "This status is not defined.");
            return FALSE;
        }
        $service->status_flag = $parameters['status'];
        $node->status_flag = $service->status_flag;
    }
    if (isset($parameters['server_id'])) {
        $new_device = guifi_device_load($parameters['server_id']);
        if (!$new_device) {
            $gapi->addError(403, "Server destination does not exist.");
            return FALSE;
        }
        // Canviar la zona --->
        $zone = _guifi_api_get_zone($new_device);
        if (is_array($zone)) {
            $gapi->addError($zone['error_code'], $zone['error_message']);
            return FALSE;
        }
        $service->zone_id = $zone;
        $node->zone_id = $service->zone_id;
        $service->device_id = $parameters['server_id'];
        $node->device_id = $service->device_id;
    }
    node_save($node);
    $nservice = _guifi_db_sql('guifi_services', array('id' => $service->id), (array) $node);
    $gapi->addResponseField('service', $nservice);
    $gapi->addResponseField('node', $node);
    return TRUE;
}
 function _guifi_user_queue_devices($u)
 {
     $query = db_query('SELECT d.id ' . 'FROM {guifi_devices} d ' . 'WHERE d.nid=%d' . '  AND type="radio"', $u['nid']);
     $rows = array();
     while ($d = db_fetch_array($query)) {
         $d = guifi_device_load($d['id']);
         $d['uid'] = $u['id'];
         if (guifi_device_access('update', $d['id'])) {
             $edit_device_icon = l(guifi_img_icon('edit.png'), 'guifi/device/' . $d['id'] . '/edit', array('html' => TRUE, 'attributes' => array('target' => '_blank'))) . l(guifi_img_icon('drop.png'), 'guifi/device/' . $d['id'] . '/delete', array('html' => TRUE, 'attributes' => array('target' => '_blank')));
         } else {
             $edit_device_icon = '';
         }
         if (user_access('administer guifi users')) {
             $edit_ok_icon = drupal_get_form('_guifi_user_queue_device_form', $d);
         } else {
             $edit_ok_icon = $d['flag'];
             if (count($d['radios']) == 1 and $d['radios'][0]['mode'] == 'client') {
                 $edit_ok_icon .= ' ' . $d['radios'][0]['mac'];
             }
         }
         $ip = guifi_main_ip($d['id']);
         $status_url = guifi_cnml_availability(array('device' => $d['id'], 'format' => 'short'));
         $rows[] = array($edit_device_icon . l($d['nick'], 'guifi/device/' . $d['id'], array('attributes' => array('target' => '_blank'))), array('data' => l($ip['ipv4'] . '/' . $ip['maskbits'], guifi_device_admin_url($d, $ip['ipv4']), array('attributes' => array('title' => t('Connect to the device on a new window'), 'target' => '_blank'))), 'align' => 'right'), array('data' => $edit_ok_icon, 'class' => $d['flag']), array('data' => $status_url, 'class' => $d['flag']));
     }
     return $rows;
 }
function theme_guifi_services_list($node, $service = '%')
{
    if (is_numeric($node)) {
        $typestr = t('by device');
    } else {
        $node = node_load(array('nid' => $node->id));
        if ($node->type == 'guifi_node') {
            $typestr = t('by node');
        } else {
            $typestr = t('by zone');
        }
    }
    $rows = guifi_list_services_query($node, $typestr);
    $rows ? $box .= theme('table', array(t('service'), t('zone'), t('device'), t('status'), t('disponibilitat')), array_merge($rows), array('width' => '100%')) : ($box .= t('There are no services defined at the database'));
    $output = theme('box', t('Services of %node (%by)', array('%node' => $node->title, '%by' => $typestr)), $box);
    switch ($typestr) {
        case t('by node'):
            drupal_set_title(t('services @ %node', array('%node' => $node->title)));
            drupal_set_breadcrumb(guifi_node_ariadna($node, 'node/%d/view/services'));
            $output .= theme_links(module_invoke_all('link', 'node', $node, FALSE));
            break;
        case t('by zone'):
            drupal_set_breadcrumb(guifi_zone_ariadna($node->id, 'node/%d/view/services'));
            $output .= theme_links(module_invoke_all('link', 'node', $node, FALSE));
            break;
        case t('by device'):
            $device = guifi_device_load($node);
            drupal_set_title(t('View device %dname', array('%dname' => $device['nick'], '%nid' => $device['nid'])));
            $node = node_load(array('nid' => $device['nid']));
            drupal_set_breadcrumb(guifi_node_ariadna($node));
            $output .= theme_links(module_invoke_all('link', 'node', $node, FALSE));
            break;
    }
    $output .= theme_pager(NULL, variable_get("guifi_pagelimit", 50));
    print theme('page', $output, FALSE);
    return;
}
 function _guifi_zone_availability_devices($nid)
 {
     $oneyearfromnow = time() - '31622400';
     $qry = db_query('SELECT d.id did, d.nick dnick, d.flag dflag, d.timestamp_changed changed ' . 'FROM {guifi_devices} d ' . 'WHERE d.type = "radio" ' . '  AND d.nid=%d ' . 'ORDER BY d.nick', $nid);
     $rows = array();
     while ($d = db_fetch_array($qry)) {
         $dev = guifi_device_load($d['did']);
         if (guifi_device_access('update', $dev)) {
             $edit = l(guifi_img_icon('edit.png'), 'guifi/device/' . $d['did'] . '/edit', array('html' => TRUE, 'attributes' => array('title' => t('edit device'), 'target' => '_blank'))) . l(guifi_img_icon('drop.png'), 'guifi/device/' . $d['did'] . '/delete', array('html' => TRUE, 'attributes' => array('title' => t('delete device'), 'target' => '_blank')));
         } else {
             $edit = NULL;
         }
         $ip = guifi_main_ip($d['did']);
         $status_url = guifi_cnml_availability(array('device' => $d['did'], 'format' => 'long'));
         if (!empty($d['changed'])) {
             if ($d['changed'] < $oneyearfromnow) {
                 $dchanged = array('data' => '<b><font color="#AA0000">' . format_date($d['changed'], 'custom', t('d/m/Y')) . '</font></b>');
             } else {
                 $dchanged = array('data' => format_date($d['changed'], 'custom', t('d/m/Y')));
             }
         } else {
             $dchanged = array('data' => t('never changed'));
         }
         $rows[] = array(array('data' => $edit . l($d['dnick'], 'guifi/device/' . $d['did'])), array('data' => l($ip['ipv4'] . '/' . $ip['maskbits'], guifi_device_admin_url($d['did'], $ip['ipv4']), array('attributes' => array('title' => t('Connect to the device on a new window'), 'target' => '_blank'))), 'align' => 'right'), array('data' => $d['dflag'] . $status_url, 'class' => $d['dflag']), $dchanged);
     }
     guifi_log(GUIFILOG_TRACE, 'function guifi_zone_availability_device()', $rows);
     return $rows;
 }