r4163 commitUpdateObject(): enforce NULL value for "label"
[racktables] / inc / database.php
1 <?php
2 /*
3 *
4 * This file is a library of database access functions for RackTables.
5 *
6 */
7
8 $SQLSchema = array
9 (
10 'object' => array
11 (
12 'table' => 'RackObject',
13 'columns' => array
14 (
15 'id' => 'id',
16 'name' => 'name',
17 'label' => 'label',
18 'barcode' => 'barcode',
19 'asset_no' => 'asset_no',
20 'objtype_id' => 'objtype_id',
21 'rack_id' => '(select rack_id from RackSpace where object_id = id order by rack_id asc limit 1)',
22 'Rack_name' => '(select name from Rack where id = rack_id)',
23 'row_id' => '(select row_id from Rack where id = rack_id)',
24 'Row_name' => '(select name from RackRow where id = row_id)',
25 'has_problems' => 'has_problems',
26 'comment' => 'comment',
27 'nports' => '(SELECT COUNT(*) FROM Port WHERE object_id = RackObject.id)',
28 'runs8021Q' => '(SELECT 1 FROM VLANSwitch WHERE object_id = id LIMIT 1)',
29 ),
30 'keycolumn' => 'id',
31 'ordcolumns' => array ('RackObject.name'),
32 ),
33 'user' => array
34 (
35 'table' => 'UserAccount',
36 'columns' => array
37 (
38 'user_id' => 'user_id',
39 'user_name' => 'user_name',
40 'user_password_hash' => 'user_password_hash',
41 'user_realname' => 'user_realname',
42 ),
43 'keycolumn' => 'user_id',
44 'ordcolumns' => array ('UserAccount.user_name'),
45 ),
46 'ipv4net' => array
47 (
48 'table' => 'IPv4Network',
49 'columns' => array
50 (
51 'id' => 'id',
52 'ip' => 'INET_NTOA(IPv4Network.ip)',
53 'mask' => 'mask',
54 'name' => 'name',
55 'comment' => 'comment',
56 'parent_id' => '(SELECT id FROM IPv4Network AS subt WHERE IPv4Network.ip & (4294967295 >> (32 - subt.mask)) << (32 - subt.mask) = subt.ip and subt.mask < IPv4Network.mask ORDER BY subt.mask DESC limit 1)',
57 'vlanc' => '(SELECT COUNT(*) FROM VLANIPv4 WHERE ipv4net_id = id)',
58 ),
59 'keycolumn' => 'id',
60 'ordcolumns' => array ('IPv4Network.ip', 'IPv4Network.mask'),
61 ),
62 'ipv6net' => array
63 (
64 'table' => 'IPv6Network',
65 'columns' => array
66 (
67 'id' => 'id',
68 'ip_bin' => 'ip',
69 'mask' => 'mask',
70 'name' => 'name',
71 'comment' => 'comment',
72 'parent_id' => '(SELECT id FROM IPv6Network AS subt WHERE IPv6Network.ip >= subt.ip AND IPv6Network.last_ip <= subt.last_ip AND IPv6Network.mask > subt.mask ORDER BY subt.mask DESC limit 1)',
73 'vlanc' => '(SELECT COUNT(*) FROM VLANIPv6 WHERE ipv6net_id = id)',
74 ),
75 'keycolumn' => 'id',
76 'ordcolumns' => array ('IPv6Network.ip', 'IPv6Network.mask'),
77 ),
78 'file' => array
79 (
80 'table' => 'File',
81 'columns' => array
82 (
83 'id' => 'id',
84 'name' => 'name',
85 'type' => 'type',
86 'size' => 'size',
87 'ctime' => 'ctime',
88 'mtime' => 'mtime',
89 'atime' => 'atime',
90 'comment' => 'comment',
91 ),
92 'keycolumn' => 'id',
93 'ordcolumns' => array ('File.name'),
94 ),
95 'ipv4vs' => array
96 (
97 'table' => 'IPv4VS',
98 'columns' => array
99 (
100 'id' => 'id',
101 'vip' => 'INET_NTOA(vip)',
102 'vport' => 'vport',
103 'proto' => 'proto',
104 'name' => 'name',
105 'vsconfig' => 'vsconfig',
106 'rsconfig' => 'rsconfig',
107 'poolcount' => '(select count(vs_id) from IPv4LB where vs_id = id)',
108 'dname' => 'CONCAT_WS("/", CONCAT_WS(":", INET_NTOA(vip), vport), proto)',
109 ),
110 'keycolumn' => 'id',
111 'ordcolumns' => array ('IPv4VS.vip', 'IPv4VS.proto', 'IPv4VS.vport'),
112 ),
113 'ipv4rspool' => array
114 (
115 'table' => 'IPv4RSPool',
116 'columns' => array
117 (
118 'id' => 'id',
119 'name' => 'name',
120 'refcnt' => '(select count(rspool_id) from IPv4LB where rspool_id = id)',
121 'rscount' => '(select count(rspool_id) from IPv4RS where rspool_id = IPv4RSPool.id)',
122 'vsconfig' => 'vsconfig',
123 'rsconfig' => 'rsconfig',
124 ),
125 'keycolumn' => 'id',
126 'ordcolumns' => array ('IPv4RSPool.name', 'IPv4RSPool.id'),
127 ),
128 'rack' => array
129 (
130 'table' => 'Rack',
131 'columns' => array
132 (
133 'id' => 'id',
134 'name' => 'name',
135 'height' => 'height',
136 'comment' => 'comment',
137 'row_id' => 'row_id',
138 'row_name' => '(select name from RackRow where RackRow.id = row_id)',
139 ),
140 'keycolumn' => 'id',
141 'ordcolumns' => array ('row_name', 'Rack.name'),
142 'pidcolumn' => 'row_id',
143 ),
144 );
145
146 $searchfunc = array
147 (
148 'object' => array
149 (
150 'by_sticker' => 'getStickerSearchResults',
151 'by_port' => 'getPortSearchResults',
152 'by_attr' => 'getObjectAttrsSearchResults',
153 'by_iface' => 'getObjectIfacesSearchResults',
154 'by_nat' => 'getObjectNATSearchResults',
155 ),
156 );
157
158 $tablemap_8021q = array
159 (
160 'desired' => array
161 (
162 'pvm' => 'PortVLANMode',
163 'pav' => 'PortAllowedVLAN',
164 'pnv' => 'PortNativeVLAN',
165 ),
166 'cached' => array
167 (
168 'pvm' => 'CachedPVM',
169 'pav' => 'CachedPAV',
170 'pnv' => 'CachedPNV',
171 ),
172 );
173
174 // VST roles
175 $port_role_options = array
176 (
177 'none' => 'none',
178 'access' => 'user: access only',
179 'trunk' => 'user: trunk only',
180 'anymode' => 'user: any mode',
181 'uplink' => 'system: uplink trunk',
182 'downlink' => 'system: downlink trunk',
183 );
184
185 $object_attribute_cache = array();
186
187 function escapeString ($value, $do_db_escape = FALSE)
188 {
189 $ret = htmlspecialchars ($value, ENT_QUOTES, 'UTF-8');
190 if ($do_db_escape)
191 {
192 global $dbxlink;
193 $ret = substr ($dbxlink->quote ($ret), 1, -1);
194 }
195 return $ret;
196 }
197
198 // Return detailed information about one rack row.
199 function getRackRowInfo ($rackrow_id)
200 {
201 $query =
202 "select RackRow.id as id, RackRow.name as name, count(Rack.id) as count, " .
203 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
204 "from RackRow left join Rack on Rack.row_id = RackRow.id " .
205 "where RackRow.id = ? " .
206 "group by RackRow.id";
207 $result = usePreparedSelectBlade ($query, array ($rackrow_id));
208 if ($row = $result->fetch (PDO::FETCH_ASSOC))
209 return $row;
210 else
211 throw new EntityNotFoundException ('rackrow', $rackrow_id);
212 }
213
214 function getRackRows ()
215 {
216 $result = usePreparedSelectBlade ('SELECT id, name FROM RackRow ORDER BY name');
217 $rows = array();
218 while ($row = $result->fetch (PDO::FETCH_ASSOC))
219 $rows[$row['id']] = $row['name'];
220 return $rows;
221 }
222
223 // Return a simple object list w/o related information, so that the returned value
224 // can be directly used by printSelect(). An optional argument is the name of config
225 // option with constraint in RackCode.
226 function getNarrowObjectList ($varname = '')
227 {
228 $wideList = listCells ('object');
229 if (strlen ($varname) and strlen (getConfigVar ($varname)))
230 {
231 global $parseCache;
232 if (!isset ($parseCache[$varname]))
233 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
234 if ($parseCache[$varname]['result'] != 'ACK')
235 return array();
236 $wideList = filterCellList ($wideList, $parseCache[$varname]['load']);
237 }
238 $ret = array();
239 foreach ($wideList as $cell)
240 $ret[$cell['id']] = $cell['dname'];
241 return $ret;
242 }
243
244 // For a given realm return a list of entity records, each with
245 // enough information for judgeCell() to execute.
246 function listCells ($realm, $parent_id = 0)
247 {
248 if (!$parent_id)
249 {
250 global $entityCache;
251 if (isset ($entityCache['complete'][$realm]))
252 return $entityCache['complete'][$realm];
253 }
254 global $SQLSchema;
255 if (!isset ($SQLSchema[$realm]))
256 throw new InvalidArgException ('realm', $realm);
257 $SQLinfo = $SQLSchema[$realm];
258 $qparams = array ();
259 $query = 'SELECT ';
260 foreach ($SQLinfo['columns'] as $alias => $expression)
261 // Automatically prepend table name to each single column, but leave all others intact.
262 $query .= ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}") . ', ';
263 $query = trim($query, ', ');
264 $query .= " FROM ${SQLinfo['table']}";
265 if (isset ($SQLinfo['pidcolumn']) and $parent_id)
266 {
267 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['pidcolumn']} = ?";
268 $qparams[] = $parent_id;
269 }
270 $query .= " ORDER BY ";
271 foreach ($SQLinfo['ordcolumns'] as $oc)
272 $query .= "${oc}, ";
273 $query = trim($query, ', ');
274 $result = usePreparedSelectBlade ($query, $qparams);
275 $ret = array();
276 // Index returned result by the value of key column.
277 while ($row = $result->fetch (PDO::FETCH_ASSOC))
278 {
279 $entity_id = $row[$SQLinfo['keycolumn']];
280 $ret[$entity_id] = array ('realm' => $realm);
281 $ret[$entity_id]['etags'] = array();
282 foreach (array_keys ($SQLinfo['columns']) as $alias)
283 $ret[$entity_id][$alias] = $row[$alias];
284 }
285 unset($result);
286
287 // select tags and link them to previosly fetched entities
288 $query = 'SELECT entity_id, tag_id FROM TagStorage WHERE entity_realm = ?';
289 $result = usePreparedSelectBlade ($query, array($realm));
290 global $taglist;
291 while ($row = $result->fetch (PDO::FETCH_ASSOC))
292 {
293 if (array_key_exists($row['entity_id'], $ret))
294 $ret[$row['entity_id']]['etags'][] = array
295 (
296 'id' => $row['tag_id'],
297 'tag' => $taglist[$row['tag_id']]['tag'],
298 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
299 );
300 }
301 unset($result);
302 // Add necessary finish to the list before returning it. Maintain caches.
303 if (!$parent_id)
304 unset ($entityCache['partial'][$realm]);
305 if ($realm == 'object') // cache all attributes of all objects to speed up autotags calculation
306 cacheAllObjectsAttributes();
307 foreach (array_keys ($ret) as $entity_id)
308 {
309 $ret[$entity_id]['etags'] = getExplicitTagsOnly ($ret[$entity_id]['etags']);
310 $ret[$entity_id]['itags'] = getImplicitTags ($ret[$entity_id]['etags']);
311 $ret[$entity_id]['atags'] = generateEntityAutoTags ($ret[$entity_id]);
312 switch ($realm)
313 {
314 case 'object':
315 setDisplayedName ($ret[$entity_id]);
316 break;
317 case 'ipv4net':
318 $ret[$entity_id]['ip_bin'] = ip2long ($ret[$entity_id]['ip']);
319 $ret[$entity_id]['mask_bin'] = binMaskFromDec ($ret[$entity_id]['mask']);
320 $ret[$entity_id]['mask_bin_inv'] = binInvMaskFromDec ($ret[$entity_id]['mask']);
321 $ret[$entity_id]['db_first'] = sprintf ('%u', 0x00000000 + $ret[$entity_id]['ip_bin'] & $ret[$entity_id]['mask_bin']);
322 $ret[$entity_id]['db_last'] = sprintf ('%u', 0x00000000 + $ret[$entity_id]['ip_bin'] | ($ret[$entity_id]['mask_bin_inv']));
323 break;
324 case 'ipv6net':
325 $ret[$entity_id]['ip_bin'] = new IPv6Address ($ret[$entity_id]['ip_bin']);
326 $ret[$entity_id]['ip'] = $ret[$entity_id]['ip_bin']->format();
327 $ret[$entity_id]['db_first'] = $ret[$entity_id]['ip_bin']->get_first_subnet_address($ret[$entity_id]['mask']);
328 $ret[$entity_id]['db_last'] = $ret[$entity_id]['ip_bin']->get_last_subnet_address($ret[$entity_id]['mask']);
329 break;
330 default:
331 break;
332 }
333 if (!$parent_id)
334 $entityCache['complete'][$realm][$entity_id] = $ret[$entity_id];
335 else
336 $entityCache['partial'][$realm][$entity_id] = $ret[$entity_id];
337 }
338 return $ret;
339 }
340
341 // Very much like listCells(), but return only one record requested (or NULL,
342 // if it does not exist).
343 function spotEntity ($realm, $id)
344 {
345 global $entityCache;
346 if (isset ($entityCache['complete'][$realm]))
347 // Emphasize the absence of record, if listCells() has already been called.
348 if (isset ($entityCache['complete'][$realm][$id]))
349 return $entityCache['complete'][$realm][$id];
350 else
351 throw new EntityNotFoundException ($realm, $id);
352 elseif (isset ($entityCache['partial'][$realm][$id]))
353 return $entityCache['partial'][$realm][$id];
354 global $SQLSchema;
355 if (!isset ($SQLSchema[$realm]))
356 throw new InvalidArgException ('realm', $realm);
357 $SQLinfo = $SQLSchema[$realm];
358 $query = 'SELECT tag_id';
359 foreach ($SQLinfo['columns'] as $alias => $expression)
360 // Automatically prepend table name to each single column, but leave all others intact.
361 $query .= ', ' . ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
362 $query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = ? and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
363 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['keycolumn']} = ?";
364 $query .= " ORDER BY tag_id";
365 $result = usePreparedSelectBlade ($query, array ($realm, $id));
366 $ret = array();
367 global $taglist;
368 while ($row = $result->fetch (PDO::FETCH_ASSOC))
369 if (!isset ($ret['realm']))
370 {
371 $ret = array ('realm' => $realm);
372 foreach (array_keys ($SQLinfo['columns']) as $alias)
373 $ret[$alias] = $row[$alias];
374 $ret['etags'] = array();
375 if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
376 $ret['etags'][] = array
377 (
378 'id' => $row['tag_id'],
379 'tag' => $taglist[$row['tag_id']]['tag'],
380 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
381 );
382 }
383 elseif (isset ($taglist[$row['tag_id']]))
384 $ret['etags'][] = array
385 (
386 'id' => $row['tag_id'],
387 'tag' => $taglist[$row['tag_id']]['tag'],
388 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
389 );
390 unset ($result);
391 if (!isset ($ret['realm'])) // no rows were returned
392 throw new EntityNotFoundException ($realm, $id);
393 $ret['etags'] = getExplicitTagsOnly ($ret['etags']);
394 $ret['itags'] = getImplicitTags ($ret['etags']);
395 $ret['atags'] = generateEntityAutoTags ($ret);
396 switch ($realm)
397 {
398 case 'object':
399 setDisplayedName ($ret);
400 break;
401 case 'ipv4net':
402 $ret['ip_bin'] = ip2long ($ret['ip']);
403 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
404 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
405 $ret['db_first'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']);
406 $ret['db_last'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv']));
407 break;
408 case 'ipv6net':
409 $ret['ip_bin'] = new IPv6Address ($ret['ip_bin']);
410 $ret['ip'] = $ret['ip_bin']->format();
411 $ret['db_first'] = $ret['ip_bin']->get_first_subnet_address($ret['mask']);
412 $ret['db_last'] = $ret['ip_bin']->get_last_subnet_address($ret['mask']);
413 break;
414 default:
415 break;
416 }
417 $entityCache['partial'][$realm][$id] = $ret;
418 return $ret;
419 }
420
421 // This function can be used with array_walk().
422 function amplifyCell (&$record, $dummy = NULL)
423 {
424 switch ($record['realm'])
425 {
426 case 'object':
427 $record['ports'] = getObjectPortsAndLinks ($record['id']);
428 $record['ipv4'] = getObjectIPv4Allocations ($record['id']);
429 $record['ipv6'] = getObjectIPv6Allocations ($record['id']);
430 $record['nat4'] = getNATv4ForObject ($record['id']);
431 $record['ipv4rspools'] = getRSPoolsForObject ($record['id']);
432 $record['files'] = getFilesOfEntity ($record['realm'], $record['id']);
433 break;
434 case 'file':
435 $record['links'] = getFileLinks ($record['id']);
436 break;
437 case 'ipv4rspool':
438 $record['lblist'] = array();
439 $query = "select object_id, vs_id, lb.vsconfig, lb.rsconfig, lb.prio from " .
440 "IPv4LB as lb inner join IPv4VS as vs on lb.vs_id = vs.id " .
441 "where rspool_id = ? order by object_id, vip, vport";
442 $result = usePreparedSelectBlade ($query, array ($record['id']));
443 while ($row = $result->fetch (PDO::FETCH_ASSOC))
444 $record['lblist'][$row['object_id']][$row['vs_id']] = array
445 (
446 'rsconfig' => $row['rsconfig'],
447 'vsconfig' => $row['vsconfig'],
448 'prio' => $row['prio'],
449 );
450 unset ($result);
451 $record['rslist'] = array();
452 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
453 "IPv4RS where rspool_id = ? order by IPv4RS.rsip, rsport";
454 $result = usePreparedSelectBlade ($query, array ($record['id']));
455 while ($row = $result->fetch (PDO::FETCH_ASSOC))
456 $record['rslist'][$row['id']] = array
457 (
458 'inservice' => $row['inservice'],
459 'rsip' => $row['rsip'],
460 'rsport' => $row['rsport'],
461 'rsconfig' => $row['rsconfig'],
462 );
463 unset ($result);
464 break;
465 case 'ipv4vs':
466 // Get the detailed composition of a particular virtual service, namely the list
467 // of all pools, each shown with the list of objects servicing it. VS/RS configs
468 // will be returned as well.
469 $record['rspool'] = array();
470 $query = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
471 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, lb.prio from " .
472 "IPv4RSPool as pool left join IPv4LB as lb on pool.id = lb.rspool_id " .
473 "where vs_id = ? order by pool.name, object_id";
474 $result = usePreparedSelectBlade ($query, array ($record['id']));
475 while ($row = $result->fetch (PDO::FETCH_ASSOC))
476 {
477 if (!isset ($record['rspool'][$row['id']]))
478 $record['rspool'][$row['id']] = array
479 (
480 'name' => $row['name'],
481 'vsconfig' => $row['vsconfig'],
482 'rsconfig' => $row['rsconfig'],
483 'lblist' => array(),
484 );
485 if ($row['object_id'] == NULL)
486 continue;
487 $record['rspool'][$row['id']]['lblist'][$row['object_id']] = array
488 (
489 'vsconfig' => $row['lb_vsconfig'],
490 'rsconfig' => $row['lb_rsconfig'],
491 'prio' => $row['prio'],
492 );
493 }
494 unset ($result);
495 break;
496 case 'rack':
497 $record['mountedObjects'] = array();
498 // start with default rackspace
499 for ($i = $record['height']; $i > 0; $i--)
500 for ($locidx = 0; $locidx < 3; $locidx++)
501 $record[$i][$locidx]['state'] = 'F';
502 // load difference
503 $query =
504 "select unit_no, atom, state, object_id " .
505 "from RackSpace where rack_id = ? and " .
506 "unit_no between 1 and ? order by unit_no";
507 $result = usePreparedSelectBlade ($query, array ($record['id'], $record['height']));
508 global $loclist;
509 $mounted_objects = array();
510 while ($row = $result->fetch (PDO::FETCH_ASSOC))
511 {
512 $record[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
513 $record[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
514 if ($row['state'] == 'T' and $row['object_id'] != NULL)
515 $mounted_objects[$row['object_id']] = TRUE;
516 }
517 $record['mountedObjects'] = array_keys ($mounted_objects);
518 unset ($result);
519 break;
520 case 'ipv4net':
521 $record['8021q'] = getIPv4Network8021QBindings ($record['id']);
522 break;
523 case 'ipv6net':
524 $record['8021q'] = getIPv6Network8021QBindings ($record['id']);
525 break;
526 default:
527 }
528 }
529
530 function getObjectPortsAndLinks ($object_id)
531 {
532 $query = "SELECT id, name, label, l2address, iif_id, (SELECT iif_name FROM PortInnerInterface WHERE id = iif_id) AS iif_name, " .
533 "type AS oif_id, (SELECT dict_value FROM Dictionary WHERE dict_key = type) AS oif_name, reservation_comment " .
534 "FROM Port WHERE object_id = ?";
535 // list and decode all ports of the current object
536 $result = usePreparedSelectBlade ($query, array ($object_id));
537 $ret=array();
538 while ($row = $result->fetch (PDO::FETCH_ASSOC))
539 {
540 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
541 $row['remote_id'] = NULL;
542 $row['remote_name'] = NULL;
543 $row['remote_object_id'] = NULL;
544 $ret[] = $row;
545 }
546 unset ($result);
547 // now find and decode remote ends for all locally terminated connections
548 // FIXME: can't this data be extracted in one pass with sub-queries?
549 foreach (array_keys ($ret) as $tmpkey)
550 {
551 $portid = $ret[$tmpkey]['id'];
552 $remote_id = NULL;
553 $query = "select porta, portb, cable from Link where porta = ? or portb = ?";
554 $result = usePreparedSelectBlade ($query, array ($portid, $portid));
555 $cable = "CableID n/a";
556 if ($row = $result->fetch (PDO::FETCH_ASSOC))
557 {
558 if ($portid != $row['porta'])
559 $remote_id = $row['porta'];
560 elseif ($portid != $row['portb'])
561 $remote_id = $row['portb'];
562 $cable = $row['cable'];
563 }
564 unset ($result);
565 if ($remote_id) // there's a remote end here
566 {
567 $query = "SELECT name, object_id FROM Port WHERE id = ?";
568 $result = usePreparedSelectBlade ($query, array ($remote_id));
569 if ($row = $result->fetch (PDO::FETCH_ASSOC))
570 {
571 $ret[$tmpkey]['remote_name'] = $row['name'];
572 $ret[$tmpkey]['remote_object_id'] = $row['object_id'];
573 $ret[$tmpkey]['cableid'] = $cable;
574 }
575 $ret[$tmpkey]['remote_id'] = $remote_id;
576 unset ($result);
577 }
578 }
579 return sortPortList ($ret, TRUE);
580 }
581
582 function commitAddRack ($name, $height, $row_id, $comment, $taglist)
583 {
584 usePreparedInsertBlade
585 (
586 'Rack',
587 array
588 (
589 'row_id' => $row_id,
590 'name' => $name,
591 'height' => $height,
592 'comment' => $comment
593 )
594 );
595 $last_insert_id = lastInsertID();
596 produceTagsForLastRecord ('rack', $taglist, $last_insert_id);
597 recordHistory ('Rack', $last_insert_id);
598 }
599
600 function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
601 {
602 // Maintain UNIQUE INDEX for common names and asset tags by
603 // filtering out empty strings (not NULLs).
604 $result1 = usePreparedInsertBlade
605 (
606 'RackObject',
607 array
608 (
609 'name' => !strlen ($new_name) ? NULL : $new_name,
610 'label' => $new_label,
611 'barcode' => !strlen ($new_barcode) ? NULL : $new_barcode,
612 'objtype_id' => $new_type_id,
613 'asset_no' => !strlen ($new_asset_no) ? NULL : $new_asset_no,
614 )
615 );
616 $last_insert_id = lastInsertID();
617 // Do AutoPorts magic
618 executeAutoPorts ($last_insert_id, $new_type_id);
619 // Now tags...
620 produceTagsForLastRecord ('object', $taglist, $last_insert_id);
621
622 recordHistory ('RackObject', $last_insert_id);
623
624 return $last_insert_id;
625 }
626
627 function commitUpdateObject ($object_id, $new_name, $new_label, $new_barcode, $new_has_problems, $new_asset_no, $new_comment)
628 {
629 usePreparedUpdateBlade
630 (
631 'RackObject',
632 array
633 (
634 'name' => !mb_strlen ($new_name) ? NULL : $new_name,
635 'label' => !mb_strlen ($new_label) ? NULL : $new_label,
636 'barcode' => !mb_strlen ($new_barcode) ? NULL : $new_barcode,
637 'has_problems' => $new_has_problems,
638 'asset_no' => !mb_strlen ($new_asset_no) ? NULL : $new_asset_no,
639 'comment' => $new_comment,
640 ),
641 array
642 (
643 'id' => $object_id
644 )
645 );
646 return recordHistory ('RackObject', $object_id);
647 }
648
649 // Remove file links related to the entity, but leave the entity and file(s) intact.
650 function releaseFiles ($entity_realm, $entity_id)
651 {
652 usePreparedDeleteBlade ('FileLink', array ('entity_type' => $entity_realm, 'entity_id' => $entity_id));
653 }
654
655 // There are times when you want to delete all traces of an object
656 function commitDeleteObject ($object_id = 0)
657 {
658 // Reset most of stuff
659 commitResetObject ($object_id);
660 // Object itself
661 usePreparedDeleteBlade ('RackObject', array ('id' => $object_id));
662 }
663
664 function commitResetObject ($object_id = 0)
665 {
666 releaseFiles ('object', $object_id);
667 destroyTagsForEntity ('object', $object_id);
668 usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id));
669 usePreparedDeleteBlade ('IPv4Allocation', array ('object_id' => $object_id));
670 usePreparedDeleteBlade ('IPv6Allocation', array ('object_id' => $object_id));
671 usePreparedDeleteBlade ('IPv4NAT', array ('object_id' => $object_id));
672 // Rack space
673 usePreparedExecuteBlade ('DELETE FROM Atom WHERE molecule_id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
674 usePreparedExecuteBlade ('DELETE FROM Molecule WHERE id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
675 usePreparedDeleteBlade ('MountOperation', array ('object_id' => $object_id));
676 usePreparedDeleteBlade ('RackSpace', array ('object_id' => $object_id));
677 // 802.1Q
678 usePreparedDeleteBlade ('PortVLANMode', array ('object_id' => $object_id));
679 usePreparedDeleteBlade ('PortNativeVLAN', array ('object_id' => $object_id));
680 usePreparedDeleteBlade ('PortAllowedVLAN', array ('object_id' => $object_id));
681 usePreparedDeleteBlade ('CachedPVM', array ('object_id' => $object_id));
682 usePreparedDeleteBlade ('VLANSwitch', array ('object_id' => $object_id));
683 // Ports & links
684 usePreparedDeleteBlade ('Port', array ('object_id' => $object_id));
685 // CN
686 usePreparedUpdateBlade ('RackObject', array ('name' => NULL, 'label' => ''), array ('id' => $object_id));
687 // FQDN
688 commitUpdateAttrValue ($object_id, 3, "");
689 // log history
690 recordHistory ('RackObject', $object_id);
691 }
692
693 function commitDeleteRack($rack_id)
694 {
695 releaseFiles ('rack', $rack_id);
696 destroyTagsForEntity ('rack', $rack_id);
697 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id));
698 usePreparedDeleteBlade ('RackHistory', array ('id' => $rack_id));
699 usePreparedDeleteBlade ('Rack', array ('id' => $rack_id));
700 return TRUE;
701 }
702
703 function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
704 {
705 // Can't shrink a rack if rows being deleted contain mounted objects
706 $check_result = usePreparedSelectBlade ('SELECT COUNT(*) AS count FROM RackSpace WHERE rack_id = ? AND unit_no > ?', array ($rack_id, $new_height));
707 $check_row = $check_result->fetch (PDO::FETCH_ASSOC);
708 unset ($check_result);
709 if ($check_row['count'] > 0)
710 throw new InvalidArgException ('new_height', $new_height, 'Cannot shrink rack, objects are still mounted there');
711 usePreparedUpdateBlade
712 (
713 'Rack',
714 array
715 (
716 'name' => $new_name,
717 'height' => $new_height,
718 'comment' => $new_comment,
719 'row_id' => $new_row_id,
720 ),
721 array
722 (
723 'id' => $rack_id,
724 )
725 );
726 return recordHistory ('Rack', $rack_id);
727 }
728
729 // This function accepts rack data returned by amplifyCell(), validates and applies changes
730 // supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
731 // correspond to current rack ID.
732 // 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
733 // If 4th arg is present, object_id fields will be updated accordingly to the new state.
734 // The function returns the modified rack upon success.
735 function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
736 {
737 global $loclist;
738 $rack_id = $rackData['id'];
739 $rack_name = $rackData['name'];
740 $rackchanged = FALSE;
741 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
742 {
743 for ($locidx = 0; $locidx < 3; $locidx++)
744 {
745 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
746 continue;
747 // detect a change
748 $state = $rackData[$unit_no][$locidx]['state'];
749 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
750 $newstate = $checked_state;
751 else
752 $newstate = $unchecked_state;
753 if ($state == $newstate)
754 continue;
755 $rackchanged = TRUE;
756 // and validate
757 $atom = $loclist[$locidx];
758 // The only changes allowed are those introduced by checkbox grid.
759 if
760 (
761 !($state == $checked_state && $newstate == $unchecked_state) &&
762 !($state == $unchecked_state && $newstate == $checked_state)
763 )
764 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
765 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
766 // anyway and then looking for probable need of INSERT.
767 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id, 'unit_no' => $unit_no, 'atom' => $atom));
768 if ($newstate != 'F')
769 usePreparedInsertBlade ('RackSpace', array ('rack_id' => $rack_id, 'unit_no' => $unit_no, 'atom' => $atom, 'state' => $newstate));
770 if ($newstate == 'T' and $object_id != 0)
771 {
772 // At this point we already have a record in RackSpace.
773 $r = usePreparedUpdateBlade
774 (
775 'RackSpace',
776 array ('object_id' => $object_id),
777 array
778 (
779 'rack_id' => $rack_id,
780 'unit_no' => $unit_no,
781 'atom' => $atom,
782 )
783 );
784 if ($r === FALSE)
785 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
786 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
787 }
788 }
789 }
790 if ($rackchanged)
791 {
792 usePreparedUpdateBlade ('Rack', array ('thumb_data' => NULL), array ('id' => $rack_id));
793 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
794 }
795 else
796 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
797 }
798
799 // This function builds a list of rack-unit-atom records, which are assigned to
800 // the requested object.
801 function getMoleculeForObject ($object_id)
802 {
803 $result = usePreparedSelectBlade
804 (
805 'SELECT rack_id, unit_no, atom FROM RackSpace ' .
806 'WHERE state = "T" AND object_id = ? ORDER BY rack_id, unit_no, atom',
807 array ($object_id)
808 );
809 return $result->fetchAll (PDO::FETCH_ASSOC);
810 }
811
812 // This function builds a list of rack-unit-atom records for requested molecule.
813 function getMolecule ($mid = 0)
814 {
815 $result = usePreparedSelectBlade ('SELECT rack_id, unit_no, atom FROM Atom WHERE molecule_id = ?', array ($mid));
816 return $result->fetchAll (PDO::FETCH_ASSOC);
817 }
818
819 // returns exactly what is's named after
820 function lastInsertID ()
821 {
822 $result = usePreparedSelectBlade ('select last_insert_id()');
823 $row = $result->fetch (PDO::FETCH_NUM);
824 return $row[0];
825 }
826
827 // This function creates a new record in Molecule and number of linked
828 // R-U-A records in Atom.
829 function createMolecule ($molData)
830 {
831 usePreparedExecuteBlade ('INSERT INTO Molecule VALUES()');
832 $molecule_id = lastInsertID();
833 foreach ($molData as $rua)
834 usePreparedInsertBlade
835 (
836 'Atom',
837 array
838 (
839 'molecule_id' => $molecule_id,
840 'rack_id' => $rua['rack_id'],
841 'unit_no' => $rua['unit_no'],
842 'atom' => $rua['atom'],
843 )
844 );
845 return $molecule_id;
846 }
847
848 // History logger. This function assumes certain table naming convention and
849 // column design:
850 // 1. History table name equals to dictionary table name plus 'History'.
851 // 2. History table must have the same row set (w/o keys) plus one row named
852 // 'ctime' of type 'timestamp'.
853 function recordHistory ($tableName, $orig_id)
854 {
855 global $remote_username;
856 return FALSE !== usePreparedExecuteBlade
857 (
858 "INSERT INTO ${tableName}History SELECT *, CURRENT_TIMESTAMP(), ? " .
859 "FROM ${tableName} WHERE id=?",
860 array ($remote_username, $orig_id)
861 );
862 }
863
864 function getRackspaceHistory ()
865 {
866 $result = usePreparedSelectBlade
867 (
868 "SELECT id as mo_id, object_id as ro_id, ctime, comment, user_name FROM " .
869 "MountOperation ORDER BY ctime DESC"
870 );
871 return $result->fetchAll (PDO::FETCH_ASSOC);
872 }
873
874 // This function is used in renderRackspaceHistory()
875 function getOperationMolecules ($op_id = 0)
876 {
877 $result = usePreparedSelectBlade ('SELECT old_molecule_id, new_molecule_id FROM MountOperation WHERE id = ?', array ($op_id));
878 // We expect one row.
879 $row = $result->fetch (PDO::FETCH_ASSOC);
880 return array ($row['old_molecule_id'], $row['new_molecule_id']);
881 }
882
883 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
884 {
885 $result = usePreparedSelectBlade ('SELECT DISTINCT rack_id FROM RackSpace WHERE object_id = ? ORDER BY rack_id', array ($object_id));
886 $rows = $result->fetchAll (PDO::FETCH_NUM);
887 unset ($result);
888 $ret = array();
889 foreach ($rows as $row)
890 {
891 if (!$fetch_rackdata)
892 {
893 $ret[$row[0]] = $row[0];
894 continue;
895 }
896 $rackData = spotEntity ('rack', $row[0]);
897 amplifyCell ($rackData);
898 $ret[$row[0]] = $rackData;
899 }
900 return $ret;
901 }
902
903 function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
904 {
905 $db_l2address = l2addressForDatabase ($port_l2address);
906 global $dbxlink;
907 $dbxlink->exec ('LOCK TABLES Port WRITE');
908 if (alreadyUsedL2Address ($db_l2address, $object_id))
909 {
910 $dbxlink->exec ('UNLOCK TABLES');
911 throw new InvalidRequestArgException ('port_l2address', $port_l2address, 'address belongs to another object');
912 }
913 $matches = array();
914 switch (1)
915 {
916 case preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $port_type_id, $matches):
917 $iif_id = $matches[1];
918 $oif_id = $matches[2];
919 break;
920 case preg_match ('/^([[:digit:]]+)$/', $port_type_id, $matches):
921 $iif_id = 1;
922 $oif_id = $matches[1];
923 break;
924 default:
925 $dbxlink->exec ('UNLOCK TABLES');
926 throw new InvalidArgException ('port_type_id', $port_type_id, 'format error');
927 }
928 $result = usePreparedInsertBlade
929 (
930 'Port',
931 array
932 (
933 'name' => $port_name,
934 'object_id' => $object_id,
935 'label' => $port_label,
936 'iif_id' => $iif_id,
937 'type' => $oif_id,
938 'l2address' => ($db_l2address === '') ? NULL : $db_l2address,
939 )
940 );
941 $dbxlink->exec ('UNLOCK TABLES');
942 }
943
944 // The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
945 // string value. In case it is omitted, we just assign it its current value.
946 // It would be nice to simplify this semantics later.
947 function commitUpdatePort ($object_id, $port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_reservation_comment)
948 {
949 $db_l2address = l2addressForDatabase ($port_l2address);
950 global $dbxlink;
951 $dbxlink->exec ('LOCK TABLES Port WRITE');
952 if (alreadyUsedL2Address ($db_l2address, $object_id))
953 {
954 $dbxlink->exec ('UNLOCK TABLES');
955 // FIXME: it is more correct to throw InvalidArgException here
956 // and convert it to InvalidRequestArgException at upper level,
957 // when there is a mean to do that.
958 throw new InvalidRequestArgException ('port_l2address', $db_l2address, 'address belongs to another object');
959 }
960 usePreparedUpdateBlade
961 (
962 'Port',
963 array
964 (
965 'name' => $port_name,
966 'type' => $port_type_id,
967 'label' => $port_label,
968 'reservation_comment' => mb_strlen ($port_reservation_comment) ? $port_reservation_comment : NULL,
969 'l2address' => ($db_l2address === '') ? NULL : $db_l2address,
970 ),
971 array
972 (
973 'id' => $port_id,
974 'object_id' => $object_id
975 )
976 );
977 $dbxlink->exec ('UNLOCK TABLES');
978 }
979
980 function getAllIPv4Allocations ()
981 {
982 $result = usePreparedSelectBlade
983 (
984 "select object_id as object_id, ".
985 "RackObject.name as object_name, ".
986 "IPv4Allocation.name as name, ".
987 "INET_NTOA(ip) as ip ".
988 "from IPv4Allocation join RackObject on id=object_id "
989 );
990 $ret = array();
991 while ($row = $result->fetch (PDO::FETCH_ASSOC))
992 $ret[] = $row;
993 return $ret;
994 }
995
996 function linkPorts ($porta, $portb, $cable = NULL)
997 {
998 if ($porta == $portb)
999 throw new InvalidArgException ('porta/portb', $porta, "Ports can't be the same");
1000
1001 global $dbxlink;
1002 $dbxlink->exec ('LOCK TABLES Link WRITE');
1003 $result = usePreparedSelectBlade
1004 (
1005 'SELECT COUNT(*) FROM Link WHERE porta IN (?,?) OR portb IN (?,?)',
1006 array ($porta, $portb, $porta, $portb)
1007 );
1008 if ($result->fetchColumn () != 0)
1009 {
1010 $dbxlink->exec ('UNLOCK TABLES');
1011 return "Port ${porta} or ${portb} is already linked";
1012 }
1013 if ($porta > $portb)
1014 {
1015 $tmp = $porta;
1016 $porta = $portb;
1017 $portb = $tmp;
1018 }
1019 $ret = FALSE !== usePreparedInsertBlade ('Link', array ('porta' => $porta, 'portb' => $portb, 'cable' => $cable));
1020 $dbxlink->exec ('UNLOCK TABLES');
1021 $ret = $ret and FALSE !== usePreparedExecuteBlade
1022 (
1023 'UPDATE Port SET reservation_comment=NULL WHERE id IN(?, ?)',
1024 array ($porta, $portb)
1025 );
1026 return $ret ? '' : 'query failed';
1027 }
1028
1029 // Return all IPv4 addresses allocated to the objects. Attach detailed
1030 // info about address to each alocation records. Index result by dotted-quad
1031 // address.
1032 function getObjectIPv4Allocations ($object_id = 0)
1033 {
1034 $ret = array();
1035 $result = usePreparedSelectBlade
1036 (
1037 'SELECT name AS osif, type, inet_ntoa(ip) AS dottedquad FROM IPv4Allocation ' .
1038 'WHERE object_id = ? ORDER BY ip',
1039 array ($object_id)
1040 );
1041 // don't spawn a sub-query with unfetched buffer, it may fail
1042 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1043 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
1044 unset ($result);
1045 foreach (array_keys ($ret) as $dottedquad)
1046 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
1047 return $ret;
1048 }
1049
1050 // Return all IPv6 addresses allocated to the objects. Attach detailed
1051 // info about address to each alocation records. Index result by binary string of IPv6
1052 function getObjectIPv6Allocations ($object_id = 0)
1053 {
1054 $ret = array();
1055 $result = usePreparedSelectBlade
1056 (
1057 'SELECT name AS osif, type, ip AS ip FROM IPv6Allocation ' .
1058 'WHERE object_id = ? ORDER BY ip',
1059 array ($object_id)
1060 );
1061 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1062 $ret[$row['ip']] = array ('osif' => $row['osif'], 'type' => $row['type']);
1063 unset ($result);
1064 foreach (array_keys ($ret) as $ip_bin)
1065 $ret[$ip_bin]['addrinfo'] = getIPv6Address (new IPv6Address ($ip_bin));
1066 return $ret;
1067 }
1068
1069 // Return minimal IPv4 address, optionally with "ip" key set, if requested.
1070 function constructIPv4Address ($dottedquad = NULL)
1071 {
1072 $ret = array
1073 (
1074 'version' => 4,
1075 'name' => '',
1076 'reserved' => 'no',
1077 'outpf' => array(),
1078 'inpf' => array(),
1079 'rslist' => array(),
1080 'allocs' => array(),
1081 'lblist' => array()
1082 );
1083 if ($dottedquad != NULL)
1084 $ret['ip'] = $dottedquad;
1085 return $ret;
1086 }
1087
1088 // Return minimal IPv6 address, optionally with "ip" key set, if requested.
1089 function constructIPv6Address ($bin_ip = NULL)
1090 {
1091 $ret = array
1092 (
1093 'version' => 6,
1094 'name' => '',
1095 'reserved' => 'no',
1096 'allocs' => array(),
1097 );
1098 if ($bin_ip != NULL)
1099 $ret['ip'] = $bin_ip->format();
1100 return $ret;
1101 }
1102
1103 // Check the range requested for meaningful IPv4 records, build them
1104 // into a list and return. Return an empty list if nothing matched.
1105 // Both arguments are expected in signed int32 form. The resulting list
1106 // is keyed by uint32 form of each IP address, items aren't sorted.
1107 // LATER: accept a list of pairs and build WHERE sub-expression accordingly
1108 function scanIPv4Space ($pairlist)
1109 {
1110 $ret = array();
1111 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
1112 return $ret;
1113 // FIXME: this is a copy-and-paste prototype
1114 $or = '';
1115 $whereexpr1 = '(';
1116 $whereexpr2 = '(';
1117 $whereexpr3 = '(';
1118 $whereexpr4 = '(';
1119 $whereexpr5a = '(';
1120 $whereexpr5b = '(';
1121 $qparams = array();
1122 foreach ($pairlist as $tmp)
1123 {
1124 $db_first = sprintf ('%u', 0x00000000 + $tmp['i32_first']);
1125 $db_last = sprintf ('%u', 0x00000000 + $tmp['i32_last']);
1126 $whereexpr1 .= $or . "ip between ? and ?";
1127 $whereexpr2 .= $or . "ip between ? and ?";
1128 $whereexpr3 .= $or . "vip between ? and ?";
1129 $whereexpr4 .= $or . "rsip between ? and ?";
1130 $whereexpr5a .= $or . "remoteip between ? and ?";
1131 $whereexpr5b .= $or . "localip between ? and ?";
1132 $or = ' or ';
1133 $qparams[] = $db_first;
1134 $qparams[] = $db_last;
1135 }
1136 $whereexpr1 .= ')';
1137 $whereexpr2 .= ')';
1138 $whereexpr3 .= ')';
1139 $whereexpr4 .= ')';
1140 $whereexpr5a .= ')';
1141 $whereexpr5b .= ')';
1142
1143 // 1. collect labels and reservations
1144 $query = "select INET_NTOA(ip) as ip, name, reserved from IPv4Address ".
1145 "where ${whereexpr1} and (reserved = 'yes' or name != '')";
1146 $result = usePreparedSelectBlade ($query, $qparams);
1147 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1148 {
1149 $ip_bin = ip2long ($row['ip']);
1150 if (!isset ($ret[$ip_bin]))
1151 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1152 $ret[$ip_bin]['name'] = $row['name'];
1153 $ret[$ip_bin]['reserved'] = $row['reserved'];
1154 }
1155 unset ($result);
1156
1157 // 2. check for allocations
1158 $query =
1159 "select INET_NTOA(ip) as ip, object_id, name, type " .
1160 "from IPv4Allocation where ${whereexpr2} order by type";
1161 $result = usePreparedSelectBlade ($query, $qparams);
1162 // release DBX early to avoid issues with nested spotEntity() calls
1163 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1164 unset ($result);
1165 foreach ($allRows as $row)
1166 {
1167 $ip_bin = ip2long ($row['ip']);
1168 if (!isset ($ret[$ip_bin]))
1169 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1170 $oinfo = spotEntity ('object', $row['object_id']);
1171 $ret[$ip_bin]['allocs'][] = array
1172 (
1173 'type' => $row['type'],
1174 'name' => $row['name'],
1175 'object_id' => $row['object_id'],
1176 'object_name' => $oinfo['dname'],
1177 );
1178 }
1179
1180 // 3. look for virtual services and related LB
1181 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, object_id " .
1182 "from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id " .
1183 "where ${whereexpr3} order by vport, proto, object_id";
1184 $result = usePreparedSelectBlade ($query, $qparams);
1185 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1186 unset ($result);
1187 foreach ($allRows as $row)
1188 {
1189 $ip_bin = ip2long ($row['ip']);
1190 if (!isset ($ret[$ip_bin]))
1191 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1192 $oinfo = spotEntity ('object', $row['object_id']);
1193 $ret[$ip_bin]['lblist'][] = array
1194 (
1195 'vport' => $row['vport'],
1196 'proto' => $row['proto'],
1197 'vs_id' => $row['vs_id'],
1198 'name' => $row['name'],
1199 'vip' => $row['ip'],
1200 'object_id' => $row['object_id'],
1201 'object_name' => $oinfo['dname'],
1202 );
1203 }
1204
1205 // 4. don't forget about real servers along with pools
1206 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
1207 "IPv4RS as rs inner join IPv4RSPool as rsp on rs.rspool_id = rsp.id " .
1208 "where ${whereexpr4} " .
1209 "order by ip, rsport, rspool_id";
1210 $result = usePreparedSelectBlade ($query, $qparams);
1211 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1212 {
1213 $ip_bin = ip2long ($row['ip']);
1214 if (!isset ($ret[$ip_bin]))
1215 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1216 $tmp = array();
1217 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1218 $tmp[$cname] = $row[$cname];
1219 $ret[$ip_bin]['rslist'][] = $tmp;
1220 }
1221 unset ($result);
1222
1223 // 5. add NAT rules, part 1
1224 $query =
1225 "select " .
1226 "proto, " .
1227 "INET_NTOA(localip) as localip, " .
1228 "localport, " .
1229 "INET_NTOA(remoteip) as remoteip, " .
1230 "remoteport, " .
1231 "description " .
1232 "from IPv4NAT " .
1233 "where ${whereexpr5a} " .
1234 "order by localip, localport, remoteip, remoteport, proto";
1235 $result = usePreparedSelectBlade ($query, $qparams);
1236 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1237 {
1238 $remoteip_bin = ip2long ($row['remoteip']);
1239 if (!isset ($ret[$remoteip_bin]))
1240 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
1241 $ret[$remoteip_bin]['inpf'][] = $row;
1242 }
1243 unset ($result);
1244 // 5. add NAT rules, part 2
1245 $query =
1246 "select " .
1247 "proto, " .
1248 "INET_NTOA(localip) as localip, " .
1249 "localport, " .
1250 "INET_NTOA(remoteip) as remoteip, " .
1251 "remoteport, " .
1252 "description " .
1253 "from IPv4NAT " .
1254 "where ${whereexpr5b} " .
1255 "order by localip, localport, remoteip, remoteport, proto";
1256 $result = usePreparedSelectBlade ($query, $qparams);
1257 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1258 {
1259 $localip_bin = ip2long ($row['localip']);
1260 if (!isset ($ret[$localip_bin]))
1261 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
1262 $ret[$localip_bin]['outpf'][] = $row;
1263 }
1264 unset ($result);
1265 return $ret;
1266 }
1267
1268 // Check the range requested for meaningful IPv6 records, build them
1269 // into a list and return. Return an empty list if nothing matched.
1270 // Both arguments are expected as instances of IPv6Address class. The resulting list
1271 // is keyed by uint32 form of each IP address, items aren't sorted.
1272 function scanIPv6Space ($pairlist)
1273 {
1274 $ret = array();
1275 $wheres = array();
1276 foreach ($pairlist as $pair)
1277 {
1278 $wheres[] = "ip >= ? AND ip <= ?";
1279 $qparams[] = (string) $pair['first'];
1280 $qparams[] = (string) $pair['last'];
1281 }
1282 if (! count ($wheres)) // this is normal for a network completely divided into smaller parts
1283 return $ret;
1284 $whereexpr = '(' .implode (' OR ', $wheres) . ')';
1285
1286 // 1. collect labels and reservations
1287 $query = "select ip, name, reserved from IPv6Address ".
1288 "where ${whereexpr} and (reserved = 'yes' or name != '')";
1289 $result = usePreparedSelectBlade ($query, $qparams);
1290 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1291 {
1292 $ip_bin = new IPv6Address ($row['ip']);
1293 $key = (string)$ip_bin;
1294 if (!isset ($ret[$key]))
1295 $ret[$key] = constructIPv6Address ($ip_bin);
1296 $ret[$key]['name'] = $row['name'];
1297 $ret[$key]['reserved'] = $row['reserved'];
1298 }
1299 unset ($result);
1300
1301 // 2. check for allocations
1302 $query =
1303 "select ip, object_id, name, type " .
1304 "from IPv6Allocation where ${whereexpr} order by type";
1305 $result = usePreparedSelectBlade ($query, $qparams);
1306 // release DBX early to avoid issues with nested spotEntity() calls
1307 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1308 unset ($result);
1309 foreach ($allRows as $row)
1310 {
1311 $ip_bin = new IPv6Address ($row['ip']);
1312 $key = (string)$ip_bin;
1313 if (!isset ($ret[$key]))
1314 $ret[$key] = constructIPv6Address ($ip_bin);
1315 $oinfo = spotEntity ('object', $row['object_id']);
1316 $ret[$key]['allocs'][] = array
1317 (
1318 'type' => $row['type'],
1319 'name' => $row['name'],
1320 'object_id' => $row['object_id'],
1321 'object_name' => $oinfo['dname'],
1322 );
1323 }
1324 return $ret;
1325 }
1326
1327 // this is a wrapper around getIPv4Address and getIPv6Address
1328 // You can pass dotted IPv4, human representation of IPv6, or instance of IPv6Address
1329 function getIPAddress ($ip)
1330 {
1331 if (is_a ($ip, 'IPv6Address'))
1332 return getIPv6Address ($ip);
1333 $ipv6 = new IPv6Address;
1334 if ($ipv6->parse ($ip))
1335 return getIPv6Address ($ipv6);
1336 return getIPv4Address ($ip);
1337 }
1338
1339 function getIPv4Address ($dottedquad = '')
1340 {
1341 if ($dottedquad == '')
1342 throw new InvalidArgException ('$dottedquad', $dottedquad);
1343 $i32 = ip2long ($dottedquad); // signed 32 bit
1344 $scanres = scanIPv4Space (array (array ('i32_first' => $i32, 'i32_last' => $i32)));
1345 if (empty ($scanres))
1346 //$scanres[$i32] = constructIPv4Address ($dottedquad); // XXX: this should be verified to not break things
1347 return constructIPv4Address ($dottedquad);
1348 markupIPAddrList ($scanres);
1349 return $scanres[$i32];
1350 }
1351
1352 // returns the array of structure described by constructIPv6Address
1353 function getIPv6Address ($v6addr)
1354 {
1355 if (! is_object ($v6addr))
1356 throw new InvalidArgException ('$v6addr', $v6addr);
1357 $scanres = scanIPv6Space (array (array ('first' => $v6addr, 'last' => $v6addr)));
1358 if (empty ($scanres))
1359 return constructIPv6Address ($v6addr);
1360 markupIPAddrList ($scanres);
1361 return array_shift ($scanres);
1362 }
1363
1364 function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1365 {
1366 return usePreparedExecuteBlade
1367 (
1368 'INSERT INTO IPv4Allocation (ip, object_id, name, type) VALUES (INET_ATON(?), ?, ?, ?)',
1369 array ($ip, $object_id, $name, $type)
1370 );
1371 }
1372
1373 function bindIPv6ToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1374 {
1375 return usePreparedInsertBlade
1376 (
1377 'IPv6Allocation',
1378 array ('ip' => $ip, 'object_id' => $object_id, 'name' => $name, 'type' => $type)
1379 );
1380 }
1381
1382 // Return the id of the smallest IPv4 network containing the given IPv4 address
1383 // or NULL, if nothing was found. When finding the covering network for
1384 // another network, it is important to filter out matched records with longer
1385 // masks (they aren't going to be the right pick).
1386 function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
1387 {
1388 $query = 'select id from IPv4Network where ' .
1389 "inet_aton(?) & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1390 "and mask < ? " .
1391 'order by mask desc limit 1';
1392 $result = usePreparedSelectBlade ($query, array ($dottedquad, $masklen));
1393 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1394 return $row['id'];
1395 return NULL;
1396 }
1397
1398 // Return the id of the smallest IPv6 network containing the given IPv6 address
1399 // ($ip is an instance of IPv4Address class) or NULL, if nothing was found.
1400 function getIPv6AddressNetworkId ($ip, $masklen = 128)
1401 {
1402 $query = 'select id from IPv6Network where ip <= ? AND last_ip >= ? and mask < ? order by mask desc limit 1';
1403 $result = usePreparedSelectBlade ($query, array ((string)$ip, (string)$ip, $masklen));
1404 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1405 return $row['id'];
1406 return NULL;
1407 }
1408
1409 // It is a wrapper around updateV4Address and updateV6Address.
1410 // You can pass dotted IPv4, human representation of IPv6, or instance of IPv6Address
1411 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1412 {
1413 if (is_a ($ip, 'IPv6Address'))
1414 return updateV6Address ($ip, $name, $reserved);
1415 $ipv6 = new IPv6Address;
1416 if ($ipv6->parse ($ip))
1417 return updateV6Address ($ipv6, $name, $reserved);
1418 return updateV4Address ($ip, $name, $reserved);
1419 }
1420
1421 // This function is actually used not only to update, but also to create records,
1422 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1423 // (MySQL 4.0 workaround).
1424 function updateV4Address ($ip = 0, $name = '', $reserved = 'no')
1425 {
1426 usePreparedExecuteBlade ('DELETE FROM IPv4Address WHERE ip = INET_ATON(?)', array ($ip));
1427 // INSERT may appear not necessary.
1428 if ($name == '' and $reserved == 'no')
1429 return '';
1430 $ret = usePreparedExecuteBlade
1431 (
1432 'INSERT INTO IPv4Address (name, reserved, ip) VALUES (?, ?, INET_ATON(?))',
1433 array ($name, $reserved, $ip)
1434 );
1435 return $ret !== FALSE ? '' : (__FUNCTION__ . 'query failed');
1436 }
1437
1438 function updateV6Address ($ip, $name = '', $reserved = 'no')
1439 {
1440 usePreparedDeleteBlade ('IPv6Address', array ('ip' => $ip));
1441 // INSERT may appear not necessary.
1442 if ($name == '' and $reserved == 'no')
1443 return '';
1444 $ret = usePreparedInsertBlade
1445 (
1446 'IPv6Address',
1447 array ('name' => $name, 'reserved' => $reserved, 'ip' => $ip)
1448 );
1449 return $ret !== FALSE ? '' : (__FUNCTION__ . 'query failed');
1450 }
1451
1452 function updateBond ($ip='', $object_id=0, $name='', $type='')
1453 {
1454 return usePreparedExecuteBlade
1455 (
1456 'UPDATE IPv4Allocation SET name=?, type=? WHERE ip=INET_ATON(?) AND object_id=?',
1457 array ($name, $type, $ip, $object_id)
1458 );
1459 }
1460
1461 function updateIPv6Bond ($ip='', $object_id=0, $name='', $type='')
1462 {
1463 return usePreparedUpdateBlade
1464 (
1465 'IPv6Allocation',
1466 array
1467 (
1468 'name' => $name,
1469 'type' => $type,
1470 ),
1471 array
1472 (
1473 'ip' => $ip,
1474 'object_id' => $object_id,
1475 )
1476 );
1477 }
1478
1479 function unbindIpFromObject ($ip, $object_id)
1480 {
1481 return usePreparedExecuteBlade
1482 (
1483 'DELETE FROM IPv4Allocation WHERE ip=INET_ATON(?) AND object_id=?',
1484 array ($ip, $object_id)
1485 );
1486 }
1487
1488 function unbindIPv6FromObject ($ip, $object_id)
1489 {
1490 return usePreparedDeleteBlade
1491 (
1492 'IPv6Allocation',
1493 array ('ip' => $ip, 'object_id' => $object_id)
1494 );
1495 }
1496
1497 function getIPv4PrefixSearchResult ($terms)
1498 {
1499 $byname = getSearchResultByField
1500 (
1501 'IPv4Network',
1502 array ('id'),
1503 'name',
1504 $terms,
1505 'ip'
1506 );
1507 $ret = array();
1508 foreach ($byname as $row)
1509 $ret[$row['id']] = spotEntity ('ipv4net', $row['id']);
1510 return $ret;
1511 }
1512
1513 function getIPv6PrefixSearchResult ($terms)
1514 {
1515 $byname = getSearchResultByField
1516 (
1517 'IPv6Network',
1518 array ('id'),
1519 'name',
1520 $terms,
1521 'ip'
1522 );
1523 $ret = array();
1524 foreach ($byname as $row)
1525 $ret[$row['id']] = spotEntity ('ipv6net', $row['id']);
1526 return $ret;
1527 }
1528
1529 function getIPv4AddressSearchResult ($terms)
1530 {
1531 $query = "select inet_ntoa(ip) as ip, name from IPv4Address where ";
1532 $or = '';
1533 $qparams = array();
1534 foreach (explode (' ', $terms) as $term)
1535 {
1536 $query .= $or . "name like ?";
1537 $or = ' or ';
1538 $qparams[] = "%${term}%";
1539 }
1540 $result = usePreparedSelectBlade ($query, $qparams);
1541 $ret = array();
1542 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1543 $ret[$row['ip']] = $row;
1544 return $ret;
1545 }
1546
1547 function getIPv6AddressSearchResult ($terms)
1548 {
1549 $query = "select ip, name from IPv6Address where ";
1550 $or = '';
1551 $qparams = array();
1552 foreach (explode (' ', $terms) as $term)
1553 {
1554 $query .= $or . "name like ?";
1555 $or = ' or ';
1556 $qparams[] = "%${term}%";
1557 }
1558 $result = usePreparedSelectBlade ($query, $qparams);
1559 $ret = array();
1560 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1561 $ret[$row['ip']] = $row;
1562 return $ret;
1563 }
1564
1565 function getIPv4RSPoolSearchResult ($terms)
1566 {
1567 $byname = getSearchResultByField
1568 (
1569 'IPv4RSPool',
1570 array ('id'),
1571 'name',
1572 $terms,
1573 'name'
1574 );
1575 $ret = array();
1576 foreach ($byname as $row)
1577 $ret[$row['id']] = spotEntity ('ipv4rspool', $row['id']);
1578 return $ret;
1579 }
1580
1581 function getIPv4VServiceSearchResult ($terms)
1582 {
1583 $byname = getSearchResultByField
1584 (
1585 'IPv4VS',
1586 array ('id'),
1587 'name',
1588 $terms,
1589 'vip'
1590 );
1591 $ret = array();
1592 foreach ($byname as $row)
1593 $ret[$row['id']] = spotEntity ('ipv4vs', $row['id']);
1594 return $ret;
1595 }
1596
1597 function getAccountSearchResult ($terms)
1598 {
1599 $byUsername = getSearchResultByField
1600 (
1601 'UserAccount',
1602 array ('user_id', 'user_name', 'user_realname'),
1603 'user_name',
1604 $terms,
1605 'user_name'
1606 );
1607 $byRealname = getSearchResultByField
1608 (
1609 'UserAccount',
1610 array ('user_id', 'user_name', 'user_realname'),
1611 'user_realname',
1612 $terms,
1613 'user_name'
1614 );
1615 // Merge it together, if duplicates persist, byUsername wins
1616 foreach (array ($byRealname, $byUsername) as $array)
1617 foreach ($array as $user)
1618 {
1619 $user['realm'] = 'user';
1620 $ret[$user['user_id']] = $user;
1621 }
1622 return $ret;
1623 }
1624
1625 function getFileSearchResult ($terms)
1626 {
1627 $byName = getSearchResultByField
1628 (
1629 'File',
1630 array ('id'),
1631 'name',
1632 $terms,
1633 'name'
1634 );
1635 $byComment = getSearchResultByField
1636 (
1637 'File',
1638 array ('id'),
1639 'comment',
1640 $terms,
1641 'name'
1642 );
1643 // Filter out dupes.
1644 foreach ($byName as $res1)
1645 foreach (array_keys ($byComment) as $key2)
1646 if ($res1['id'] == $byComment[$key2]['id'])
1647 {
1648 unset ($byComment[$key2]);
1649 continue 2;
1650 }
1651 $ret = array();
1652 foreach (array_merge ($byName, $byComment) as $row)
1653 $ret[$row['id']] = spotEntity ('file', $row['id']);
1654 return $ret;
1655 }
1656
1657 function getRackSearchResult ($terms)
1658 {
1659 $byName = getSearchResultByField
1660 (
1661 'Rack',
1662 array ('id'),
1663 'name',
1664 $terms,
1665 'name'
1666 );
1667 $byComment = getSearchResultByField
1668 (
1669 'Rack',
1670 array ('id'),
1671 'comment',
1672 $terms,
1673 'name'
1674 );
1675 // Filter out dupes.
1676 foreach ($byName as $res1)
1677 foreach (array_keys ($byComment) as $key2)
1678 if ($res1['id'] == $byComment[$key2]['id'])
1679 {
1680 unset ($byComment[$key2]);
1681 continue 2;
1682 }
1683 $ret = array();
1684 foreach (array_merge ($byName, $byComment) as $row)
1685 $ret[$row['id']] = spotEntity ('rack', $row['id']);
1686 return $ret;
1687 }
1688
1689 function getVLANSearchResult ($terms)
1690 {
1691 $ret = array();
1692 $matches = array();
1693 if (preg_match ('/^vlan\s*(\d+)$/i', $terms, $matches))
1694 {
1695 $byID = getSearchResultByField
1696 (
1697 'VLANDescription',
1698 array ('domain_id', 'vlan_id'),
1699 'vlan_id',
1700 $matches[1],
1701 'domain_id',
1702 1
1703 );
1704 foreach ($byID as $row)
1705 {
1706 $vlan_ck = $row['domain_id'] . '-' . $row['vlan_id'];
1707 $ret[$vlan_ck] = $vlan_ck;
1708 }
1709 }
1710 else
1711 {
1712 $byDescr = getSearchResultByField
1713 (
1714 'VLANDescription',
1715 array ('domain_id', 'vlan_id'),
1716 'vlan_descr',
1717 $terms
1718 );
1719 foreach ($byDescr as $row)
1720 {
1721 $vlan_ck = $row['domain_id'] . '-' . $row['vlan_id'];
1722 $ret[$vlan_ck] = $vlan_ck;
1723 }
1724 }
1725 return $ret;
1726 }
1727
1728 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '', $exactness = 0)
1729 {
1730 $pfx = '';
1731 $query = 'select ';
1732 $qparams = array();
1733 foreach ($rcolumns as $col)
1734 {
1735 $query .= $pfx . $col;
1736 $pfx = ', ';
1737 }
1738 $pfx = '';
1739 $query .= " from ${tname} where ";
1740 foreach (explode (' ', $terms) as $term)
1741 {
1742 switch ($exactness)
1743 {
1744 case 2: // does this work as expected?
1745 $query .= $pfx . "binary ${scolumn} = ?";
1746 $qparams[] = $term;
1747 break;
1748 case 1:
1749 $query .= $pfx . "${scolumn} = ?";
1750 $qparams[] = $term;
1751 break;
1752 default:
1753 $query .= $pfx . "${scolumn} like ?";
1754 $qparams[] = "%${term}%";
1755 break;
1756 }
1757 $pfx = ' or ';
1758 }
1759 if ($ocolumn != '')
1760 $query .= " order by ${ocolumn}";
1761 $result = usePreparedSelectBlade ($query, $qparams);
1762 $ret = array();
1763 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1764 $ret[] = $row;
1765 return $ret;
1766 }
1767
1768 function getObjectSearchResults ($what)
1769 {
1770 $ret = array();
1771 global $searchfunc;
1772 foreach ($searchfunc['object'] as $method => $func)
1773 foreach ($func ($what) as $objRecord)
1774 {
1775 $ret[$objRecord['id']]['id'] = $objRecord['id'];
1776 $ret[$objRecord['id']][$method] = $objRecord[$method];
1777 }
1778 return $ret;
1779 }
1780
1781 function getObjectAttrsSearchResults ($what)
1782 {
1783 $ret = array();
1784 foreach (array ('name', 'label', 'asset_no', 'barcode') as $column)
1785 {
1786 $tmp = getSearchResultByField
1787 (
1788 'RackObject',
1789 array ('id'),
1790 $column,
1791 $what,
1792 $column
1793 );
1794 foreach ($tmp as $row)
1795 {
1796 $ret[$row['id']]['id'] = $row['id'];
1797 $ret[$row['id']]['by_attr'][] = $column;
1798 }
1799 }
1800 return $ret;
1801 }
1802
1803 // Look for EXACT value in stickers and return a list of pairs "object_id-attribute_id",
1804 // which matched. A partilar object_id could be returned more, than once, if it has
1805 // multiple matching stickers. Search is only performed on "string" attributes.
1806 function getStickerSearchResults ($what, $exactness = 0)
1807 {
1808 $stickers = getSearchResultByField
1809 (
1810 'AttributeValue',
1811 array ('object_id', 'attr_id'),
1812 'string_value',
1813 $what,
1814 'object_id',
1815 $exactness
1816 );
1817 $map = getAttrMap();
1818 $ret = array();
1819 foreach ($stickers as $sticker)
1820 if ($map[$sticker['attr_id']]['type'] == 'string')
1821 {
1822 $ret[$sticker['object_id']]['id'] = $sticker['object_id'];
1823 $ret[$sticker['object_id']]['by_sticker'][] = $sticker['attr_id'];
1824 }
1825 return $ret;
1826 }
1827
1828 // search in port "reservation comment", "label" and "L2 address" columns
1829 function getPortSearchResults ($what)
1830 {
1831 $ret = array();
1832 $ports = getSearchResultByField
1833 (
1834 'Port',
1835 array ('object_id', 'id', 'reservation_comment'),
1836 'reservation_comment',
1837 $what,
1838 'object_id',
1839 0
1840 );
1841 foreach ($ports as $port)
1842 {
1843 $ret[$port['object_id']]['id'] = $port['object_id'];
1844 $ret[$port['object_id']]['by_port'][$port['id']] = $port['reservation_comment'];
1845 }
1846 $ports = getSearchResultByField
1847 (
1848 'Port',
1849 array ('object_id', 'id', 'label'),
1850 'label',
1851 $what,
1852 'object_id',
1853 0
1854 );
1855 foreach ($ports as $port)
1856 {
1857 $ret[$port['object_id']]['id'] = $port['object_id'];
1858 $ret[$port['object_id']]['by_port'][$port['id']] = $port['label'];
1859 }
1860 try
1861 {
1862 $db_l2address = l2addressForDatabase ($what);
1863 }
1864 catch (InvalidArgException $e)
1865 {
1866 return $ret;
1867 }
1868 $ports = getSearchResultByField
1869 (
1870 'Port',
1871 array ('object_id', 'id', 'l2address'),
1872 'l2address',
1873 $db_l2address,
1874 'object_id',
1875 2
1876 );
1877 foreach ($ports as $port)
1878 {
1879 $ret[$port['object_id']]['id'] = $port['object_id'];
1880 $ret[$port['object_id']]['by_port'][$port['id']] = $port['l2address'];
1881 }
1882 return $ret;
1883 }
1884
1885 // search in IPv4 allocations
1886 function getObjectIfacesSearchResults ($what)
1887 {
1888 $ret = array();
1889 $ifaces4 = getSearchResultByField
1890 (
1891 'IPv4Allocation',
1892 array ('object_id', 'name'),
1893 'name',
1894 $what,
1895 'object_id'
1896 );
1897 $ifaces6 = getSearchResultByField
1898 (
1899 'IPv6Allocation',
1900 array ('object_id', 'name'),
1901 'name',
1902 $what,
1903 'object_id'
1904 );
1905 foreach (array_merge ($ifaces4, $ifaces6) as $row)
1906 {
1907 $ret[$row['object_id']]['id'] = $row['object_id'];
1908 $ret[$row['object_id']]['by_iface'][] = $row['name'];
1909 }
1910 return $ret;
1911 }
1912
1913 function getObjectNATSearchResults ($what)
1914 {
1915 $ret = array();
1916 $ifaces = getSearchResultByField
1917 (
1918 'IPv4NAT',
1919 array ('object_id', 'description'),
1920 'description',
1921 $what,
1922 'object_id'
1923 );
1924 foreach ($ifaces as $row)
1925 {
1926 $ret[$row['object_id']]['id'] = $row['object_id'];
1927 $ret[$row['object_id']]['by_nat'][] = $row['description'];
1928 }
1929 return $ret;
1930 }
1931
1932 // This function returns either port ID or NULL for specified arguments.
1933 function getPortIDs ($object_id, $port_name)
1934 {
1935 $ret = array();
1936 $result = usePreparedSelectBlade ('SELECT id FROM Port WHERE object_id = ? AND name = ?', array ($object_id, $port_name));
1937 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1938 $ret[] = $row['id'];
1939 return $ret;
1940 }
1941
1942 // Search in "FQDN" attribute only, and return object ID, when there is exactly
1943 // one result found (and NULL in any other case).
1944 function searchByMgmtHostname ($string)
1945 {
1946 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value = ? LIMIT 2', array ($string));
1947 $rows = $result->fetchAll (PDO::FETCH_NUM);
1948 if (count ($rows) != 1)
1949 return NULL;
1950 return $rows[0][0];
1951 }
1952
1953 function commitCreateUserAccount ($username, $realname, $password)
1954 {
1955 return usePreparedInsertBlade
1956 (
1957 'UserAccount',
1958 array
1959 (
1960 'user_name' => $username,
1961 'user_realname' => $realname,
1962 'user_password_hash' => $password,
1963 )
1964 );
1965 }
1966
1967 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1968 {
1969 return usePreparedUpdateBlade
1970 (
1971 'UserAccount',
1972 array
1973 (
1974 'user_name' => $new_username,
1975 'user_realname' => $new_realname,
1976 'user_password_hash' => $new_password,
1977 ),
1978 array ('user_id' => $id)
1979 );
1980 }
1981
1982 // This function returns an array of all port type pairs from PortCompat table.
1983 function getPortOIFCompat ()
1984 {
1985 $query =
1986 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1987 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1988 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1989 'ORDER BY type1name, type2name';
1990 $result = usePreparedSelectBlade ($query);
1991 return $result->fetchAll (PDO::FETCH_ASSOC);
1992 }
1993
1994 function getDictStats ()
1995 {
1996 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28);
1997 $result = usePreparedSelectBlade
1998 (
1999 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
2000 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id"
2001 );
2002 $tc = $tw = $uc = $uw = 0;
2003 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2004 {
2005 $tc++;
2006 $tw += $row['wc'];;
2007 if (in_array ($row['chapter_no'], $stock_chapters))
2008 continue;
2009 $uc++;
2010 $uw += $row['wc'];;
2011 }
2012 unset ($result);
2013 $result = usePreparedSelectBlade
2014 (
2015 "select count(object_id) as attrc from RackObject as ro left join " .
2016 "AttributeValue as av on ro.id = av.object_id group by ro.id"
2017 );
2018 $to = $ta = $so = 0;
2019 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2020 {
2021 $to++;
2022 if ($row['attrc'] != 0)
2023 {
2024 $so++;
2025 $ta += $row['attrc'];
2026 }
2027 }
2028 unset ($result);
2029 $ret = array();
2030 $ret['Total chapters in dictionary'] = $tc;
2031 $ret['Total words in dictionary'] = $tw;
2032 $ret['User chapters'] = $uc;
2033 $ret['Words in user chapters'] = $uw;
2034 $ret['Total objects'] = $to;
2035 $ret['Objects with stickers'] = $so;
2036 $ret['Total stickers attached'] = $ta;
2037 return $ret;
2038 }
2039
2040 function getIPv4Stats ()
2041 {
2042 $ret = array();
2043 $subject = array();
2044 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
2045 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
2046 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
2047 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
2048 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
2049 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
2050 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
2051 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
2052
2053 foreach ($subject as $item)
2054 {
2055 $result = usePreparedSelectBlade ($item['q']);
2056 $row = $result->fetch (PDO::FETCH_NUM);
2057 $ret[$item['txt']] = $row[0];
2058 unset ($result);
2059 }
2060 return $ret;
2061 }
2062
2063 function getIPv6Stats ()
2064 {
2065 $ret = array();
2066 $subject = array();
2067 $subject[] = array ('q' => 'select count(id) from IPv6Network', 'txt' => 'Networks');
2068 $subject[] = array ('q' => 'select count(ip) from IPv6Address', 'txt' => 'Addresses commented/reserved');
2069 $subject[] = array ('q' => 'select count(ip) from IPv6Allocation', 'txt' => 'Addresses allocated');
2070
2071 foreach ($subject as $item)
2072 {
2073 $result = usePreparedSelectBlade ($item['q']);
2074 $row = $result->fetch (PDO::FETCH_NUM);
2075 $ret[$item['txt']] = $row[0];
2076 unset ($result);
2077 }
2078 return $ret;
2079 }
2080
2081 function getRackspaceStats ()
2082 {
2083 $ret = array();
2084 $subject = array();
2085 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
2086 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
2087 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
2088 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
2089
2090 foreach ($subject as $item)
2091 {
2092 $result = usePreparedSelectBlade ($item['q']);
2093 $row = $result->fetch (PDO::FETCH_NUM);
2094 $ret[$item['txt']] = !strlen ($row[0]) ? 0 : $row[0];
2095 unset ($result);
2096 }
2097 return $ret;
2098 }
2099
2100 /*
2101
2102 The following allows figuring out records in TagStorage, which refer to non-existing entities:
2103
2104 mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
2105 mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
2106 mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
2107 mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
2108 mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
2109 mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
2110 mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
2111
2112 Accordingly, these are the records, which refer to non-existent tags:
2113
2114 mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
2115
2116 */
2117
2118 function commitDeleteChapter ($chapter_no = 0)
2119 {
2120 return usePreparedDeleteBlade ('Chapter', array ('id' => $chapter_no, 'sticky' => 'no'));
2121 }
2122
2123 // This is a dictionary accessor. We perform link rendering, so the user sees
2124 // nice <select> drop-downs.
2125 function readChapter ($chapter_id = 0, $style = '')
2126 {
2127 $result = usePreparedSelectBlade
2128 (
2129 "select dict_key, dict_value from Dictionary " .
2130 "where chapter_id = ?",
2131 array ($chapter_id)
2132 );
2133 $chapter = array();
2134 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2135 $chapter[$row['dict_key']] = $style == '' ? $row['dict_value'] : parseWikiLink ($row['dict_value'], $style);
2136 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
2137 asort ($chapter);
2138 return $chapter;
2139 }
2140
2141 // Return refcounters for all given keys of the given chapter.
2142 function getChapterRefc ($chapter_id, $keylist)
2143 {
2144 $ret = array();
2145 foreach ($keylist as $key)
2146 $ret[$key] = 0;
2147 switch ($chapter_id)
2148 {
2149 case CHAP_OBJTYPE:
2150 // RackObjectType chapter is referenced by AttributeMap and RackObject tables
2151 $query = 'select dict_key as uint_value, (select count(*) from AttributeMap where objtype_id = dict_key) + ' .
2152 "(select count(*) from RackObject where objtype_id = dict_key) as refcnt from Dictionary where chapter_id = ?";
2153 break;
2154 case CHAP_PORTTYPE:
2155 // PortOuterInterface chapter is referenced by PortCompat, PortInterfaceCompat and Port tables
2156 $query = 'select dict_key as uint_value, (select count(*) from PortCompat where type1 = dict_key or type2 = dict_key) + ' .
2157 '(select count(*) from Port where type = dict_key) + (SELECT COUNT(*) FROM PortInterfaceCompat WHERE oif_id = dict_key) as refcnt ' .
2158 "from Dictionary where chapter_id = ?";
2159 break;
2160 default:
2161 // Find the list of all assigned values of dictionary-addressed attributes, each with
2162 // chapter/word keyed reference counters.
2163 $query = "select uint_value, count(object_id) as refcnt
2164 from AttributeMap am
2165 inner join AttributeValue av on am.attr_id = av.attr_id
2166 inner join RackObject ro on ro.id = av.object_id
2167 where am.chapter_id = ? and ro.objtype_id = am.objtype_id
2168 group by uint_value";
2169 break;
2170 }
2171 $result = usePreparedSelectBlade ($query, array ($chapter_id));
2172 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2173 $ret[$row['uint_value']] = $row['refcnt'];
2174 return $ret;
2175 }
2176
2177 // Return a list of all stickers with sticker map applied. Each sticker records will
2178 // list all its ways on the map with refcnt set.
2179 function getAttrMap ()
2180 {
2181 $result = usePreparedSelectBlade
2182 (
2183 'SELECT id, type, name, chapter_id, (SELECT dict_value FROM Dictionary WHERE dict_key = objtype_id) '.
2184 'AS objtype_name, (SELECT name FROM Chapter WHERE id = chapter_id) ' .
2185 'AS chapter_name, objtype_id, (SELECT COUNT(object_id) FROM AttributeValue AS av INNER JOIN RackObject AS ro ' .
2186 'ON av.object_id = ro.id WHERE av.attr_id = Attribute.id AND ro.objtype_id = AttributeMap.objtype_id) ' .
2187 'AS refcnt FROM Attribute LEFT JOIN AttributeMap ON id = attr_id ORDER BY Attribute.name, objtype_name'
2188 );
2189 $ret = array();
2190 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2191 {
2192 if (!isset ($ret[$row['id']]))
2193 $ret[$row['id']] = array
2194 (
2195 'id' => $row['id'],
2196 'type' => $row['type'],
2197 'name' => $row['name'],
2198 'application' => array(),
2199 );
2200 if ($row['objtype_id'] == '')
2201 continue;
2202 $application = array
2203 (
2204 'objtype_id' => $row['objtype_id'],
2205 'refcnt' => $row['refcnt'],
2206 );
2207 if ($row['type'] == 'dict')
2208 {
2209 $application['chapter_no'] = $row['chapter_id'];
2210 $application['chapter_name'] = $row['chapter_name'];
2211 }
2212 $ret[$row['id']]['application'][] = $application;
2213 }
2214 return $ret;
2215 }
2216
2217 // FIXME: don't store garbage in chapter_no for non-dictionary types.
2218 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2219 {
2220 if ($attr_id <= 0)
2221 throw new InvalidArgException ('$attr_id', $attr_id);
2222 if ($objtype_id <= 0)
2223 throw new InvalidArgException ('$objtype_id', $objtype_id);
2224
2225 return usePreparedInsertBlade
2226 (
2227 'AttributeMap',
2228 array
2229 (
2230 'attr_id' => $attr_id,
2231 'objtype_id' => $objtype_id,
2232 'chapter_id' => $chapter_no
2233 )
2234 );
2235 }
2236
2237 function cacheAllObjectsAttributes()
2238 {
2239 global $object_attribute_cache;
2240 $object_attribute_cache = fetchAttrsForObjects(NULL);
2241 }
2242
2243 // Fetches a list of attributes for each object in $object_set array.
2244 // If $object_set is not set, returns attributes for all objects in DB
2245 // Returns an array with object_id keys
2246 function fetchAttrsForObjects($object_set)
2247 {
2248 $ret = array();
2249 $query =
2250 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
2251 "C.id as chapter_id, AV.uint_value, AV.float_value, AV.string_value, D.dict_value, RO.id as object_id from " .
2252 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2253 "inner join Attribute as A on AM.attr_id = A.id " .
2254 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
2255 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2256 "left join Chapter as C on AM.chapter_id = C.id";
2257 if (is_array ($object_set) && !empty ($object_set))
2258 {
2259 $query .= ' WHERE RO.id IN (';
2260 foreach ($object_set as $object_id)
2261 $query .= intval ($object_id) . ', ';
2262 $query = trim ($query, ', ') . ')';
2263 }
2264 $query .= " order by A.name, A.type";
2265
2266 $result = usePreparedSelectBlade ($query);
2267 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2268 {
2269 $object_id = $row['object_id'];
2270 $attr_id = $row['attr_id'];
2271 if (!array_key_exists ($object_id, $ret))
2272 $ret[$object_id] = array();
2273
2274 $record = array();
2275 $record['id'] = $row['attr_id'];
2276 $record['name'] = $row['attr_name'];
2277 $record['type'] = $row['attr_type'];
2278 switch ($row['attr_type'])
2279 {
2280 case 'dict':
2281 $record['chapter_id'] = $row['chapter_id'];
2282 $record['chapter_name'] = $row['chapter_name'];
2283 $record['key'] = $row['uint_value'];
2284 // fall through
2285 case 'uint':
2286 case 'float':
2287 case 'string':
2288 $record['value'] = $row[$row['attr_type'] . '_value'];
2289 $record['o_value'] = parseWikiLink ($record['value'], 'o');
2290 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2291 break;
2292 default:
2293 $record['value'] = NULL;
2294 break;
2295 }
2296 $ret[$object_id][$attr_id] = $record;
2297 }
2298 return $ret;
2299 }
2300
2301 // This function returns all optional attributes for requested object
2302 // as an array of records.
2303 // Empty array is returned, if there are no attributes found.
2304 function getAttrValues ($object_id)
2305 {
2306 global $object_attribute_cache;
2307 if (isset ($object_attribute_cache[$object_id]))
2308 return $object_attribute_cache[$object_id];
2309
2310 $ret = fetchAttrsForObjects(array($object_id));
2311 $attrs = array();
2312 if (isset ($ret[$object_id]))
2313 {
2314 $attrs = $ret[$object_id];
2315 $object_attribute_cache[$object_id] = $attrs;
2316 }
2317 return $attrs;
2318 }
2319
2320 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2321 {
2322 return usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
2323 }
2324
2325 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2326 {
2327 if ($object_id <= 0)
2328 throw new InvalidArgException ('$objtype_id', $objtype_id);
2329 if ($attr_id <= 0)
2330 throw new InvalidArgException ('$attr_id', $attr_id);
2331 if (!strlen ($value))
2332 return commitResetAttrValue ($object_id, $attr_id);
2333 $result = usePreparedSelectBlade ('select type as attr_type from Attribute where id = ?', array ($attr_id));
2334 $row = $result->fetch (PDO::FETCH_NUM);
2335 $attr_type = $row[0];
2336 unset ($result);
2337 switch ($attr_type)
2338 {
2339 case 'uint':
2340 case 'float':
2341 case 'string':
2342 $column = $attr_type . '_value';
2343 break;
2344 case 'dict':
2345 $column = 'uint_value';
2346 break;
2347 default:
2348 throw new InvalidArgException ('$attr_type', $attr_type, 'Unknown attribute type found in object #'.$object_id.', attribute #'.$attr_id);
2349 }
2350 usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
2351 // We know $value isn't empty here.
2352 usePreparedInsertBlade
2353 (
2354 'AttributeValue',
2355 array
2356 (
2357 $column => $value,
2358 'object_id' => $object_id,
2359 'attr_id' => $attr_id,
2360 )
2361 );
2362 return TRUE;
2363 }
2364
2365 function convertPDOException ($e)
2366 {
2367 switch ($e->getCode() . '-' . $e->errorInfo[1])
2368 {
2369 case '23000-1062':
2370 $text = 'such record already exists';
2371 break;
2372 case '23000-1205':
2373 $text = 'such record already exists';
2374 break;
2375 case '23000-1451':
2376 case '23000-1452':
2377 $text = 'foreign key violation';
2378 break;
2379 case 'HY000-1205':
2380 $text = 'lock wait timeout';
2381 break;
2382 default:
2383 return $e;
2384 }
2385 return new RTDatabaseError ($text);
2386 }
2387
2388 // This is a swiss-knife blade to insert a record into a table.
2389 // The first argument is table name.
2390 // The second argument is an array of "name" => "value" pairs.
2391 function usePreparedInsertBlade ($tablename, $columns)
2392 {
2393 global $dbxlink;
2394 $query = "INSERT INTO ${tablename} (" . implode (', ', array_keys ($columns));
2395 $query .= ') VALUES (' . questionMarks (count ($columns)) . ')';
2396 // Now the query should be as follows:
2397 // INSERT INTO table (c1, c2, c3) VALUES (?, ?, ?)
2398 try
2399 {
2400 $prepared = $dbxlink->prepare ($query);
2401 if (!$prepared->execute (array_values ($columns)))
2402 return FALSE;
2403 return $prepared->rowCount() == 1;
2404 }
2405 catch (PDOException $e)
2406 {
2407 throw convertPDOException ($e);
2408 }
2409 }
2410
2411 // This swiss-knife blade deletes any number of records from the specified table
2412 // using the specified key names and values.
2413 function usePreparedDeleteBlade ($tablename, $columns, $conjunction = 'AND')
2414 {
2415 global $dbxlink;
2416 $conj = '';
2417 $query = "DELETE FROM ${tablename} WHERE ";
2418 foreach ($columns as $colname => $colvalue)
2419 {
2420 $query .= " ${conj} ${colname}=?";
2421 $conj = $conjunction;
2422 }
2423 try
2424 {
2425 $prepared = $dbxlink->prepare ($query);
2426 if (!$prepared->execute (array_values ($columns)))
2427 return FALSE;
2428 return $prepared->rowCount(); // FALSE !== 0
2429 }
2430 catch (PDOException $e)
2431 {
2432 throw convertPDOException ($e);
2433 }
2434 }
2435
2436 function usePreparedSelectBlade ($query, $args = array())
2437 {
2438 global $dbxlink;
2439 $prepared = $dbxlink->prepare ($query);
2440 try
2441 {
2442 if (!$prepared->execute ($args))
2443 return FALSE;
2444 return $prepared;
2445 }
2446 catch (PDOException $e)
2447 {
2448 throw convertPDOException ($e);
2449 }
2450 }
2451
2452 function usePreparedUpdateBlade ($tablename, $set_columns, $where_columns, $conjunction = 'AND')
2453 {
2454 global $dbxlink;
2455 $conj = '';
2456 $query = "UPDATE ${tablename} SET ";
2457 foreach (array_keys ($set_columns) as $colname)
2458 {
2459 $query .= "${conj}${colname}=?";
2460 $conj = ', ';
2461 }
2462 $conj = '';
2463 $query .= ' WHERE ';
2464 foreach (array_keys ($where_columns) as $colname)
2465 {
2466 $query .= "${conj} ${colname}=?";
2467 $conj = $conjunction;
2468 }
2469 try
2470 {
2471 $prepared = $dbxlink->prepare ($query);
2472 $prepared->execute (array_merge (array_values ($set_columns), array_values ($where_columns)));
2473 }
2474 catch (PDOException $e)
2475 {
2476 throw convertPDOException ($e);
2477 }
2478 }
2479
2480 // Prepare and execute the statement with parameters, then return number of
2481 // rows affected (or FALSE in case of an error).
2482 function usePreparedExecuteBlade ($query, $args = array())
2483 {
2484 global $dbxlink;
2485 try
2486 {
2487 if (!$prepared = $dbxlink->prepare ($query))
2488 return FALSE;
2489 if (!$prepared->execute ($args))
2490 return FALSE;
2491 return $prepared->rowCount();
2492 }
2493 catch (PDOException $e)
2494 {
2495 throw convertPDOException ($e);
2496 }
2497 }
2498
2499 function loadConfigCache ()
2500 {
2501 $result = usePreparedSelectBlade ('SELECT varname, varvalue, vartype, is_hidden, emptyok, description, is_userdefined FROM Config ORDER BY varname');
2502 $cache = array();
2503 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2504 $cache[$row['varname']] = $row;
2505 return $cache;
2506 }
2507
2508 function loadUserConfigCache ($username = NULL)
2509 {
2510 if (!strlen ($username))
2511 throw new InvalidArgException ('$username', $username);
2512 $result = usePreparedSelectBlade ('SELECT varname, varvalue FROM UserConfig WHERE user = ?', array ($username));
2513 $cache = array();
2514 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2515 $cache[$row['varname']] = $row;
2516 return $cache;
2517 }
2518
2519 // Database version detector. Should behave corretly on any
2520 // working dataset a user might have.
2521 function getDatabaseVersion ()
2522 {
2523 $result = usePreparedSelectBlade ('SELECT varvalue FROM Config WHERE varname = "DB_VERSION" and vartype = "string"');
2524 if ($result == NULL)
2525 {
2526 // FIXME: this code is never executed, but an exception thrown instead
2527 global $dbxlink;
2528 $errorInfo = $dbxlink->errorInfo();
2529 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2530 return '0.14.4';
2531 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
2532 }
2533 $rows = $result->fetchAll (PDO::FETCH_NUM);
2534 unset ($result);
2535 if (count ($rows) != 1 || !strlen ($rows[0][0]))
2536 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2537 $ret = $rows[0][0];
2538 return $ret;
2539 }
2540
2541 // Return an array of virtual services. For each of them list real server pools
2542 // with their load balancers and other stats.
2543 function getSLBSummary ()
2544 {
2545 $result = usePreparedSelectBlade
2546 (
2547 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2548 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2549 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2550 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2551 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
2552 'group by vs.id, object_id order by vs.vip, object_id'
2553 );
2554 $ret = array();
2555 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2556 {
2557 $vsid = $row['vsid'];
2558 $object_id = $row['object_id'];
2559 if (!isset ($ret[$vsid]))
2560 {
2561 $ret[$vsid] = array();
2562 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2563 $ret[$vsid][$cname] = $row[$cname];
2564 $ret[$vsid]['lblist'] = array();
2565 }
2566 // There's only one assigned RS pool possible for each LB-VS combination.
2567 $ret[$vsid]['lblist'][$row['object_id']] = array
2568 (
2569 'id' => $row['rspool_id'],
2570 'size' => $row['rscount'],
2571 'name' => $row['pool_name']
2572 );
2573 }
2574 return $ret;
2575 }
2576
2577 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2578 {
2579 return usePreparedExecuteBlade
2580 (
2581 'INSERT INTO IPv4RS (rsip, rsport, rspool_id, inservice, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?)',
2582 array
2583 (
2584 $rsip,
2585 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2586 $pool_id,
2587 $inservice == 'yes' ? 'yes' : 'no',
2588 !strlen ($rsconfig) ? NULL : $rsconfig
2589 )
2590 );
2591 }
2592
2593 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '', $prio = '')
2594 {
2595 return usePreparedInsertBlade
2596 (
2597 'IPv4LB',
2598 array
2599 (
2600 'object_id' => $object_id,
2601 'rspool_id' => $pool_id,
2602 'vs_id' => $vs_id,
2603 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2604 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig),
2605 'prio' => (!strlen ($prio) ? NULL : $prio),
2606 )
2607 );
2608 }
2609
2610 function commitDeleteVS ($id = 0)
2611 {
2612 releaseFiles ('ipv4vs', $id);
2613 return FALSE !== usePreparedDeleteBlade ('IPv4VS', array ('id' => $id)) && FALSE !== destroyTagsForEntity ('ipv4vs', $id);
2614 }
2615
2616 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2617 {
2618 if (long2ip (ip2long ($rsip)) !== $rsip)
2619 throw new InvalidArgException ('$rsip', $rsip);
2620 return usePreparedExecuteBlade
2621 (
2622 'UPDATE IPv4RS SET rsip=INET_ATON(?), rsport=?, rsconfig=? WHERE id=?',
2623 array
2624 (
2625 $rsip,
2626 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2627 !strlen ($rsconfig) ? NULL : $rsconfig,
2628 $rsid,
2629 )
2630 );
2631 }
2632
2633 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2634 {
2635 if (!strlen ($vip))
2636 throw new InvalidArgException ('$vip', $vip);
2637 if ($vport <= 0)
2638 throw new InvalidArgException ('$vport', $vport);
2639 if (!strlen ($proto))
2640 throw new InvalidArgException ('$proto', $proto);
2641 return usePreparedExecuteBlade
2642 (
2643 'UPDATE IPv4VS SET vip=INET_ATON(?), vport=?, proto=?, name=?, vsconfig=?, rsconfig=? WHERE id=?',
2644 array
2645 (
2646 $vip,
2647 $vport,
2648 $proto,
2649 !strlen ($name) ? NULL : $name,
2650 !strlen ($vsconfig) ? NULL : $vsconfig,
2651 !strlen ($rsconfig) ? NULL : $rsconfig,
2652 $vsid,
2653 )
2654 );
2655 }
2656
2657 function loadThumbCache ($rack_id = 0)
2658 {
2659 $ret = NULL;
2660 $result = usePreparedSelectBlade ("SELECT thumb_data FROM Rack WHERE id = ? AND thumb_data IS NOT NULL", array ($rack_id));
2661 $row = $result->fetch (PDO::FETCH_ASSOC);
2662 if ($row)
2663 $ret = base64_decode ($row['thumb_data']);
2664 return $ret;
2665 }
2666
2667 // Return the list of attached RS pools for the given object. As long as we have
2668 // the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
2669 // by vs_id, because there will be only one RS pool listed for each VS of the
2670 // current object.
2671 function getRSPoolsForObject ($object_id = 0)
2672 {
2673 $result = usePreparedSelectBlade
2674 (
2675 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2676 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig, lb.prio from ' .
2677 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2678 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2679 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2680 'where lb.object_id = ? ' .
2681 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name',
2682 array ($object_id)
2683 );
2684 $ret = array ();
2685 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2686 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig', 'prio') as $cname)
2687 $ret[$row['vs_id']][$cname] = $row[$cname];
2688 return $ret;
2689 }
2690
2691 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2692 {
2693 usePreparedInsertBlade
2694 (
2695 'IPv4RSPool',
2696 array
2697 (
2698 'name' => (!strlen ($name) ? NULL : $name),
2699 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2700 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
2701 )
2702 );
2703 produceTagsForLastRecord ('ipv4rspool', $taglist);
2704 }
2705
2706 function commitDeleteRSPool ($pool_id = 0)
2707 {
2708 releaseFiles ('ipv4rspool', $pool_id);
2709 return usePreparedDeleteBlade ('IPv4RSPool', array ('id' => $pool_id)) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2710 }
2711
2712 function getRSList ()
2713 {
2714 $result = usePreparedSelectBlade
2715 (
2716 "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2717 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport"
2718 );
2719 $ret = array ();
2720 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2721 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2722 $ret[$row['id']][$cname] = $row[$cname];
2723 return $ret;
2724 }
2725
2726 // Return the list of all currently configured load balancers with their pool count.
2727 function getLBList ()
2728 {
2729 $result = usePreparedSelectBlade
2730 (
2731 "select object_id, count(rspool_id) as poolcount " .
2732 "from IPv4LB group by object_id order by object_id"
2733 );
2734 $ret = array ();
2735 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2736 $ret[$row['object_id']] = $row['poolcount'];
2737 return $ret;
2738 }
2739
2740 // For the given object return: its vsconfig/rsconfig; the list of RS pools
2741 // attached (each with vsconfig/rsconfig in turn), each with the list of
2742 // virtual services terminating the pool. Each pool also lists all real
2743 // servers with rsconfig.
2744 function getSLBConfig ($object_id)
2745 {
2746 $ret = array();
2747 $result = usePreparedSelectBlade
2748 (
2749 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2750 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2751 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, lb.prio as prio, pool.id as pool_id, pool.name as pool_name, ' .
2752 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2753 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2754 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2755 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2756 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2757 "where lb.object_id = ? and rs.inservice = 'yes' " .
2758 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport",
2759 array ($object_id)
2760 );
2761 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2762 {
2763 $vs_id = $row['vs_id'];
2764 if (!isset ($ret[$vs_id]))
2765 {
2766 foreach (array ('vip', 'vport', 'proto', 'vs_name', 'vs_vsconfig', 'vs_rsconfig', 'lb_vsconfig', 'lb_rsconfig', 'pool_vsconfig', 'pool_rsconfig', 'pool_id', 'pool_name', 'prio') as $c)
2767 $ret[$vs_id][$c] = $row[$c];
2768 $ret[$vs_id]['rslist'] = array();
2769 }
2770 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2771 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2772 }
2773 return $ret;
2774 }
2775
2776 function commitUpdateSLBDefConf ($data)
2777 {
2778 return saveScript('DefaultVSConfig', $data['vs']) &&
2779 saveScript('DefaultRSConfig', $data['rs']);
2780 }
2781
2782 function getSLBDefaults ($do_cache_result = FALSE) {
2783 static $ret = array();
2784
2785 if (! $do_cache_result)
2786 $ret = array();
2787 elseif (! empty ($ret))
2788 return $ret;
2789
2790 $ret['vs'] = loadScript('DefaultVSConfig');
2791 $ret['rs'] = loadScript('DefaultRSConfig');
2792 return $ret;
2793 }
2794
2795 function commitSetInService ($rs_id = 0, $inservice = '')
2796 {
2797 if (! in_array ($inservice, array ('yes', 'no')))
2798 throw new InvalidArgException ('$inservice', $inservice);
2799 return usePreparedUpdateBlade ('IPv4RS', array ('inservice' => $inservice), array ('id' => $rs_id));
2800 }
2801
2802 function executeAutoPorts ($object_id = 0, $type_id = 0)
2803 {
2804 if ($object_id == 0)
2805 throw new InvalidArgException ('$object_id', $object_id);
2806 if ($type_id == 0)
2807 throw new InvalidArgException ('$type_id', $type_id);
2808 foreach (getAutoPorts ($type_id) as $autoport)
2809 commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2810 }
2811
2812 // Return only implicitly listed tags, the rest of the chain will be
2813 // generated/deducted later at higher levels.
2814 // Result is a chain: randomly indexed taginfo list.
2815 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2816 {
2817 $ret = array();
2818 $result = usePreparedSelectBlade
2819 (
2820 "select tt.id, tag from " .
2821 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2822 "where entity_realm = ? and entity_id = ? " .
2823 "order by tt.tag",
2824 array ($entity_realm, $entity_id)
2825 );
2826 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2827 $ret[$row['id']] = $row;
2828 return getExplicitTagsOnly ($ret);
2829 }
2830
2831 // Return a tag chain with all DB tags on it.
2832 function getTagList ()
2833 {
2834 $ret = array();
2835 $result = usePreparedSelectBlade
2836 (
2837 "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
2838 "from TagTree left join TagStorage on id = tag_id " .
2839 "group by id, entity_realm order by tag"
2840 );
2841 // Collation index. The resulting rows are ordered according to default collation,
2842 // which is utf8_general_ci for UTF-8.
2843 $ci = 0;
2844 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2845 {
2846 if (!isset ($ret[$row['id']]))
2847 $ret[$row['id']] = array
2848 (
2849 'id' => $row['id'],
2850 'tag' => $row['tag'],
2851 'ci' => $ci++,
2852 'parent_id' => $row['parent_id'],
2853 'refcnt' => array ('total' => 0)
2854 );
2855 if ($row['realm'])
2856 {
2857 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2858 $ret[$row['id']]['refcnt']['total'] += $row['refcnt'];
2859 // introduce the 'pseudo'-ream 'ipnet' which combines 'ipv4net' and 'ipv6net' realms.
2860 if ($row['realm'] == 'ipv4net' || $row['realm'] == 'ipv6net')
2861 if (isset ($ret[$row['id']]['refcnt']['ipnet']))
2862 $ret[$row['id']]['refcnt']['ipnet'] += $row['refcnt'];
2863 else
2864 $ret[$row['id']]['refcnt']['ipnet'] = $row['refcnt'];
2865 }
2866 }
2867 return $ret;
2868 }
2869
2870 // Drop the whole chain stored.
2871 function destroyTagsForEntity ($entity_realm, $entity_id)
2872 {
2873 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id));
2874 }
2875
2876 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2877 // FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
2878 // but not now.
2879 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2880 {
2881 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id, 'tag_id' => $tag_id));
2882 }
2883
2884 // Push a record into TagStorage unconditionally.
2885 function addTagForEntity ($realm, $entity_id, $tag_id)
2886 {
2887 global $SQLSchema;
2888 if (! array_key_exists ($realm, $SQLSchema))
2889 throw new InvalidArgException ('realm', $realm);
2890 // spotEntity ($realm, $entity_id) would be a more expensive way
2891 // to validate two parameters
2892 return usePreparedInsertBlade
2893 (
2894 'TagStorage',
2895 array
2896 (
2897 'entity_realm' => $realm,
2898 'entity_id' => $entity_id,
2899 'tag_id' => $tag_id,
2900 )
2901 );
2902 }
2903
2904 // Add records into TagStorage, if this makes sense (IOW, they don't appear
2905 // on the implicit list already). Then remove any other records, which
2906 // appear on the "implicit" side of the chain. This will make sure,
2907 // that both the tag base is still minimal and all requested tags appear on
2908 // the resulting tag chain.
2909 // Return TRUE, if any changes were committed.
2910 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2911 {
2912 // Put the current explicit sub-chain into a buffer and merge all tags from
2913 // the extra chain, which aren't there yet.
2914 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2915 foreach ($extrachain as $extratag)
2916 if (!tagOnChain ($extratag, $newchain))
2917 $newchain[] = $extratag;
2918 // Then minimize the working buffer and check if it differs from the original
2919 // chain we started with. If it is so, save the work and signal the upper layer.
2920 $newchain = getExplicitTagsOnly ($newchain);
2921 if (tagChainCmp ($oldchain, $newchain))
2922 {
2923 destroyTagsForEntity ($realm, $entity_id);
2924 foreach ($newchain as $taginfo)
2925 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2926 return TRUE;
2927 }
2928 return FALSE;
2929 }
2930
2931 // Presume, that the target record has no tags attached.
2932 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
2933 {
2934 if (!$last_insert_id)
2935 $last_insert_id = lastInsertID();
2936 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
2937 addTagForEntity ($realm, $last_insert_id, $taginfo['id']);
2938 }
2939
2940 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2941 {
2942 // $range is in x.x.x.x/x format, split into ip/mask vars
2943 $rangeArray = explode('/', $range);
2944 if (count ($rangeArray) != 2)
2945 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv4 prefix');
2946 $ip = $rangeArray[0];
2947 $mask = $rangeArray[1];
2948
2949 if (!strlen ($ip) or !strlen ($mask))
2950 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv4 prefix');
2951 $ipL = ip2long($ip);
2952 $maskL = ip2long($mask);
2953 if ($ipL == -1 || $ipL === FALSE)
2954 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv4 address');
2955 if ($mask < 32 && $mask > 0)
2956 $maskL = $mask;
2957 else
2958 {
2959 $maskB = decbin($maskL);
2960 if (strlen($maskB)!=32)
2961 throw new InvalidRequestArgException ('range', $range, 'Invalid netmask');
2962 $ones=0;
2963 $zeroes=FALSE;
2964 foreach( str_split ($maskB) as $digit)
2965 {
2966 if ($digit == '0')
2967 $zeroes = TRUE;
2968 if ($digit == '1')
2969 {
2970 $ones++;
2971 if ($zeroes == TRUE)
2972 throw new InvalidRequestArgException ('range', $range, 'Invalid netmask');
2973 }
2974 }
2975 $maskL = $ones;
2976 }
2977 $binmask = binMaskFromDec($maskL);
2978 $ipL = $ipL & $binmask;
2979 usePreparedInsertBlade
2980 (
2981 'IPv4Network',
2982 array
2983 (
2984 'ip' => sprintf ('%u', $ipL),
2985 'mask' => $maskL,
2986 'name' => $name
2987 )
2988 );
2989
2990 if ($is_bcast and $maskL < 31)
2991 {
2992 $network_addr = long2ip ($ipL);
2993 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
2994 updateV4Address ($network_addr, 'network', 'yes');
2995 updateV4Address ($broadcast_addr, 'broadcast', 'yes');
2996 }
2997 produceTagsForLastRecord ('ipv4net', $taglist);
2998 }
2999
3000 function createIPv6Prefix ($range = '', $name = '', $taglist = array())
3001 {
3002 // $range is in aaa0:b::c:d/x format, split into ip/mask vars
3003 $rangeArray = explode ('/', $range);
3004 if (count ($rangeArray) != 2)
3005 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv6 prefix');
3006 $ip = $rangeArray[0];
3007 $mask = $rangeArray[1];
3008 $address = new IPv6Address;
3009 if (!strlen ($ip) or !strlen ($mask) or ! $address->parse ($ip))
3010 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv4 prefix');
3011 $network_addr = $address->get_first_subnet_address ($mask);
3012 $broadcast_addr = $address->get_last_subnet_address ($mask);
3013 if (! $network_addr || ! $broadcast_addr)
3014 throw new InvalidRequestArgException ('range', $range, 'Invalid netmask');
3015 usePreparedInsertBlade
3016 (
3017 'IPv6Network',
3018 array
3019 (
3020 'ip' => $network_addr,
3021 'last_ip' => $broadcast_addr,
3022 'mask' => $mask,
3023 'name' => $name
3024 )
3025 );
3026 produceTagsForLastRecord ('ipv6net', $taglist);
3027 }
3028
3029 // FIXME: This function doesn't wipe relevant records from IPv4Address table.
3030 function destroyIPv4Prefix ($id)
3031 {
3032 releaseFiles ('ipv4net', $id);
3033 usePreparedDeleteBlade ('IPv4Network', array ('id' => $id));
3034 destroyTagsForEntity ('ipv4net', $id);
3035 }
3036
3037 // FIXME: This function doesn't wipe relevant records from IPv6Address table.
3038 function destroyIPv6Prefix ($id)
3039 {
3040 releaseFiles ('ipv6net', $id);
3041 usePreparedDeleteBlade ('IPv6Network', array ('id' => $id));
3042 destroyTagsForEntity ('ipv6net', $id);
3043 }
3044
3045 function loadScript ($name)
3046 {
3047 $result = usePreparedSelectBlade ("select script_text from Script where script_name = ?", array ($name));
3048 $row = $result->fetch (PDO::FETCH_NUM);
3049 if ($row !== FALSE)
3050 return $row[0];
3051 else
3052 return NULL;
3053 }
3054
3055 function saveScript ($name = '', $text)
3056 {
3057 if (!strlen ($name))
3058 throw new InvalidArgException ('$name', $name);
3059 return usePreparedExecuteBlade
3060 (
3061 'INSERT INTO Script (script_name, script_text) VALUES (?, ?) ' .
3062 'ON DUPLICATE KEY UPDATE script_text=?',
3063 array ($name, $text, $text)
3064 );
3065 }
3066
3067 function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3068 {
3069 if (NULL === getIPv4AddressNetworkId ($localip))
3070 return "$localip: Non existant ip";
3071 if (NULL === getIPv4AddressNetworkId ($remoteip))
3072 return "$remoteip: Non existant ip";
3073 if ( ($localport <= 0) or ($localport >= 65536) )
3074 return "$localport: invaild port";
3075 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3076 return "$remoteport: invaild port";
3077
3078 $result = usePreparedExecuteBlade
3079 (
3080 'INSERT INTO IPv4NAT (object_id, localip, remoteip, localport, remoteport, proto, description) ' .
3081 'VALUES (?, INET_ATON(?), INET_ATON(?), ?, ?, ?, ?)',
3082 array
3083 (
3084 $object_id,
3085 $localip,
3086 $remoteip,
3087 $localport,
3088 $remoteport,
3089 $proto,
3090 $description,
3091 )
3092 );
3093 return $result !== FALSE ? '' : (__FUNCTION__ . '(): failed to insert the rule');
3094 }
3095
3096 function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3097 {
3098 return usePreparedExecuteBlade
3099 (
3100 'DELETE FROM IPv4NAT WHERE object_id=? AND localip=INET_ATON(?) AND ' .
3101 'remoteip=INET_ATON(?) AND localport=? AND remoteport=? AND proto=?',
3102 array ($object_id, $localip, $remoteip, $localport, $remoteport, $proto)
3103 );
3104 }
3105
3106 function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3107 {
3108 return usePreparedExecuteBlade
3109 (
3110 'UPDATE IPv4NAT SET description=? WHERE object_id=? AND localip=INET_ATON(?) AND remoteip=INET_ATON(?) ' .
3111 'AND localport=? AND remoteport=? AND proto=?',
3112 array ($description, $object_id, $localip, $remoteip, $localport, $remoteport, $proto)
3113 );
3114 }
3115
3116 function getNATv4ForObject ($object_id)
3117 {
3118 $ret = array();
3119 $ret['out'] = array();
3120 $ret['in'] = array();
3121 $result = usePreparedSelectBlade
3122 (
3123 "select ".
3124 "proto, ".
3125 "INET_NTOA(localip) as localip, ".
3126 "localport, ".
3127 "INET_NTOA(remoteip) as remoteip, ".
3128 "remoteport, ".
3129 "ipa1.name as local_addr_name, " .
3130 "ipa2.name as remote_addr_name, " .
3131 "description ".
3132 "from IPv4NAT ".
3133 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
3134 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
3135 "where object_id=? ".
3136 "order by localip, localport, proto, remoteip, remoteport",
3137 array ($object_id)
3138 );
3139 $count=0;
3140 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3141 {
3142 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3143 $ret['out'][$count][$cname] = $row[$cname];
3144 $count++;
3145 }
3146 unset ($result);
3147
3148 $result = usePreparedSelectBlade
3149 (
3150 "select ".
3151 "proto, ".
3152 "INET_NTOA(localip) as localip, ".
3153 "localport, ".
3154 "INET_NTOA(remoteip) as remoteip, ".
3155 "remoteport, ".
3156 "IPv4NAT.object_id as object_id, ".
3157 "RackObject.name as object_name, ".
3158 "description ".
3159 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
3160 "where IPv4Allocation.object_id=? ".
3161 "order by remoteip, remoteport, proto, localip, localport",
3162 array ($object_id)
3163 );
3164 $count=0;
3165 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3166 {
3167 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3168 $ret['in'][$count][$cname] = $row[$cname];
3169 $count++;
3170 }
3171 return $ret;
3172 }
3173
3174 // Return a list of files, which are not linked to the specified record. This list
3175 // will be used by printSelect().
3176 function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3177 {
3178 $query = usePreparedSelectBlade
3179 (
3180 'SELECT id, name FROM File ' .
3181 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
3182 'ORDER BY name, id',
3183 array ($entity_type, $entity_id)
3184 );
3185 $ret=array();
3186 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3187 $ret[$row['id']] = $row['name'];
3188 return $ret;
3189 }
3190
3191 // FIXME: return a standard cell list, so upper layer can iterate over
3192 // it conveniently.
3193 function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3194 {
3195 $query = usePreparedSelectBlade
3196 (
3197 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3198 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3199 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name',
3200 array ($entity_type, $entity_id)
3201 );
3202 $ret = array();
3203 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3204 $ret[$row['file_id']] = array (
3205 'id' => $row['file_id'],
3206 'link_id' => $row['link_id'],
3207 'name' => $row['name'],
3208 'type' => $row['type'],
3209 'size' => $row['size'],
3210 'ctime' => $row['ctime'],
3211 'mtime' => $row['mtime'],
3212 'atime' => $row['atime'],
3213 'comment' => $row['comment'],
3214 );
3215 return $ret;
3216 }
3217
3218 function getFile ($file_id)
3219 {
3220 $query = usePreparedSelectBlade
3221 (
3222 'SELECT id, name, type, size, ctime, mtime, atime, contents, comment ' .
3223 'FROM File WHERE id = ?',
3224 array ($file_id)
3225 );
3226 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3227 // FIXME: isn't this repeating the code already in spotEntity()?
3228 throw new EntityNotFoundException ('file', $file_id);
3229 else
3230 {
3231 $ret = array();
3232 $ret['id'] = $row['id'];
3233 $ret['name'] = $row['name'];
3234 $ret['type'] = $row['type'];
3235 $ret['size'] = $row['size'];
3236 $ret['ctime'] = $row['ctime'];
3237 $ret['mtime'] = $row['mtime'];
3238 $ret['atime'] = $row['atime'];
3239 $ret['contents'] = $row['contents'];
3240 $ret['comment'] = $row['comment'];
3241 unset ($query);
3242
3243 // Someone accessed this file, update atime
3244 usePreparedExecuteBlade ('UPDATE File SET atime = NOW() WHERE id = ?', array ($file_id));
3245 }
3246 return $ret;
3247 }
3248
3249 function getFileCache ($file_id)
3250 {
3251 $query = usePreparedSelectBlade
3252 (
3253 'SELECT File.thumbnail FROM File ' .
3254 'WHERE File.id = ? and File.thumbnail IS NOT NULL',
3255 array ($file_id)
3256 );
3257 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3258 return FALSE;
3259 $ret = $row['thumbnail'];
3260 $query->CloseCursor();
3261 usePreparedExecuteBlade ('UPDATE File SET atime = NOW() WHERE id = ?', array ($file_id));
3262 return $ret;
3263 }
3264
3265 function commitAddFileCache ($file_id, $contents)
3266 {
3267 global $dbxlink;
3268 $query = $dbxlink->prepare('UPDATE File SET thumbnail = ? WHERE id = ?');
3269 $query->bindParam(1, $contents, PDO::PARAM_LOB);
3270 $query->bindParam(2, $file_id);
3271 try
3272 {
3273 return $query->execute();
3274 }
3275 catch (PDOException $e)
3276 {
3277 throw convertPDOException ($e);
3278 }
3279 }
3280
3281 function getFileLinks ($file_id)
3282 {
3283 $query = usePreparedSelectBlade
3284 (
3285 'SELECT id, file_id, entity_type, entity_id FROM FileLink ' .
3286 'WHERE file_id = ? ORDER BY entity_type, entity_id',
3287 array ($file_id)
3288 );
3289 $rows = $query->fetchAll (PDO::FETCH_ASSOC);
3290 $ret = array();
3291 foreach ($rows as $row)
3292 {
3293 // get info of the parent
3294 switch ($row['entity_type'])
3295 {
3296 case 'ipv4net': case 'ipv6net':
3297 $page = $row['entity_type'];
3298 $id_name = 'id';
3299 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3300 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3301 break;
3302 case 'ipv4rspool':
3303 $page = 'ipv4rspool';
3304 $id_name = 'pool_id';
3305 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3306 $name = $parent['name'];
3307 break;
3308 case 'ipv4vs':
3309 $page = 'ipv4vs';
3310 $id_name = 'vs_id';
3311 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3312 $name = $parent['name'];
3313 break;
3314 case 'object':
3315 $page = 'object';
3316 $id_name = 'object_id';
3317 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3318 $name = $parent['dname'];
3319 break;
3320 case 'rack':
3321 $page = 'rack';
3322 $id_name = 'rack_id';
3323 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3324 $name = $parent['name'];
3325 break;
3326 case 'user':
3327 $page = 'user';
3328 $id_name = 'user_id';
3329 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3330 $name = $parent['user_name'];
3331 break;
3332 }
3333
3334 // name needs to have some value for hrefs to work
3335 if (!strlen ($name))
3336 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3337
3338 $ret[$row['id']] = array(
3339 'page' => $page,
3340 'id_name' => $id_name,
3341 'entity_type' => $row['entity_type'],
3342 'entity_id' => $row['entity_id'],
3343 'name' => $name
3344 );
3345 }
3346 return $ret;
3347 }
3348
3349 function getFileStats ()
3350 {
3351 $result = usePreparedSelectBlade ('SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type');
3352 $ret = array();
3353 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3354 if ($row['count'] > 0)
3355 $ret["Links in realm '${row['entity_type']}'"] = $row['count'];
3356 unset ($result);
3357
3358 // Find number of files without any linkage
3359 $result = usePreparedSelectBlade
3360 (
3361 'SELECT COUNT(*) ' .
3362 'FROM File ' .
3363 'WHERE id NOT IN (SELECT file_id FROM FileLink)'
3364 );
3365 $ret["Unattached files"] = $result->fetchColumn ();