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