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