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