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