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