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