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