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