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