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