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