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