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