r2001 + finally stick with "tag chain" term
[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 escapeString ($value, $do_db_escape = TRUE)
9 {
10 $ret = htmlentities ($value, ENT_QUOTES, 'UTF-8');
11 if ($do_db_escape)
12 {
13 global $dbxlink;
14 $ret = substr ($dbxlink->quote ($ret), 1, -1);
15 }
16 return $ret;
17 }
18
19 function getRackspace ($tagfilter = array())
20 {
21 $whereclause = getWhereClause ($tagfilter);
22 $query =
23 "select dict_key as row_id, dict_value as row_name " .
24 "from Chapter natural join Dictionary left join Rack on Rack.row_id = dict_key " .
25 "left join TagStorage on Rack.id = TagStorage.target_id and target_realm = 'rack' " .
26 "where chapter_name = 'RackRow' " .
27 $whereclause .
28 " order by dict_value";
29 $result = useSelectBlade ($query, __FUNCTION__);
30 $ret = array();
31 $clist = array ('row_id', 'row_name');
32 while ($row = $result->fetch (PDO::FETCH_ASSOC))
33 foreach ($clist as $cname)
34 $ret[$row['row_id']][$cname] = $row[$cname];
35 $result->closeCursor();
36 return $ret;
37 }
38
39 // Return detailed information about one rack row.
40 function getRackRowInfo ($rackrow_id)
41 {
42 $query =
43 "select dict_key as id, dict_value as name, count(Rack.id) as count, " .
44 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
45 "from Chapter natural join Dictionary left join Rack on Rack.row_id = dict_key " .
46 "where chapter_name = 'RackRow' and dict_key = ${rackrow_id} " .
47 "group by dict_key";
48 $result = useSelectBlade ($query, __FUNCTION__);
49 if ($row = $result->fetch (PDO::FETCH_ASSOC))
50 return $row;
51 else
52 return NULL;
53 }
54
55 // This function returns id->name map for all object types. The map is used
56 // to build <select> input for objects.
57 function getObjectTypeList ()
58 {
59 return readChapter ('RackObjectType');
60 }
61
62 // Return a part of SQL query suitable for embeding into a bigger text.
63 // The returned result should list all tag IDs shown in the tag filter.
64 function getWhereClause ($tagfilter = array())
65 {
66 $whereclause = '';
67 if (count ($tagfilter))
68 {
69 $whereclause .= ' and (';
70 $orclause = '';
71 foreach ($tagfilter as $tag_id)
72 {
73 $whereclause .= $orclause . 'tag_id = ' . $tag_id;
74 $orclause = ' or ';
75 }
76 $whereclause .= ') ';
77 }
78 return $whereclause;
79 }
80
81 function getObjectList ($type_id = 0, $tagfilter = array())
82 {
83 $whereclause = getWhereClause ($tagfilter);
84 if ($type_id != 0)
85 $whereclause .= " and objtype_id = '${type_id}' ";
86 $query =
87 "select distinct RackObject.id as id , RackObject.name as name, dict_value as objtype_name, " .
88 "RackObject.label as label, RackObject.barcode as barcode, " .
89 "dict_key as objtype_id, asset_no, rack_id, Rack.name as Rack_name from " .
90 "((RackObject inner join Dictionary on objtype_id=dict_key natural join Chapter) " .
91 "left join RackSpace on RackObject.id = object_id) " .
92 "left join Rack on rack_id = Rack.id " .
93 "left join TagStorage on RackObject.id = TagStorage.target_id and target_realm = 'object' " .
94 "where RackObject.deleted = 'no' and chapter_name = 'RackObjectType' " .
95 $whereclause .
96 "order by name";
97 $result = useSelectBlade ($query, __FUNCTION__);
98 $ret = array();
99 while ($row = $result->fetch (PDO::FETCH_ASSOC))
100 {
101 foreach (array (
102 'id',
103 'name',
104 'label',
105 'barcode',
106 'objtype_name',
107 'objtype_id',
108 'asset_no',
109 'rack_id',
110 'Rack_name'
111 ) as $cname)
112 $ret[$row['id']][$cname] = $row[$cname];
113 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
114 }
115 $result->closeCursor();
116 return $ret;
117 }
118
119 function getRacksForRow ($row_id = 0, $tagfilter = array())
120 {
121 $query =
122 "select Rack.id, Rack.name, height, Rack.comment, row_id, " .
123 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name " .
124 "from Rack left join Dictionary on row_id = dict_key natural join Chapter " .
125 "left join TagStorage on Rack.id = TagStorage.target_id and target_realm = 'rack' " .
126 "where chapter_name = 'RackRow' and Rack.deleted = 'no' " .
127 (($row_id == 0) ? "" : "and row_id = ${row_id} ") .
128 getWhereClause ($tagfilter) .
129 " order by row_name, Rack.id";
130 $result = useSelectBlade ($query, __FUNCTION__);
131 $ret = array();
132 $clist = array
133 (
134 'id',
135 'name',
136 'height',
137 'comment',
138 'row_id',
139 'left_is_front',
140 'bottom_is_unit1',
141 'row_name'
142 );
143 while ($row = $result->fetch (PDO::FETCH_ASSOC))
144 foreach ($clist as $cname)
145 $ret[$row['id']][$cname] = $row[$cname];
146 $result->closeCursor();
147 usort ($ret, 'sortRacks');
148 $ret = restoreRackIDs ($ret);
149 return $ret;
150 }
151
152 // This is a popular helper for getting information about
153 // a particular rack and its rackspace at once.
154 function getRackData ($rack_id = 0, $silent = FALSE)
155 {
156 if ($rack_id == 0)
157 {
158 if ($silent == FALSE)
159 showError ('Invalid rack_id', __FUNCTION__);
160 return NULL;
161 }
162 $query =
163 "select Rack.id, Rack.name, row_id, height, Rack.comment, " .
164 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name from " .
165 "Rack left join Dictionary on Rack.row_id = dict_key natural join Chapter " .
166 "where chapter_name = 'RackRow' and Rack.id='${rack_id}' and Rack.deleted = 'no' limit 1";
167 $result = useSelectBlade ($query, __FUNCTION__);
168 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
169 {
170 if ($silent == FALSE)
171 showError ('Query #1 succeded, but returned no data', __FUNCTION__);
172 return NULL;
173 }
174
175 // load metadata
176 $clist = array
177 (
178 'id',
179 'name',
180 'height',
181 'comment',
182 'row_id',
183 'left_is_front',
184 'bottom_is_unit1',
185 'row_name'
186 );
187 foreach ($clist as $cname)
188 $rack[$cname] = $row[$cname];
189 $result->closeCursor();
190 unset ($result);
191
192 // start with default rackspace
193 for ($i = $rack['height']; $i > 0; $i--)
194 for ($locidx = 0; $locidx < 3; $locidx++)
195 $rack[$i][$locidx]['state'] = 'F';
196
197 // load difference
198 $query =
199 "select unit_no, atom, state, object_id " .
200 "from RackSpace where rack_id = ${rack_id} and " .
201 "unit_no between 1 and " . $rack['height'] . " order by unit_no";
202 $result = useSelectBlade ($query, __FUNCTION__);
203 global $loclist;
204 while ($row = $result->fetch (PDO::FETCH_ASSOC))
205 {
206 $rack[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
207 $rack[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
208 }
209 $result->closeCursor();
210 return $rack;
211 }
212
213 // This is a popular helper.
214 function getObjectInfo ($object_id = 0)
215 {
216 if ($object_id == 0)
217 {
218 showError ('Invalid object_id', __FUNCTION__);
219 return;
220 }
221 $query =
222 "select id, name, label, barcode, dict_value as objtype_name, asset_no, dict_key as objtype_id, has_problems, comment from " .
223 "RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter " .
224 "where id = '${object_id}' and deleted = 'no' and chapter_name = 'RackObjectType' limit 1";
225 $result = useSelectBlade ($query, __FUNCTION__);
226 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
227 {
228 showError ('Query succeeded, but returned no data', __FUNCTION__);
229 $ret = NULL;
230 }
231 else
232 {
233 $ret['id'] = $row['id'];
234 $ret['name'] = $row['name'];
235 $ret['label'] = $row['label'];
236 $ret['barcode'] = $row['barcode'];
237 $ret['objtype_name'] = $row['objtype_name'];
238 $ret['objtype_id'] = $row['objtype_id'];
239 $ret['has_problems'] = $row['has_problems'];
240 $ret['asset_no'] = $row['asset_no'];
241 $ret['dname'] = displayedName ($ret);
242 $ret['comment'] = $row['comment'];
243 }
244 $result->closeCursor();
245 unset ($result);
246 return $ret;
247 }
248
249 function getPortTypes ()
250 {
251 return readChapter ('PortType');
252 }
253
254 function getObjectPortsAndLinks ($object_id = 0)
255 {
256 if ($object_id == 0)
257 {
258 showError ('Invalid object_id', __FUNCTION__);
259 return;
260 }
261 $query =
262 "select Port.id as Port_id, ".
263 "Port.name as Port_name, ".
264 "Port.label as Port_label, ".
265 "Port.l2address as Port_l2address, ".
266 "Port.type as Port_type, ".
267 "Port.reservation_comment as Port_reservation_comment, " .
268 "dict_value as PortType_name, ".
269 "RemotePort.id as RemotePort_id, ".
270 "RemotePort.name as RemotePort_name, ".
271 "RemotePort.object_id as RemotePort_object_id, ".
272 "RackObject.name as RackObject_name ".
273 "from (".
274 "(".
275 "(".
276 "Port inner join Dictionary on Port.type = dict_key natural join Chapter".
277 ") ".
278 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
279 ") ".
280 "left join Port as RemotePort on Link.portb=RemotePort.id or Link.porta=RemotePort.id ".
281 ") ".
282 "left join RackObject on RemotePort.object_id=RackObject.id ".
283 "where chapter_name = 'PortType' and Port.object_id=${object_id} ".
284 "and (Port.id != RemotePort.id or RemotePort.id is null) ".
285 "order by Port_name";
286 $result = useSelectBlade ($query, __FUNCTION__);
287 $ret=array();
288 $count=0;
289 while ($row = $result->fetch (PDO::FETCH_ASSOC))
290 {
291 $ret[$count]['id'] = $row['Port_id'];
292 $ret[$count]['name'] = $row['Port_name'];
293 $ret[$count]['l2address'] = l2addressFromDatabase ($row['Port_l2address']);
294 $ret[$count]['label'] = $row['Port_label'];
295 $ret[$count]['type_id'] = $row['Port_type'];
296 $ret[$count]['type'] = $row['PortType_name'];
297 $ret[$count]['reservation_comment'] = $row['Port_reservation_comment'];
298 $ret[$count]['remote_id'] = $row['RemotePort_id'];
299 $ret[$count]['remote_name'] = htmlentities ($row['RemotePort_name'], ENT_QUOTES);
300 $ret[$count]['remote_object_id'] = $row['RemotePort_object_id'];
301 $ret[$count]['remote_object_name'] = $row['RackObject_name'];
302 // Save on displayedName() calls.
303 if (empty ($row['RackObject_name']) and !empty ($row['RemotePort_object_id']))
304 {
305 $oi = getObjectInfo ($row['RemotePort_object_id']);
306 $ret[$count]['remote_object_name'] = displayedName ($oi);
307 }
308 $count++;
309 }
310 $result->closeCursor();
311 return $ret;
312 }
313
314 function commitAddRack ($name, $height, $row_id, $comment, $taglist)
315 {
316 $result = useInsertBlade
317 (
318 'Rack',
319 array
320 (
321 'row_id' => $row_id,
322 'name' => "'${name}'",
323 'height' => $height,
324 'comment' => "'${comment}'"
325 )
326 );
327 if ($result == NULL)
328 {
329 showError ('useInsertBlade() failed', __FUNCTION__);
330 return FALSE;
331 }
332
333 if (($result = useSelectBlade ('select last_insert_id()', __FUNCTION__)) == NULL)
334 {
335 showError ('Query #2 failed', __FUNCTION__);
336 return FALSE;
337 }
338 // we always have a row
339 $row = $result->fetch (PDO::FETCH_NUM);
340 $last_insert_id = $row[0];
341 $result->closeCursor();
342 $errcount = 0;
343 foreach ($taglist as $tag_id)
344 if (addTagForEntity ('rack', $last_insert_id, $tag_id) == FALSE)
345 $errcount++;
346 if ($errcount)
347 showError ("Experienced ${errcount} errors adding tags for the rack");
348 return recordHistory ('Rack', "id = ${last_insert_id}");
349 }
350
351 function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
352 {
353 global $dbxlink;
354 // Maintain UNIQUE INDEX for common names and asset tags by
355 // filtering out empty strings (not NULLs).
356 $result1 = useInsertBlade
357 (
358 'RackObject',
359 array
360 (
361 'name' => empty ($new_name) ? 'NULL' : "'${new_name}'",
362 'label' => "'${new_label}'",
363 'barcode' => empty ($new_barcode) ? 'NULL' : "'${new_barcode}'",
364 'objtype_id' => $new_type_id,
365 'asset_no' => empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'"
366 )
367 );
368 if ($result1 == NULL)
369 {
370 showError ("SQL query #1 failed", __FUNCTION__);
371 return FALSE;
372 }
373 $result2 = useSelectBlade ('select last_insert_id()', __FUNCTION__);
374 if ($result2 == NULL)
375 {
376 $errorInfo = $dbxlink->errorInfo();
377 showError ("SQL query '${query}' failed: ${errorInfo[2]}", __FUNCTION__);
378 die;
379 }
380 // we always have a row
381 $row = $result2->fetch (PDO::FETCH_NUM);
382 $last_insert_id = $row[0];
383 $result2->closeCursor();
384 // Do AutoPorts magic
385 executeAutoPorts ($last_insert_id, $new_type_id);
386 // Now tags...
387 $errcount = 0;
388 foreach ($taglist as $tag_id)
389 if (addTagForEntity ('object', $last_insert_id, $tag_id) == FALSE)
390 $errcount++;
391 if ($errcount)
392 showError ("Experienced ${errcount} errors adding tags for the object");
393 return recordHistory ('RackObject', "id = ${last_insert_id}");
394 }
395
396 function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
397 {
398 if ($object_id == 0 || $new_type_id == 0)
399 {
400 showError ('Not all required args are present.', __FUNCTION__);
401 return FALSE;
402 }
403 global $dbxlink;
404 $new_asset_no = empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'";
405 $new_barcode = empty ($new_barcode) ? 'NULL' : "'${new_barcode}'";
406 $new_name = empty ($new_name) ? 'NULL' : "'${new_name}'";
407 $query = "update RackObject set name=${new_name}, label='${new_label}', barcode=${new_barcode}, objtype_id='${new_type_id}', " .
408 "has_problems='${new_has_problems}', asset_no=${new_asset_no}, comment='${new_comment}' " .
409 "where id='${object_id}' limit 1";
410 $result = $dbxlink->query ($query);
411 if ($result == NULL)
412 {
413 showError ("SQL query '${query}' failed", __FUNCTION__);
414 return FALSE;
415 }
416 $result->closeCursor();
417 return recordHistory ('RackObject', "id = ${object_id}");
418 }
419
420 function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
421 {
422 if (empty ($rack_id) || empty ($new_name) || empty ($new_height))
423 {
424 showError ('Not all required args are present.', __FUNCTION__);
425 return FALSE;
426 }
427 global $dbxlink;
428 $query = "update Rack set name='${new_name}', height='${new_height}', comment='${new_comment}', row_id=${new_row_id} " .
429 "where id='${rack_id}' limit 1";
430 $result1 = $dbxlink->query ($query);
431 if ($result1->rowCount() != 1)
432 {
433 showError ('Error updating rack information', __FUNCTION__);
434 return FALSE;
435 }
436 return recordHistory ('Rack', "id = ${rack_id}");
437 }
438
439 // This function accepts rack data returned by getRackData(), validates and applies changes
440 // supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
441 // correspond to current rack ID.
442 // 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
443 // If 4th arg is present, object_id fields will be updated accordingly to the new state.
444 // The function returns the modified rack upon success.
445 function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
446 {
447 global $loclist, $dbxlink;
448 $rack_id = $rackData['id'];
449 $rack_name = $rackData['name'];
450 $rackchanged = FALSE;
451 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
452 {
453 for ($locidx = 0; $locidx < 3; $locidx++)
454 {
455 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
456 continue;
457 // detect a change
458 $state = $rackData[$unit_no][$locidx]['state'];
459 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
460 $newstate = $checked_state;
461 else
462 $newstate = $unchecked_state;
463 if ($state == $newstate)
464 continue;
465 $rackchanged = TRUE;
466 // and validate
467 $atom = $loclist[$locidx];
468 // The only changes allowed are those introduced by checkbox grid.
469 if
470 (
471 !($state == $checked_state && $newstate == $unchecked_state) &&
472 !($state == $unchecked_state && $newstate == $checked_state)
473 )
474 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
475 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
476 // anyway and then looking for probable need of INSERT.
477 $query =
478 "delete from RackSpace where rack_id = ${rack_id} and " .
479 "unit_no = ${unit_no} and atom = '${atom}' limit 1";
480 $r = $dbxlink->query ($query);
481 if ($r == NULL)
482 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL DELETE query failed");
483 if ($newstate != 'F')
484 {
485 $query =
486 "insert into RackSpace(rack_id, unit_no, atom, state) " .
487 "values(${rack_id}, ${unit_no}, '${atom}', '${newstate}') ";
488 $r = $dbxlink->query ($query);
489 if ($r == NULL)
490 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL INSERT query failed");
491 }
492 if ($newstate == 'T' and $object_id != 0)
493 {
494 // At this point we already have a record in RackSpace.
495 $query =
496 "update RackSpace set object_id=${object_id} " .
497 "where rack_id=${rack_id} and unit_no=${unit_no} and atom='${atom}' limit 1";
498 $r = $dbxlink->query ($query);
499 if ($r->rowCount() == 1)
500 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
501 else
502 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
503 }
504 }
505 }
506 if ($rackchanged)
507 {
508 resetThumbCache ($rack_id);
509 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
510 }
511 else
512 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
513 }
514
515 // This function builds a list of rack-unit-atom records, which are assigned to
516 // the requested object.
517 function getMoleculeForObject ($object_id = 0)
518 {
519 if ($object_id == 0)
520 {
521 showError ("object_id == 0", __FUNCTION__);
522 return NULL;
523 }
524 $query =
525 "select rack_id, unit_no, atom from RackSpace " .
526 "where state = 'T' and object_id = ${object_id} order by rack_id, unit_no, atom";
527 $result = useSelectBlade ($query, __FUNCTION__);
528 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
529 $result->closeCursor();
530 return $ret;
531 }
532
533 // This function builds a list of rack-unit-atom records for requested molecule.
534 function getMolecule ($mid = 0)
535 {
536 if ($mid == 0)
537 {
538 showError ("mid == 0", __FUNCTION__);
539 return NULL;
540 }
541 $query =
542 "select rack_id, unit_no, atom from Atom " .
543 "where molecule_id=${mid}";
544 $result = useSelectBlade ($query, __FUNCTION__);
545 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
546 $result->closeCursor();
547 return $ret;
548 }
549
550 // This function creates a new record in Molecule and number of linked
551 // R-U-A records in Atom.
552 function createMolecule ($molData)
553 {
554 global $dbxlink;
555 $query = "insert into Molecule values()";
556 $result1 = $dbxlink->query ($query);
557 if ($result1->rowCount() != 1)
558 {
559 showError ('Error inserting into Molecule', __FUNCTION__);
560 return NULL;
561 }
562 $query = 'select last_insert_id()';
563 $result2 = $dbxlink->query ($query);
564 if ($result2 == NULL)
565 {
566 showError ('Cannot get last ID.', __FUNCTION__);
567 return NULL;
568 }
569 $row = $result2->fetch (PDO::FETCH_NUM);
570 $molecule_id = $row[0];
571 $result2->closeCursor();
572 foreach ($molData as $rua)
573 {
574 $rack_id = $rua['rack_id'];
575 $unit_no = $rua['unit_no'];
576 $atom = $rua['atom'];
577 $query =
578 "insert into Atom(molecule_id, rack_id, unit_no, atom) " .
579 "values (${molecule_id}, ${rack_id}, ${unit_no}, '${atom}')";
580 $result3 = $dbxlink->query ($query);
581 if ($result3 == NULL or $result3->rowCount() != 1)
582 {
583 showError ('Error inserting into Atom', __FUNCTION__);
584 return NULL;
585 }
586 }
587 return $molecule_id;
588 }
589
590 // History logger. This function assumes certain table naming convention and
591 // column design:
592 // 1. History table name equals to dictionary table name plus 'History'.
593 // 2. History table must have the same row set (w/o keys) plus one row named
594 // 'ctime' of type 'timestamp'.
595 function recordHistory ($tableName, $whereClause)
596 {
597 global $dbxlink, $remote_username;
598 $query = "insert into ${tableName}History select *, current_timestamp(), '${remote_username}' from ${tableName} where ${whereClause}";
599 $result = $dbxlink->query ($query);
600 if ($result == NULL or $result->rowCount() != 1)
601 {
602 showError ("SQL query '${query}' failed for table ${tableName}", __FUNCTION__);
603 return FALSE;
604 }
605 return TRUE;
606 }
607
608 function getRackspaceHistory ()
609 {
610 $query =
611 "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 " .
612 "MountOperation as mo inner join RackObject as ro on mo.object_id = ro.id " .
613 "inner join Dictionary on objtype_id = dict_key natural join Chapter " .
614 "where chapter_name = 'RackObjectType' order by ctime desc";
615 $result = useSelectBlade ($query, __FUNCTION__);
616 $ret = $result->fetchAll(PDO::FETCH_ASSOC);
617 $result->closeCursor();
618 return $ret;
619 }
620
621 // This function is used in renderRackspaceHistory()
622 function getOperationMolecules ($op_id = 0)
623 {
624 if ($op_id <= 0)
625 {
626 showError ("Missing argument", __FUNCTION__);
627 return;
628 }
629 $query = "select old_molecule_id, new_molecule_id from MountOperation where id = ${op_id}";
630 $result = useSelectBlade ($query, __FUNCTION__);
631 // We expect one row.
632 $row = $result->fetch (PDO::FETCH_ASSOC);
633 if ($row == NULL)
634 {
635 showError ("SQL query succeded, but returned no results.", __FUNCTION__);
636 return;
637 }
638 $omid = $row['old_molecule_id'];
639 $nmid = $row['new_molecule_id'];
640 $result->closeCursor();
641 return array ($omid, $nmid);
642 }
643
644 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
645 {
646 if ($object_id <= 0)
647 {
648 showError ('Invalid object_id', __FUNCTION__);
649 return;
650 }
651 $query = "select distinct rack_id from RackSpace where object_id = ${object_id} order by rack_id";
652 $result = useSelectBlade ($query, __FUNCTION__);
653 $rows = $result->fetchAll (PDO::FETCH_NUM);
654 $result->closeCursor();
655 $ret = array();
656 foreach ($rows as $row)
657 {
658 if (!$fetch_rackdata)
659 {
660 $ret[$row[0]] = $row[0];
661 continue;
662 }
663 $rackData = getRackData ($row[0]);
664 if ($rackData == NULL)
665 {
666 showError ('getRackData() failed', __FUNCTION__);
667 return NULL;
668 }
669 $ret[$row[0]] = $rackData;
670 }
671 $result->closeCursor();
672 return $ret;
673 }
674
675 function getObjectGroupInfo ()
676 {
677 $query =
678 'select dict_key as id, dict_value as name, count(id) as count from ' .
679 'Dictionary natural join Chapter left join RackObject on dict_key = objtype_id ' .
680 'where chapter_name = "RackObjectType" ' .
681 'group by dict_key order by dict_value';
682 $result = useSelectBlade ($query, __FUNCTION__);
683 $ret = array();
684 $ret[0] = array ('id' => 0, 'name' => 'ALL types');
685 $clist = array ('id', 'name', 'count');
686 $total = 0;
687 while ($row = $result->fetch (PDO::FETCH_ASSOC))
688 if ($row['count'] > 0)
689 {
690 $total += $row['count'];
691 foreach ($clist as $cname)
692 $ret[$row['id']][$cname] = $row[$cname];
693 }
694 $result->closeCursor();
695 $ret[0]['count'] = $total;
696 return $ret;
697 }
698
699 // This function returns objects, which have no rackspace assigned to them.
700 // Additionally it keeps rack_id parameter, so we can silently pre-select
701 // the rack required.
702 function getUnmountedObjects ()
703 {
704 $query =
705 'select dict_value as objtype_name, dict_key as objtype_id, name, label, barcode, id, asset_no from ' .
706 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter ' .
707 'left join RackSpace on id = object_id '.
708 'where rack_id is null and chapter_name = "RackObjectType" order by dict_value, name, label, asset_no, barcode';
709 $result = useSelectBlade ($query, __FUNCTION__);
710 $ret = array();
711 $clist = array ('id', 'name', 'label', 'barcode', 'objtype_name', 'objtype_id', 'asset_no');
712 while ($row = $result->fetch (PDO::FETCH_ASSOC))
713 {
714 foreach ($clist as $cname)
715 $ret[$row['id']][$cname] = $row[$cname];
716 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
717 }
718 $result->closeCursor();
719 return $ret;
720 }
721
722 function getProblematicObjects ()
723 {
724 $query =
725 'select dict_value as objtype_name, dict_key as objtype_id, name, id, asset_no from ' .
726 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter '.
727 'where has_problems = "yes" and chapter_name = "RackObjectType" order by objtype_name, name';
728 $result = useSelectBlade ($query, __FUNCTION__);
729 $ret = array();
730 $clist = array ('id', 'name', 'objtype_name', 'objtype_id', 'asset_no');
731 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732 {
733 foreach ($clist as $cname)
734 $ret[$row['id']][$cname] = $row[$cname];
735 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
736 }
737 $result->closeCursor();
738 return $ret;
739 }
740
741 function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
742 {
743 if ($object_id <= 0)
744 {
745 showError ('Invalid object_id', __FUNCTION__);
746 return;
747 }
748 $port_l2address = l2addressForDatabase ($port_l2address);
749 $result = useInsertBlade
750 (
751 'Port',
752 array
753 (
754 'name' => "'${port_name}'",
755 'object_id' => "'${object_id}'",
756 'label' => "'${port_label}'",
757 'type' => "'${port_type_id}'",
758 'l2address' => "${port_l2address}"
759 )
760 );
761 if ($result)
762 return '';
763 else
764 return 'SQL query failed';
765 }
766
767 function commitUpdatePort ($port_id, $port_name, $port_label, $port_l2address, $port_reservation_comment)
768 {
769 global $dbxlink;
770 $port_l2address = l2addressForDatabase ($port_l2address);
771 $query =
772 "update Port set name='$port_name', label='$port_label', " .
773 "reservation_comment = ${port_reservation_comment}, l2address=${port_l2address} " .
774 "where id='$port_id'";
775 $result = $dbxlink->exec ($query);
776 if ($result == 1)
777 return '';
778 $errorInfo = $dbxlink->errorInfo();
779 // We could update nothing.
780 if ($errorInfo[0] == '00000')
781 return '';
782 return $errorInfo[2];
783 }
784
785 function delObjectPort ($port_id)
786 {
787 if (unlinkPort ($port_id) != '')
788 return __FUNCTION__ . ': unlinkPort() failed';
789 if (useDeleteBlade ('Port', 'id', $port_id) != TRUE)
790 return __FUNCTION__ . ': useDeleteBlade() failed';
791 return '';
792 }
793
794 function getObjectAddressesAndNames ()
795 {
796 $query =
797 "select object_id as object_id, ".
798 "RackObject.name as object_name, ".
799 "IPBonds.name as name, ".
800 "INET_NTOA(ip) as ip ".
801 "from IPBonds join RackObject on id=object_id ";
802 $result = useSelectBlade ($query, __FUNCTION__);
803 $ret = array();
804 $count=0;
805 while ($row = $result->fetch (PDO::FETCH_ASSOC))
806 {
807 $ret[$count]['object_id']=$row['object_id'];
808 $ret[$count]['object_name']=$row['object_name'];
809 $ret[$count]['name']=$row['name'];
810 $ret[$count]['ip']=$row['ip'];
811 $count++;
812 }
813 $result->closeCursor();
814 return $ret;
815 }
816
817 function getEmptyPortsOfType ($type_id)
818 {
819 $query =
820 "select distinct Port.id as Port_id, ".
821 "Port.object_id as Port_object_id, ".
822 "RackObject.name as Object_name, ".
823 "Port.name as Port_name, ".
824 "Port.type as Port_type_id, ".
825 "dict_value as Port_type_name ".
826 "from ( ".
827 " ( ".
828 " Port inner join Dictionary on Port.type = dict_key natural join Chapter ".
829 " ) ".
830 " join RackObject on Port.object_id = RackObject.id ".
831 ") ".
832 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
833 "inner join PortCompat on Port.type = PortCompat.type2 ".
834 "where chapter_name = 'PortType' and PortCompat.type1 = '$type_id' and Link.porta is NULL ".
835 "and Port.reservation_comment is null order by Object_name, Port_name";
836 $result = useSelectBlade ($query, __FUNCTION__);
837 $ret = array();
838 $count=0;
839 while ($row = $result->fetch (PDO::FETCH_ASSOC))
840 {
841 $ret[$count]['Port_id']=$row['Port_id'];
842 $ret[$count]['Port_object_id']=$row['Port_object_id'];
843 $ret[$count]['Object_name']=$row['Object_name'];
844 $ret[$count]['Port_name']=$row['Port_name'];
845 $ret[$count]['Port_type_id']=$row['Port_type_id'];
846 $ret[$count]['Port_type_name']=$row['Port_type_name'];
847 $count++;
848 }
849 $result->closeCursor();
850 return $ret;
851 }
852
853 function linkPorts ($porta, $portb)
854 {
855 if ($porta == $portb)
856 return "Ports can't be the same";
857 if ($porta > $portb)
858 {
859 $tmp = $porta;
860 $porta = $portb;
861 $portb = $tmp;
862 }
863 global $dbxlink;
864 $query1 = "insert into Link set porta='${porta}', portb='{$portb}'";
865 $query2 = "update Port set reservation_comment = NULL where id = ${porta} or id = ${portb} limit 2";
866 // FIXME: who cares about the return value?
867 $result = $dbxlink->exec ($query1);
868 $result = $dbxlink->exec ($query2);
869 return '';
870 }
871
872 function unlinkPort ($port)
873 {
874 global $dbxlink;
875 $query =
876 "delete from Link where porta='$port' or portb='$port'";
877 $result = $dbxlink->exec ($query);
878 return '';
879 }
880
881 // FIXME: after falling back to using existing getObjectInfo we don't
882 // need that large query. Shrink it some later.
883 function getObjectAddresses ($object_id = 0)
884 {
885 if ($object_id == 0)
886 {
887 showError ('Invalid object_id', __FUNCTION__);
888 return;
889 }
890 $query =
891 "select ".
892 "IPAddress.name as IPAddress_name, ".
893 "IPAddress.reserved as IPAddress_reserved, ".
894 "IPBonds.name as IPBonds_name, ".
895 "INET_NTOA(IPBonds.ip) as IPBonds_ip, ".
896 "IPBonds.type as IPBonds_type, ".
897 "RemoteBonds.name as RemoteBonds_name, ".
898 "RemoteBonds.type as RemoteBonds_type, ".
899 "RemoteBonds.object_id as RemoteBonds_object_id, ".
900 "RemoteObject.name as RemoteObject_name from IPBonds " .
901 "left join IPBonds as RemoteBonds on IPBonds.ip=RemoteBonds.ip " .
902 "and IPBonds.object_id!=RemoteBonds.object_id " .
903 "left join IPAddress on IPBonds.ip=IPAddress.ip " .
904 "left join RackObject as RemoteObject on RemoteBonds.object_id=RemoteObject.id ".
905 "where ".
906 "IPBonds.object_id = ${object_id} ".
907 "order by IPBonds.ip, RemoteObject.name";
908 $result = useSelectBlade ($query, __FUNCTION__);
909 $ret=array();
910 $count=0;
911 $refcount=0;
912 $prev_ip = 0;
913 // We are going to call getObjectInfo() for some rows,
914 // hence the connector must be unloaded from the
915 // current data.
916 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
917 $result->closeCursor();
918 foreach ($rows as $row)
919 {
920 if ($prev_ip != $row['IPBonds_ip'])
921 {
922 $count++;
923 $refcount=0;
924 $prev_ip = $row['IPBonds_ip'];
925 $ret[$count]['address_name'] = $row['IPAddress_name'];
926 $ret[$count]['address_reserved'] = $row['IPAddress_reserved'];
927 $ret[$count]['ip'] = $row['IPBonds_ip'];
928 $ret[$count]['name'] = $row['IPBonds_name'];
929 $ret[$count]['type'] = $row['IPBonds_type'];
930 $ret[$count]['references'] = array();
931 }
932
933 if ($row['RemoteBonds_type'])
934 {
935 $ret[$count]['references'][$refcount]['type'] = $row['RemoteBonds_type'];
936 $ret[$count]['references'][$refcount]['name'] = $row['RemoteBonds_name'];
937 $ret[$count]['references'][$refcount]['object_id'] = $row['RemoteBonds_object_id'];
938 if (empty ($row['RemoteBonds_object_id']))
939 $ret[$count]['references'][$refcount]['object_name'] = $row['RemoteObject_name'];
940 else
941 {
942 $oi = getObjectInfo ($row['RemoteBonds_object_id']);
943 $ret[$count]['references'][$refcount]['object_name'] = displayedName ($oi);
944 }
945 $refcount++;
946 }
947 }
948 return $ret;
949 }
950
951 function getAddressspaceList ($tagfilter = array())
952 {
953 $whereclause = getWhereClause ($tagfilter);
954 $query =
955 "select distinct ".
956 "id as IPRanges_id, ".
957 "INET_NTOA(ip) as IPRanges_ip, ".
958 "mask as IPRanges_mask, ".
959 "name as IPRanges_name ".
960 "from IPRanges left join TagStorage on IPRanges.id = TagStorage.target_id and target_realm = 'ipv4net' " .
961 "where true ${whereclause} " .
962 " order by ip";
963 $result = useSelectBlade ($query, __FUNCTION__);
964 $ret=array();
965 $count=0;
966 while ($row = $result->fetch (PDO::FETCH_ASSOC))
967 {
968 $ret[$count]['id'] = $row['IPRanges_id'];
969 $ret[$count]['ip'] = $row['IPRanges_ip'];
970 $ret[$count]['ip_bin'] = ip2long($row['IPRanges_ip']);
971 $ret[$count]['name'] = $row['IPRanges_name'];
972 $ret[$count]['mask'] = $row['IPRanges_mask'];
973 $ret[$count]['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
974 $ret[$count]['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
975 $count++;
976 }
977 $result->closeCursor();
978 return $ret;
979
980 }
981
982 function getRangeByIp ($ip = '', $id = 0)
983 {
984 if ($id == 0)
985 $query =
986 "select ".
987 "id, INET_NTOA(ip) as ip, mask, name ".
988 "from IPRanges ";
989 else
990 $query =
991 "select ".
992 "id, INET_NTOA(ip) as ip, mask, name ".
993 "from IPRanges where id='$id'";
994
995 $result = useSelectBlade ($query, __FUNCTION__);
996 $ret=array();
997 while ($row = $result->fetch (PDO::FETCH_ASSOC))
998 {
999 $binmask=binMaskFromDec($row['mask']);
1000 if ((ip2long($ip) & $binmask) == ip2long($row['ip']))
1001 {
1002 $ret['id'] = $row['id'];
1003 $ret['ip'] = $row['ip'];
1004 $ret['ip_bin'] = ip2long($row['ip']);
1005 $ret['name'] = $row['name'];
1006 $ret['mask'] = $row['mask'];
1007 $result->closeCursor();
1008 return $ret;
1009 }
1010 }
1011 $result->closeCursor();
1012 return NULL;
1013 }
1014
1015 function updateRange ($id=0, $name='')
1016 {
1017 global $dbxlink;
1018 $query =
1019 "update IPRanges set name='$name' where id='$id'";
1020 $result = $dbxlink->exec ($query);
1021 return '';
1022 }
1023
1024 // This function is actually used not only to update, but also to create records,
1025 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1026 // (MySQL 4.0 workaround).
1027 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1028 {
1029 // DELETE may safely fail.
1030 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')", FALSE);
1031 // INSERT may appear not necessary.
1032 if ($name == '' and $reserved == 'no')
1033 return '';
1034 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1035 return '';
1036 else
1037 return __FUNCTION__ . '(): useInsertBlade() failed';
1038 }
1039
1040 function updateBond ($ip='', $object_id=0, $name='', $type='')
1041 {
1042 global $dbxlink;
1043
1044 $query =
1045 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1046 $result = $dbxlink->exec ($query);
1047 return '';
1048 }
1049
1050 function unbindIpFromObject ($ip='', $object_id=0)
1051 {
1052 global $dbxlink;
1053
1054 $query =
1055 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1056 $result = $dbxlink->exec ($query);
1057 return '';
1058 }
1059
1060 // This function returns either all or one user account. Array key is user name.
1061 function getUserAccounts ($tagfilter = array())
1062 {
1063 $whereclause = getWhereClause ($tagfilter);
1064 $query =
1065 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
1066 'from UserAccount left join TagStorage ' .
1067 "on UserAccount.user_id = TagStorage.target_id and target_realm = 'user' " .
1068 "where true ${whereclause} " .
1069 'order by user_name';
1070 $result = useSelectBlade ($query, __FUNCTION__);
1071 $ret = array();
1072 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1073 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1074 foreach ($clist as $cname)
1075 $ret[$row['user_name']][$cname] = $row[$cname];
1076 $result->closeCursor();
1077 return $ret;
1078 }
1079
1080 function searchByl2address ($l2addr)
1081 {
1082 $l2addr = l2addressForDatabase ($l2addr);
1083 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1084 "where l2address = ${l2addr}";
1085 $result = useSelectBlade ($query, __FUNCTION__);
1086 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1087 $result->closeCursor();
1088 if (count ($rows) == 0) // No results.
1089 return NULL;
1090 if (count ($rows) == 1) // Target found.
1091 return $rows[0];
1092 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__);
1093 return NULL;
1094 }
1095
1096 function getIPv4PrefixSearchResult ($terms)
1097 {
1098 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPRanges where ";
1099 $or = '';
1100 foreach (explode (' ', $terms) as $term)
1101 {
1102 $query .= $or . "name like '%${term}%'";
1103 $or = ' or ';
1104 }
1105 $result = useSelectBlade ($query, __FUNCTION__);
1106 $ret = array();
1107 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1108 $ret[] = $row;
1109 return $ret;
1110 }
1111
1112 function getIPv4AddressSearchResult ($terms)
1113 {
1114 $query = "select inet_ntoa(ip) as ip, name from IPAddress where ";
1115 $or = '';
1116 foreach (explode (' ', $terms) as $term)
1117 {
1118 $query .= $or . "name like '%${term}%'";
1119 $or = ' or ';
1120 }
1121 $result = useSelectBlade ($query, __FUNCTION__);
1122 $ret = array();
1123 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1124 $ret[] = $row;
1125 return $ret;
1126 }
1127
1128 function getIPv4RSPoolSearchResult ($terms)
1129 {
1130 $query = "select id as pool_id, name from IPRSPool where ";
1131 $or = '';
1132 foreach (explode (' ', $terms) as $term)
1133 {
1134 $query .= $or . "name like '%${term}%'";
1135 $or = ' or ';
1136 }
1137 $result = useSelectBlade ($query, __FUNCTION__);
1138 $ret = array();
1139 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1140 $ret[] = $row;
1141 return $ret;
1142 }
1143
1144 function getIPv4VServiceSearchResult ($terms)
1145 {
1146 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPVirtualService where ";
1147 $or = '';
1148 foreach (explode (' ', $terms) as $term)
1149 {
1150 $query .= $or . "name like '%${term}%'";
1151 $or = ' or ';
1152 }
1153 $result = useSelectBlade ($query, __FUNCTION__);
1154 $ret = array();
1155 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1156 $ret[] = $row;
1157 return $ret;
1158 }
1159
1160 function getAccountSearchResult ($terms)
1161 {
1162 return getSearchResultByField
1163 (
1164 'UserAccount',
1165 array ('user_id', 'user_name', 'user_realname'),
1166 'user_name',
1167 $terms,
1168 'user_name'
1169 );
1170 }
1171
1172 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '')
1173 {
1174 $pfx = '';
1175 $query = 'select ';
1176 foreach ($rcolumns as $col)
1177 {
1178 $query .= $pfx . $col;
1179 $pfx = ', ';
1180 }
1181 $pfx = '';
1182 $query .= " from ${tname} where ";
1183 foreach (explode (' ', $terms) as $term)
1184 {
1185 $query .= $pfx . "${scolumn} like '%${term}%'";
1186 $pfx = ' or ';
1187 }
1188 if ($ocolumn != '')
1189 $query .= " order by ${ocolumn}";
1190 $result = useSelectBlade ($query, __FUNCTION__);
1191 $ret = array();
1192 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1193 $ret[] = $row;
1194 return $ret;
1195 }
1196
1197 // This function returns either port ID or NULL for specified arguments.
1198 function getPortID ($object_id, $port_name)
1199 {
1200 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
1201 $result = useSelectBlade ($query, __FUNCTION__);
1202 $rows = $result->fetchAll (PDO::FETCH_NUM);
1203 if (count ($rows) != 1)
1204 return NULL;
1205 $ret = $rows[0][0];
1206 $result->closeCursor();
1207 return $ret;
1208 }
1209
1210 function commitCreateUserAccount ($username, $realname, $password)
1211 {
1212 return useInsertBlade
1213 (
1214 'UserAccount',
1215 array
1216 (
1217 'user_name' => "'${username}'",
1218 'user_realname' => "'${realname}'",
1219 'user_password_hash' => "'${password}'"
1220 )
1221 );
1222 }
1223
1224 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1225 {
1226 global $dbxlink;
1227 $query =
1228 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1229 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1230 $result = $dbxlink->query ($query);
1231 if ($result == NULL)
1232 {
1233 showError ('SQL query failed', __FUNCTION__);
1234 die;
1235 }
1236 return TRUE;
1237 }
1238
1239 function commitEnableUserAccount ($id, $new_enabled_value)
1240 {
1241 global $dbxlink;
1242 $query =
1243 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1244 "where user_id = ${id} limit 1";
1245 $result = $dbxlink->query ($query);
1246 if ($result == NULL)
1247 {
1248 showError ('SQL query failed', __FUNCTION__);
1249 die;
1250 }
1251 return TRUE;
1252 }
1253
1254 // This function returns an array of all port type pairs from PortCompat table.
1255 function getPortCompat ()
1256 {
1257 $query =
1258 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1259 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1260 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1261 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1262 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1263 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
1264 $result = useSelectBlade ($query, __FUNCTION__);
1265 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1266 $result->closeCursor();
1267 return $ret;
1268 }
1269
1270 function removePortCompat ($type1 = 0, $type2 = 0)
1271 {
1272 global $dbxlink;
1273 if ($type1 == 0 or $type2 == 0)
1274 {
1275 showError ('Invalid arguments', __FUNCTION__);
1276 die;
1277 }
1278 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1279 $result = $dbxlink->query ($query);
1280 if ($result == NULL)
1281 {
1282 showError ('SQL query failed', __FUNCTION__);
1283 die;
1284 }
1285 return TRUE;
1286 }
1287
1288 function addPortCompat ($type1 = 0, $type2 = 0)
1289 {
1290 if ($type1 <= 0 or $type2 <= 0)
1291 {
1292 showError ('Invalid arguments', __FUNCTION__);
1293 die;
1294 }
1295 return useInsertBlade
1296 (
1297 'PortCompat',
1298 array ('type1' => $type1, 'type2' => $type2)
1299 );
1300 }
1301
1302 // This function returns the dictionary as an array of trees, each tree
1303 // representing a single chapter. Each element has 'id', 'name', 'sticky'
1304 // and 'word' keys with the latter holding all the words within the chapter.
1305 function getDict ($parse_links = FALSE)
1306 {
1307 $query1 =
1308 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1309 "Chapter natural left join Dictionary order by chapter_name, dict_value";
1310 $result = useSelectBlade ($query1, __FUNCTION__);
1311 $dict = array();
1312 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1313 {
1314 $chapter_no = $row['chapter_no'];
1315 if (!isset ($dict[$chapter_no]))
1316 {
1317 $dict[$chapter_no]['no'] = $chapter_no;
1318 $dict[$chapter_no]['name'] = $row['chapter_name'];
1319 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1320 $dict[$chapter_no]['word'] = array();
1321 }
1322 if ($row['dict_key'] != NULL)
1323 {
1324 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1325 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
1326 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1327 }
1328 }
1329 $result->closeCursor();
1330 unset ($result);
1331 // Find the list of all assigned values of dictionary-addressed attributes, each with
1332 // chapter/word keyed reference counters. Use the structure to adjust reference counters
1333 // of the returned disctionary words.
1334 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1335 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1336 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1337 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1338 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1339 "order by a.attr_id, am.chapter_no, uint_value";
1340 $result = useSelectBlade ($query2, __FUNCTION__);
1341 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1342 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
1343 $result->closeCursor();
1344 return $dict;
1345 }
1346
1347 function getDictStats ()
1348 {
1349 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
1350 $query =
1351 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1352 "Chapter natural left join Dictionary group by Chapter.chapter_no";
1353 $result = useSelectBlade ($query, __FUNCTION__);
1354 $tc = $tw = $uc = $uw = 0;
1355 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1356 {
1357 $tc++;
1358 $tw += $row['wc'];;
1359 if (in_array ($row['chapter_no'], $stock_chapters))
1360 continue;
1361 $uc++;
1362 $uw += $row['wc'];;
1363 }
1364 $result->closeCursor();
1365 unset ($result);
1366 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1367 "AttributeValue as av on ro.id = av.object_id group by ro.id";
1368 $result = useSelectBlade ($query, __FUNCTION__);
1369 $to = $ta = $so = 0;
1370 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1371 {
1372 $to++;
1373 if ($row['attrc'] != 0)
1374 {
1375 $so++;
1376 $ta += $row['attrc'];
1377 }
1378 }
1379 $result->closeCursor();
1380 $ret = array();
1381 $ret['Total chapters in dictionary'] = $tc;
1382 $ret['Total words in dictionary'] = $tw;
1383 $ret['User chapters'] = $uc;
1384 $ret['Words in user chapters'] = $uw;
1385 $ret['Total objects'] = $to;
1386 $ret['Objects with stickers'] = $so;
1387 $ret['Total stickers attached'] = $ta;
1388 return $ret;
1389 }
1390
1391 function getIPv4Stats()
1392 {
1393 $ret = array();
1394 $subject = array();
1395 $subject[] = array ('q' => 'select count(id) from IPRanges', 'txt' => 'Networks');
1396 $subject[] = array ('q' => 'select count(ip) from IPAddress', 'txt' => 'Addresses commented/reserved');
1397 $subject[] = array ('q' => 'select count(ip) from IPBonds', 'txt' => 'Addresses allocated');
1398 $subject[] = array ('q' => 'select count(*) from PortForwarding', 'txt' => 'NAT rules');
1399 $subject[] = array ('q' => 'select count(id) from IPVirtualService', 'txt' => 'Virtual services');
1400 $subject[] = array ('q' => 'select count(id) from IPRSPool', 'txt' => 'Real server pools');
1401 $subject[] = array ('q' => 'select count(id) from IPRealServer', 'txt' => 'Real servers');
1402 $subject[] = array ('q' => 'select count(distinct object_id) from IPLoadBalancer', 'txt' => 'Load balancers');
1403
1404 foreach ($subject as $item)
1405 {
1406 $result = useSelectBlade ($item['q'], __FUNCTION__);
1407 $row = $result->fetch (PDO::FETCH_NUM);
1408 $ret[$item['txt']] = $row[0];
1409 $result->closeCursor();
1410 unset ($result);
1411 }
1412 return $ret;
1413 }
1414
1415 function getRackspaceStats()
1416 {
1417 $ret = array();
1418 $subject = array();
1419 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1420 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1421 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1422 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1423
1424 foreach ($subject as $item)
1425 {
1426 $result = useSelectBlade ($item['q'], __FUNCTION__);
1427 $row = $result->fetch (PDO::FETCH_NUM);
1428 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
1429 $result->closeCursor();
1430 unset ($result);
1431 }
1432 return $ret;
1433 }
1434
1435 function getTagStats ()
1436 {
1437 $ret = array();
1438 $query = "select tag, count(tag_id) as refcnt from " .
1439 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
1440 "group by tag_id order by refcnt desc";
1441 $result = useSelectBlade ($query, __FUNCTION__);
1442 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1443 $ret[$row['tag']] = $row['refcnt'];
1444 $result->closeCursor();
1445 return $ret;
1446 }
1447
1448 function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1449 {
1450 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1451 {
1452 showError ('Invalid args', __FUNCTION__);
1453 die;
1454 }
1455 global $dbxlink;
1456 $query =
1457 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1458 "and dict_key=${dict_key} limit 1";
1459 $result = $dbxlink->query ($query);
1460 if ($result == NULL)
1461 {
1462 showError ('SQL query failed', __FUNCTION__);
1463 die;
1464 }
1465 return TRUE;
1466 }
1467
1468 function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1469 {
1470 if ($chapter_no <= 0 or empty ($dict_value))
1471 {
1472 showError ('Invalid args', __FUNCTION__);
1473 die;
1474 }
1475 return useInsertBlade
1476 (
1477 'Dictionary',
1478 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1479 );
1480 }
1481
1482 function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1483 {
1484 if ($chapter_no <= 0 or $dict_key <= 0)
1485 {
1486 showError ('Invalid args', __FUNCTION__);
1487 die;
1488 }
1489 global $dbxlink;
1490 $query =
1491 "delete from Dictionary where chapter_no=${chapter_no} " .
1492 "and dict_key=${dict_key} limit 1";
1493 $result = $dbxlink->query ($query);
1494 if ($result == NULL)
1495 {
1496 showError ('SQL query failed', __FUNCTION__);
1497 die;
1498 }
1499 return TRUE;
1500 }
1501
1502 function commitAddChapter ($chapter_name = '')
1503 {
1504 if (empty ($chapter_name))
1505 {
1506 showError ('Invalid args', __FUNCTION__);
1507 die;
1508 }
1509 return useInsertBlade
1510 (
1511 'Chapter',
1512 array ('chapter_name' => "'${chapter_name}'")
1513 );
1514 }
1515
1516 function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1517 {
1518 if ($chapter_no <= 0 or empty ($chapter_name))
1519 {
1520 showError ('Invalid args', __FUNCTION__);
1521 die;
1522 }
1523 global $dbxlink;
1524 $query =
1525 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1526 "and sticky = 'no' limit 1";
1527 $result = $dbxlink->query ($query);
1528 if ($result == NULL)
1529 {
1530 showError ('SQL query failed', __FUNCTION__);
1531 die;
1532 }
1533 return TRUE;
1534 }
1535
1536 function commitDeleteChapter ($chapter_no = 0)
1537 {
1538 if ($chapter_no <= 0)
1539 {
1540 showError ('Invalid args', __FUNCTION__);
1541 die;
1542 }
1543 global $dbxlink;
1544 $query =
1545 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1546 $result = $dbxlink->query ($query);
1547 if ($result == NULL)
1548 {
1549 showError ('SQL query failed', __FUNCTION__);
1550 die;
1551 }
1552 return TRUE;
1553 }
1554
1555 // This is a dictionary accessor. We perform link rendering, so the user sees
1556 // nice <select> drop-downs.
1557 function readChapter ($chapter_name = '')
1558 {
1559 if (empty ($chapter_name))
1560 {
1561 showError ('invalid argument', __FUNCTION__);
1562 return NULL;
1563 }
1564 $query =
1565 "select dict_key, dict_value from Dictionary natural join Chapter " .
1566 "where chapter_name = '${chapter_name}'";
1567 $result = useSelectBlade ($query, __FUNCTION__);
1568 $chapter = array();
1569 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1570 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
1571 $result->closeCursor();
1572 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1573 asort ($chapter);
1574 return $chapter;
1575 }
1576
1577 function getAttrMap ()
1578 {
1579 $query =
1580 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1581 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1582 "Attribute as a natural left join AttributeMap as am " .
1583 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1584 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1585 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1586 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1587 "order by attr_name";
1588 $result = useSelectBlade ($query, __FUNCTION__);
1589 $ret = array();
1590 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1591 {
1592 $attr_id = $row['attr_id'];
1593 if (!isset ($ret[$attr_id]))
1594 {
1595 $ret[$attr_id]['id'] = $attr_id;
1596 $ret[$attr_id]['type'] = $row['attr_type'];
1597 $ret[$attr_id]['name'] = $row['attr_name'];
1598 $ret[$attr_id]['application'] = array();
1599 }
1600 if ($row['objtype_id'] == '')
1601 continue;
1602 $application['objtype_id'] = $row['objtype_id'];
1603 $application['objtype_name'] = $row['objtype_name'];
1604 if ($row['attr_type'] == 'dict')
1605 {
1606 $application['chapter_no'] = $row['chapter_no'];
1607 $application['chapter_name'] = $row['chapter_name'];
1608 }
1609 $ret[$attr_id]['application'][] = $application;
1610 }
1611 $result->closeCursor();
1612 return $ret;
1613 }
1614
1615 function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1616 {
1617 if ($attr_id <= 0 or empty ($attr_name))
1618 {
1619 showError ('Invalid args', __FUNCTION__);
1620 die;
1621 }
1622 global $dbxlink;
1623 $query =
1624 "update Attribute set attr_name = '${attr_name}' " .
1625 "where attr_id = ${attr_id} limit 1";
1626 $result = $dbxlink->query ($query);
1627 if ($result == NULL)
1628 {
1629 showError ("SQL query '${query}' failed", __FUNCTION__);
1630 die;
1631 }
1632 return TRUE;
1633 }
1634
1635 function commitAddAttribute ($attr_name = '', $attr_type = '')
1636 {
1637 if (empty ($attr_name))
1638 {
1639 showError ('Invalid args', __FUNCTION__);
1640 die;
1641 }
1642 switch ($attr_type)
1643 {
1644 case 'uint':
1645 case 'float':
1646 case 'string':
1647 case 'dict':
1648 break;
1649 default:
1650 showError ('Invalid args', __FUNCTION__);
1651 die;
1652 }
1653 return useInsertBlade
1654 (
1655 'Attribute',
1656 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1657 );
1658 }
1659
1660 function commitDeleteAttribute ($attr_id = 0)
1661 {
1662 if ($attr_id <= 0)
1663 {
1664 showError ('Invalid args', __FUNCTION__);
1665 die;
1666 }
1667 return useDeleteBlade ('Attribute', 'attr_id', $attr_id, FALSE);
1668 }
1669
1670 // FIXME: don't store garbage in chapter_no for non-dictionary types.
1671 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1672 {
1673 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
1674 {
1675 showError ('Invalid args', __FUNCTION__);
1676 die;
1677 }
1678 return useInsertBlade
1679 (
1680 'AttributeMap',
1681 array
1682 (
1683 'attr_id' => $attr_id,
1684 'objtype_id' => $objtype_id,
1685 'chapter_no' => $chapter_no
1686 )
1687 );
1688 }
1689
1690 function commitReduceAttrMap ($attr_id = 0, $objtype_id)
1691 {
1692 if ($attr_id <= 0 or $objtype_id <= 0)
1693 {
1694 showError ('Invalid args', __FUNCTION__);
1695 die;
1696 }
1697 global $dbxlink;
1698 $query =
1699 "delete from AttributeMap where attr_id=${attr_id} " .
1700 "and objtype_id=${objtype_id} limit 1";
1701 $result = $dbxlink->query ($query);
1702 if ($result == NULL)
1703 {
1704 showError ('SQL query failed', __FUNCTION__);
1705 die;
1706 }
1707 return TRUE;
1708 }
1709
1710 // This function returns all optional attributes for requested object
1711 // as an array of records. NULL is returned on error and empty array
1712 // is returned, if there are no attributes found.
1713 function getAttrValues ($object_id, $strip_optgroup = FALSE)
1714 {
1715 if ($object_id <= 0)
1716 {
1717 showError ('Invalid argument', __FUNCTION__);
1718 return NULL;
1719 }
1720 $ret = array();
1721 $query =
1722 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
1723 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
1724 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
1725 "inner join Attribute as A using (attr_id) " .
1726 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
1727 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
1728 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
1729 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
1730 $result = useSelectBlade ($query, __FUNCTION__);
1731 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1732 {
1733 $record = array();
1734 $record['id'] = $row['attr_id'];
1735 $record['name'] = $row['attr_name'];
1736 $record['type'] = $row['attr_type'];
1737 switch ($row['attr_type'])
1738 {
1739 case 'uint':
1740 case 'float':
1741 case 'string':
1742 $record['value'] = $row[$row['attr_type'] . '_value'];
1743 $record['a_value'] = parseWikiLink ($record['value'], 'a');
1744 break;
1745 case 'dict':
1746 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
1747 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
1748 $record['chapter_name'] = $row['chapter_name'];
1749 $record['key'] = $row['uint_value'];
1750 break;
1751 default:
1752 $record['value'] = NULL;
1753 break;
1754 }
1755 $ret[$row['attr_id']] = $record;
1756 }
1757 $result->closeCursor();
1758 return $ret;
1759 }
1760
1761 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
1762 {
1763 if ($object_id <= 0 or $attr_id <= 0)
1764 {
1765 showError ('Invalid arguments', __FUNCTION__);
1766 die;
1767 }
1768 global $dbxlink;
1769 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1770 $result = $dbxlink->query ($query);
1771 if ($result == NULL)
1772 {
1773 showError ('SQL query failed', __FUNCTION__);
1774 die;
1775 }
1776 return TRUE;
1777 }
1778
1779 // FIXME: don't share common code with use commitResetAttrValue()
1780 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
1781 {
1782 if ($object_id <= 0 or $attr_id <= 0)
1783 {
1784 showError ('Invalid arguments', __FUNCTION__);
1785 die;
1786 }
1787 if (empty ($value))
1788 return commitResetAttrValue ($object_id, $attr_id);
1789 global $dbxlink;
1790 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
1791 $result = $dbxlink->query ($query1);
1792 if ($result == NULL)
1793 {
1794 showError ('SQL query #1 failed', __FUNCTION__);
1795 die;
1796 }
1797 $row = $result->fetch (PDO::FETCH_NUM);
1798 if ($row == NULL)
1799 {
1800 showError ('SQL query #1 returned no results', __FUNCTION__);
1801 die;
1802 }
1803 $attr_type = $row[0];
1804 $result->closeCursor();
1805 switch ($attr_type)
1806 {
1807 case 'uint':
1808 case 'float':
1809 case 'string':
1810 $column = $attr_type . '_value';
1811 break;
1812 case 'dict':
1813 $column = 'uint_value';
1814 break;
1815 default:
1816 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
1817 die;
1818 }
1819 $query2 =
1820 "delete from AttributeValue where " .
1821 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1822 $result = $dbxlink->query ($query2);
1823 if ($result == NULL)
1824 {
1825 showError ('SQL query #2 failed', __FUNCTION__);
1826 die;
1827 }
1828 // We know $value isn't empty here.
1829 $query3 =
1830 "insert into AttributeValue set ${column} = '${value}', " .
1831 "object_id = ${object_id}, attr_id = ${attr_id} ";
1832 $result = $dbxlink->query ($query3);
1833 if ($result == NULL)
1834 {
1835 showError ('SQL query #3 failed', __FUNCTION__);
1836 die;
1837 }
1838 return TRUE;
1839 }
1840
1841 function commitUseupPort ($port_id = 0)
1842 {
1843 if ($port_id <= 0)
1844 {
1845 showError ("Invalid argument", __FUNCTION__);
1846 die;
1847 }
1848 global $dbxlink;
1849 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
1850 $result = $dbxlink->exec ($query);
1851 if ($result == NULL)
1852 {
1853 showError ("SQL query failed", __FUNCTION__);
1854 die;
1855 }
1856 return TRUE;
1857
1858 }
1859
1860 // This is a swiss-knife blade to insert a record into a table.
1861 // The first argument is table name.
1862 // The second argument is an array of "name" => "value" pairs.
1863 // The function returns either TRUE or FALSE (we expect one row
1864 // to be inserted).
1865 function useInsertBlade ($tablename, $values)
1866 {
1867 global $dbxlink;
1868 $namelist = $valuelist = '';
1869 foreach ($values as $name => $value)
1870 {
1871 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
1872 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
1873 }
1874 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
1875 $result = $dbxlink->exec ($query);
1876 if ($result != 1)
1877 return FALSE;
1878 return TRUE;
1879 }
1880
1881 // This swiss-knife blade deletes one record from the specified table
1882 // using the specified key name and value.
1883 function useDeleteBlade ($tablename, $keyname, $keyvalue, $quotekey = TRUE, $deleteall = FALSE)
1884 {
1885 global $dbxlink;
1886 if ($quotekey == TRUE)
1887 $keyvalue = "'${keyvalue}'";
1888 $query = "delete from ${tablename} where ${keyname}=$keyvalue";
1889 if (!$deleteall)
1890 $query .= ' limit 1';
1891 $result = $dbxlink->exec ($query);
1892 if ($result === NULL)
1893 return FALSE;
1894 elseif (!$deleteall && $result != 1)
1895 return FALSE;
1896 else
1897 return TRUE;
1898 }
1899
1900 function useSelectBlade ($query, $caller = 'N/A')
1901 {
1902 global $dbxlink;
1903 $result = $dbxlink->query ($query);
1904 if ($result == NULL)
1905 {
1906 $ei = $dbxlink->errorInfo();
1907 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
1908 return NULL;
1909 }
1910 return $result;
1911 }
1912
1913 function loadConfigCache ()
1914 {
1915 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
1916 $result = useSelectBlade ($query, __FUNCTION__);
1917 $cache = array();
1918 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1919 $cache[$row['varname']] = $row;
1920 $result->closeCursor();
1921 return $cache;
1922 }
1923
1924 // setConfigVar() is expected to perform all necessary filtering
1925 function storeConfigVar ($varname = NULL, $varvalue = NULL)
1926 {
1927 global $dbxlink;
1928 if (empty ($varname) || $varvalue === NULL)
1929 {
1930 showError ('Invalid arguments', __FUNCTION__);
1931 return FALSE;
1932 }
1933 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
1934 $result = $dbxlink->query ($query);
1935 if ($result == NULL)
1936 {
1937 showError ("SQL query '${query}' failed", __FUNCTION__);
1938 return FALSE;
1939 }
1940 $rc = $result->rowCount();
1941 $result->closeCursor();
1942 if ($rc == 0 or $rc == 1)
1943 return TRUE;
1944 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
1945 return FALSE;
1946 }
1947
1948 // Database version detector. Should behave corretly on any
1949 // working dataset a user might have.
1950 function getDatabaseVersion ()
1951 {
1952 global $dbxlink;
1953 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
1954 $result = $dbxlink->query ($query);
1955 if ($result == NULL)
1956 {
1957 $errorInfo = $dbxlink->errorInfo();
1958 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
1959 return '0.14.4';
1960 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
1961 }
1962 $rows = $result->fetchAll (PDO::FETCH_NUM);
1963 if (count ($rows) != 1 || empty ($rows[0][0]))
1964 {
1965 $result->closeCursor();
1966 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
1967 }
1968 $ret = $rows[0][0];
1969 $result->closeCursor();
1970 return $ret;
1971 }
1972
1973 // Return an array of virtual services. For each of them list real server pools
1974 // with their load balancers and other stats.
1975 function getSLBSummary ()
1976 {
1977 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
1978 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
1979 'from IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id ' .
1980 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
1981 'left join IPRealServer as rs on rs.rspool_id = lb.rspool_id ' .
1982 'group by vs.id, object_id order by vs.vip, object_id';
1983 $result = useSelectBlade ($query, __FUNCTION__);
1984 $ret = array();
1985 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1986 {
1987 $vsid = $row['vsid'];
1988 $object_id = $row['object_id'];
1989 if (!isset ($ret[$vsid]))
1990 {
1991 $ret[$vsid] = array();
1992 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
1993 $ret[$vsid][$cname] = $row[$cname];
1994 $ret[$vsid]['lblist'] = array();
1995 }
1996 // There's only one assigned RS pool possible for each LB-VS combination.
1997 $ret[$vsid]['lblist'][$row['object_id']] = array
1998 (
1999 'id' => $row['rspool_id'],
2000 'size' => $row['rscount'],
2001 'name' => $row['pool_name']
2002 );
2003 }
2004 $result->closeCursor();
2005 return $ret;
2006 }
2007
2008 // Get the detailed composition of a particular virtual service, namely the list
2009 // of all pools, each shown with the list of objects servicing it. VS/RS configs
2010 // will be returned as well.
2011 function getVServiceInfo ($vsid = 0)
2012 {
2013 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2014 "from IPVirtualService where id = ${vsid}";
2015 $result = useSelectBlade ($query1, __FUNCTION__);
2016 $vsinfo = array ();
2017 $row = $result->fetch (PDO::FETCH_ASSOC);
2018 if (!$row)
2019 return NULL;
2020 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2021 $vsinfo[$cname] = $row[$cname];
2022 $vsinfo['rspool'] = array();
2023 $result->closeCursor();
2024 unset ($result);
2025 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2026 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
2027 "IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2028 "where vs_id = ${vsid} order by pool.name, object_id";
2029 $result = useSelectBlade ($query2, __FUNCTION__);
2030 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2031 {
2032 if (!isset ($vsinfo['rspool'][$row['id']]))
2033 {
2034 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2035 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2036 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2037 $vsinfo['rspool'][$row['id']]['lblist'] = array();
2038 }
2039 if ($row['object_id'] == NULL)
2040 continue;
2041 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2042 (
2043 'vsconfig' => $row['lb_vsconfig'],
2044 'rsconfig' => $row['lb_rsconfig']
2045 );
2046 }
2047 $result->closeCursor();
2048 return $vsinfo;
2049 }
2050
2051 // Collect and return the following info about the given real server pool:
2052 // basic information
2053 // parent virtual service information
2054 // load balancers list (each with a list of VSes)
2055 // real servers list
2056
2057 function getRSPoolInfo ($id = 0)
2058 {
2059 $query1 = "select id, name, vsconfig, rsconfig from " .
2060 "IPRSPool where id = ${id}";
2061 $result = useSelectBlade ($query1, __FUNCTION__);
2062 $ret = array();
2063 $row = $result->fetch (PDO::FETCH_ASSOC);
2064 if (!$row)
2065 return NULL;
2066 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
2067 $ret[$c] = $row[$c];
2068 $result->closeCursor();
2069 unset ($result);
2070 $ret['lblist'] = array();
2071 $ret['rslist'] = array();
2072 $query2 = "select object_id, vs_id, vsconfig, rsconfig from IPLoadBalancer " .
2073 "where rspool_id = ${id} order by object_id, vs_id";
2074 $result = useSelectBlade ($query2, __FUNCTION__);
2075 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2076 foreach (array ('vsconfig', 'rsconfig') as $c)
2077 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
2078 $result->closeCursor();
2079 unset ($result);
2080 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
2081 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
2082 $result = useSelectBlade ($query3, __FUNCTION__);
2083 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2084 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
2085 $ret['rslist'][$row['id']][$c] = $row[$c];
2086 $result->closeCursor();
2087 return $ret;
2088 }
2089
2090 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2091 {
2092 if ($pool_id <= 0 or $rsport <= 0)
2093 {
2094 showError ('Invalid arguments', __FUNCTION__);
2095 die;
2096 }
2097 return useInsertBlade
2098 (
2099 'IPRealServer',
2100 array
2101 (
2102 'rsip' => "inet_aton('${rsip}')",
2103 'rsport' => $rsport,
2104 'rspool_id' => $pool_id,
2105 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
2106 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2107 )
2108 );
2109 }
2110
2111 function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig)
2112 {
2113 if (empty ($vip) or $vport <= 0 or empty ($proto))
2114 {
2115 showError ('Invalid arguments', __FUNCTION__);
2116 die;
2117 }
2118 return useInsertBlade
2119 (
2120 'IPVirtualService',
2121 array
2122 (
2123 'vip' => "inet_aton('${vip}')",
2124 'vport' => $vport,
2125 'proto' => "'${proto}'",
2126 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2127 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2128 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2129 )
2130 );
2131 }
2132
2133 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2134 {
2135 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
2136 {
2137 showError ('Invalid arguments', __FUNCTION__);
2138 die;
2139 }
2140 return useInsertBlade
2141 (
2142 'IPLoadBalancer',
2143 array
2144 (
2145 'object_id' => $object_id,
2146 'rspool_id' => $pool_id,
2147 'vs_id' => $vs_id,
2148 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2149 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2150 )
2151 );
2152 }
2153
2154 function commitDeleteRS ($id = 0)
2155 {
2156 if ($id <= 0)
2157 return FALSE;
2158 return useDeleteBlade ('IPRealServer', 'id', $id, FALSE);
2159 }
2160
2161 function commitDeleteVS ($id = 0)
2162 {
2163 if ($id <= 0)
2164 return FALSE;
2165 return useDeleteBlade ('IPVirtualService', 'id', $id, FALSE) && deleteTagsForEntity ('ipv4vs', $id);
2166 }
2167
2168 function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
2169 {
2170 global $dbxlink;
2171 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2172 return FALSE;
2173 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2174 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
2175 $result = $dbxlink->exec ($query);
2176 if ($result === NULL)
2177 return FALSE;
2178 elseif ($result != 1)
2179 return FALSE;
2180 else
2181 return TRUE;
2182 }
2183
2184 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2185 {
2186 if ($rsid <= 0 or $rsport <= 0)
2187 {
2188 showError ('Invalid args', __FUNCTION__);
2189 die;
2190 }
2191 if (long2ip (ip2long ($rsip)) !== $rsip)
2192 {
2193 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2194 die;
2195 }
2196 global $dbxlink;
2197 $query =
2198 "update IPRealServer set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
2199 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2200 " where id = ${rsid} limit 1";
2201 $result = $dbxlink->query ($query);
2202 if ($result == NULL)
2203 {
2204 showError ("SQL query '${query}' failed", __FUNCTION__);
2205 die;
2206 }
2207 return TRUE;
2208 }
2209
2210 function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2211 {
2212 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2213 {
2214 showError ('Invalid args', __FUNCTION__);
2215 die;
2216 }
2217 global $dbxlink;
2218 $query =
2219 "update IPLoadBalancer set vsconfig = " .
2220 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2221 ', rsconfig = ' .
2222 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2223 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2224 "and vs_id = ${vs_id} limit 1";
2225 $result = $dbxlink->exec ($query);
2226 if ($result === NULL)
2227 return FALSE;
2228 else
2229 return TRUE;
2230 }
2231
2232 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2233 {
2234 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2235 {
2236 showError ('Invalid args', __FUNCTION__);
2237 die;
2238 }
2239 global $dbxlink;
2240 $query = "update IPVirtualService set " .
2241 "vip = inet_aton('${vip}'), " .
2242 "vport = ${vport}, " .
2243 "proto = '${proto}', " .
2244 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2245 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2246 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2247 " where id = ${vsid} limit 1";
2248 $result = $dbxlink->exec ($query);
2249 if ($result === NULL)
2250 return FALSE;
2251 else
2252 return TRUE;
2253 }
2254
2255 // Return the list of virtual services, indexed by vs_id.
2256 // Each record will be shown with its basic info plus RS pools counter.
2257 function getVSList ($tagfilter = array())
2258 {
2259 $whereclause = getWhereClause ($tagfilter);
2260 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2261 "from IPVirtualService as vs left join IPLoadBalancer as lb on vs.id = lb.vs_id " .
2262 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
2263 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
2264 $result = useSelectBlade ($query, __FUNCTION__);
2265 $ret = array ();
2266 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2267 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
2268 $ret[$row['id']][$cname] = $row[$cname];
2269 $result->closeCursor();
2270 return $ret;
2271 }
2272
2273 // Return the list of RS pool, indexed by pool id.
2274 function getRSPoolList ($tagfilter = array())
2275 {
2276 $whereclause = getWhereClause ($tagfilter);
2277 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2278 "from IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2279 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
2280 "where true ${whereclause} group by pool.id order by pool.id, name";
2281 $result = useSelectBlade ($query, __FUNCTION__);
2282 $ret = array ();
2283 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2284 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
2285 $ret[$row['id']][$cname] = $row[$cname];
2286 $result->closeCursor();
2287 return $ret;
2288 }
2289
2290 function loadThumbCache ($rack_id = 0)
2291 {
2292 $ret = NULL;
2293 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
2294 $result = useSelectBlade ($query, __FUNCTION__);
2295 $row = $result->fetch (PDO::FETCH_ASSOC);
2296 if ($row)
2297 $ret = base64_decode ($row['thumb_data']);
2298 $result->closeCursor();
2299 return $ret;
2300 }
2301
2302 function saveThumbCache ($rack_id = 0, $cache = NULL)
2303 {
2304 global $dbxlink;
2305 if ($rack_id == 0 or $cache == NULL)
2306 {
2307 showError ('Invalid arguments', __FUNCTION__);
2308 return;
2309 }
2310 $data = base64_encode ($cache);
2311 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2312 $result = $dbxlink->exec ($query);
2313 }
2314
2315 function resetThumbCache ($rack_id = 0)
2316 {
2317 global $dbxlink;
2318 if ($rack_id == 0)
2319 {
2320 showError ('Invalid argument', __FUNCTION__);
2321 return;
2322 }
2323 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2324 $result = $dbxlink->exec ($query);
2325 }
2326
2327 // Return the list of attached RS pools for the given object. As long as we have
2328 // the LB-VS UNIQUE in IPLoadBalancer table, it is Ok to key returned records
2329 // by vs_id, because there will be only one RS pool listed for each VS of the
2330 // current object.
2331 function getRSPoolsForObject ($object_id = 0)
2332 {
2333 if ($object_id <= 0)
2334 {
2335 showError ('Invalid object_id', __FUNCTION__);
2336 return NULL;
2337 }
2338 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2339 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
2340 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2341 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2342 'left join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2343 "where lb.object_id = ${object_id} " .
2344 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
2345 $result = useSelectBlade ($query, __FUNCTION__);
2346 $ret = array ();
2347 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2348 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
2349 $ret[$row['vs_id']][$cname] = $row[$cname];
2350 $result->closeCursor();
2351 return $ret;
2352 }
2353
2354 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '')
2355 {
2356 return useInsertBlade
2357 (
2358 'IPRSPool',
2359 array
2360 (
2361 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2362 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2363 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2364 )
2365 );
2366 }
2367
2368 function commitDeleteRSPool ($pool_id = 0)
2369 {
2370 global $dbxlink;
2371 if ($pool_id <= 0)
2372 return FALSE;
2373 return useDeleteBlade ('IPRSPool', 'id', $pool_id, FALSE) && deleteTagsForEntity ('ipv4rspool', $pool_id);
2374 }
2375
2376 function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2377 {
2378 if ($pool_id <= 0)
2379 {
2380 showError ('Invalid arg', __FUNCTION__);
2381 die;
2382 }
2383 global $dbxlink;
2384 $query = "update IPRSPool set " .
2385 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2386 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2387 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2388 " where id = ${pool_id} limit 1";
2389 $result = $dbxlink->exec ($query);
2390 if ($result === NULL)
2391 return FALSE;
2392 elseif ($result != 1)
2393 return FALSE;
2394 else
2395 return TRUE;
2396 }
2397
2398 function getRSList ()
2399 {
2400 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2401 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
2402 $result = useSelectBlade ($query, __FUNCTION__);
2403 $ret = array ();
2404 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2405 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2406 $ret[$row['id']][$cname] = $row[$cname];
2407 $result->closeCursor();
2408 return $ret;
2409 }
2410
2411 // Return the list of all currently configured load balancers with their pool count.
2412 function getLBList ()
2413 {
2414 $query = "select object_id, count(rspool_id) as poolcount " .
2415 "from IPLoadBalancer group by object_id order by object_id";
2416 $result = useSelectBlade ($query, __FUNCTION__);
2417 $ret = array ();
2418 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2419 $ret[$row['object_id']] = $row['poolcount'];
2420 $result->closeCursor();
2421 return $ret;
2422 }
2423
2424 // For the given object return: it vsconfig/rsconfig; the list of RS pools
2425 // attached (each with vsconfig/rsconfig in turn), each with the list of
2426 // virtual services terminating the pool. Each pool also lists all real
2427 // servers with rsconfig.
2428 function buildLBConfig ($object_id)
2429 {
2430 if ($object_id <= 0)
2431 {
2432 showError ('Invalid arg', __FUNCTION__);
2433 return NULL;
2434 }
2435 $ret = array();
2436 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2437 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2438 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
2439 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2440 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2441 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2442 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2443 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2444 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2445 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
2446 $result = useSelectBlade ($query, __FUNCTION__);
2447 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2448 {
2449 $vs_id = $row['vs_id'];
2450 if (!isset ($ret[$vs_id]))
2451 {
2452 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)
2453 $ret[$vs_id][$c] = $row[$c];
2454 $ret[$vs_id]['rslist'] = array();
2455 }
2456 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2457 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2458 }
2459 $result->closeCursor();
2460 return $ret;
2461 }
2462
2463 function commitSetInService ($rs_id = 0, $inservice = '')
2464 {
2465 if ($rs_id <= 0 or empty ($inservice))
2466 {
2467 showError ('Invalid args', __FUNCTION__);
2468 return NULL;
2469 }
2470 global $dbxlink;
2471 $query = "update IPRealServer set inservice = '${inservice}' where id = ${rs_id} limit 1";
2472 $result = $dbxlink->exec ($query);
2473 if ($result === NULL)
2474 return FALSE;
2475 elseif ($result != 1)
2476 return FALSE;
2477 else
2478 return TRUE;
2479 }
2480
2481 function executeAutoPorts ($object_id = 0, $type_id = 0)
2482 {
2483 if ($object_id == 0 or $type_id == 0)
2484 {
2485 showError ('Invalid arguments', __FUNCTION__);
2486 die;
2487 }
2488 $ret = TRUE;
2489 foreach (getAutoPorts ($type_id) as $autoport)
2490 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2491 return $ret;
2492 }
2493
2494 // Return only implicitly listed tags, the rest of the chain will be
2495 // generated/deducted later at higher levels.
2496 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2497 {
2498 if ($entity_realm == '' or $entity_id <= 0)
2499 {
2500 showError ('Invalid or missing arguments', __FUNCTION__);
2501 return NULL;
2502 }
2503 $ret = array();
2504 $result = useSelectBlade ("select tt.id, tag from TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id where target_realm = '${entity_realm}' and target_id = ${entity_id}", __FUNCTION__);
2505 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2506 $ret[$row['id']] = $row;
2507 $result->closeCursor();
2508 return $ret;
2509 }
2510
2511 function loadRackObjectTags ($id)
2512 {
2513 return loadEntityTags ('object', $id);
2514 }
2515
2516 function loadIPv4PrefixTags ($id)
2517 {
2518 return loadEntityTags ('ipv4net', $id);
2519 }
2520
2521 function loadRackTags ($id)
2522 {
2523 return loadEntityTags ('rack', $id);
2524 }
2525
2526 function loadIPv4VSTags ($id)
2527 {
2528 return loadEntityTags ('ipv4vs', $id);
2529 }
2530
2531 function loadIPv4RSPoolTags ($id)
2532 {
2533 return loadEntityTags ('ipv4rspool', $id);
2534 }
2535
2536 function loadUserTags ($user_id)
2537 {
2538 return loadEntityTags ('user', $user_id);
2539 }
2540
2541 function getTagList ()
2542 {
2543 $ret = array();
2544 $query = "select id, parent_id, tag, target_realm as realm, count(target_id) as refcnt " .
2545 "from TagTree left join TagStorage on id = tag_id " .
2546 "group by id, target_realm order by tag";
2547 $result = useSelectBlade ($query, __FUNCTION__);
2548 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2549 {
2550 if (!isset ($ret[$row['id']]))
2551 $ret[$row['id']] = array
2552 (
2553 'id' => $row['id'],
2554 'tag' => $row['tag'],
2555 'parent_id' => $row['parent_id'],
2556 'refcnt' => array()
2557 );
2558 if ($row['realm'])
2559 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2560 }
2561 $result->closeCursor();
2562 return $ret;
2563 }
2564
2565 function commitCreateTag ($tagname = '', $parent_id = 0)
2566 {
2567 if ($tagname == '' or $parent_id === 0)
2568 return "Invalid args to " . __FUNCTION__;
2569 $result = useInsertBlade
2570 (
2571 'TagTree',
2572 array
2573 (
2574 'tag' => "'${tagname}'",
2575 'parent_id' => $parent_id
2576 )
2577 );
2578 if ($result)
2579 return '';
2580 else
2581 return "SQL query failed in " . __FUNCTION__;
2582 }
2583
2584 function commitDestroyTag ($tagid = 0)
2585 {
2586 if ($tagid == 0)
2587 return 'Invalid arg to ' . __FUNCTION__;
2588 if (useDeleteBlade ('TagTree', 'id', $tagid, FALSE))
2589 return '';
2590 else
2591 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2592 }
2593
2594 function commitUpdateTag ($tag_id, $tag_name, $parent_id)
2595 {
2596 if ($parent_id == 0)
2597 $parent_id = 'NULL';
2598 global $dbxlink;
2599 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2600 "where id = ${tag_id} limit 1";
2601 $result = $dbxlink->exec ($query);
2602 if ($result === NULL)
2603 return 'SQL query failed in ' . __FUNCTION__;
2604 return '';
2605 }
2606
2607 function deleteTagsForEntity ($entity_realm, $entity_id)
2608 {
2609 global $dbxlink;
2610 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id}";
2611 $result = $dbxlink->exec ($query);
2612 if ($result === NULL)
2613 return FALSE;
2614 else
2615 return TRUE;
2616 }
2617
2618 function addTagForEntity ($realm, $entity_id, $tag_id)
2619 {
2620 return useInsertBlade
2621 (
2622 'TagStorage',
2623 array
2624 (
2625 'target_realm' => "'${realm}'",
2626 'target_id' => $entity_id,
2627 'tag_id' => $tag_id,
2628 )
2629 );
2630 }
2631
2632 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2633 {
2634 // $range is in x.x.x.x/x format, split into ip/mask vars
2635 $rangeArray = explode('/', $range);
2636 if (count ($rangeArray) != 2)
2637 return "Invalid IPv4 prefix '${range}'";
2638 $ip = $rangeArray[0];
2639 $mask = $rangeArray[1];
2640
2641 if (empty ($ip) or empty ($mask))
2642 return "Invalid IPv4 prefix '${range}'";
2643 $ipL = ip2long($ip);
2644 $maskL = ip2long($mask);
2645 if ($ipL == -1 || $ipL === FALSE)
2646 return 'Bad IPv4 address';
2647 if ($mask < 32 && $mask > 0)
2648 $maskL = $mask;
2649 else
2650 {
2651 $maskB = decbin($maskL);
2652 if (strlen($maskB)!=32)
2653 return 'Invalid netmask';
2654 $ones=0;
2655 $zeroes=FALSE;
2656 foreach( str_split ($maskB) as $digit)
2657 {
2658 if ($digit == '0')
2659 $zeroes = TRUE;
2660 if ($digit == '1')
2661 {
2662 $ones++;
2663 if ($zeroes == TRUE)
2664 return 'Invalid netmask';
2665 }
2666 }
2667 $maskL = $ones;
2668 }
2669 $binmask = binMaskFromDec($maskL);
2670 $ipL = $ipL & $binmask;
2671
2672 $query =
2673 "select ".
2674 "id, ip, mask, name ".
2675 "from IPRanges ";
2676
2677 $result = useSelectBlade ($query, __FUNCTION__);
2678
2679 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2680 {
2681 $otherip = $row['ip'];
2682 $othermask = binMaskFromDec($row['mask']);
2683 if (($otherip & $othermask) == ($ipL & $othermask))
2684 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
2685 if (($otherip & $binmask) == ($ipL & $binmask))
2686 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
2687 }
2688 $result->closeCursor();
2689 unset ($result);
2690 $result = useInsertBlade
2691 (
2692 'IPRanges',
2693 array
2694 (
2695 'ip' => sprintf ('%u', $ipL),
2696 'mask' => "'${maskL}'",
2697 'name' => "'${name}'"
2698 )
2699 );
2700
2701 if ($is_bcast and $maskL < 31)
2702 {
2703 $network_addr = long2ip ($ipL);
2704 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
2705 updateAddress ($network_addr, 'network', 'yes');
2706 updateAddress ($broadcast_addr, 'broadcast', 'yes');
2707 }
2708 if (!count ($taglist))
2709 return '';
2710 if (($result = useSelectBlade ('select last_insert_id()', __FUNCTION__)) == NULL)
2711 return 'Query #3 failed in ' . __FUNCTION__;
2712 $row = $result->fetch (PDO::FETCH_NUM);
2713 $last_insert_id = $row[0];
2714 $result->closeCursor();
2715 unset ($result);
2716 $errcount = 0;
2717 foreach ($taglist as $tag_id)
2718 if (addTagForEntity ('ipv4net', $last_insert_id, $tag_id) == FALSE)
2719 $errcount++;
2720 if (!$errcount)
2721 return '';
2722 else
2723 return "Experienced ${errcount} errors adding tags for the IPv4 prefix";
2724 }
2725
2726 // FIXME: This function doesn't wipe relevant records from IPAddress table.
2727 function destroyIPv4Prefix ($id = 0)
2728 {
2729 if ($id <= 0)
2730 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
2731 if (!useDeleteBlade ('IPRanges', 'id', $id, FALSE))
2732 return __FUNCTION__ . ': SQL query #1 failed';
2733 if (!deleteTagsForEntity ('ipv4net', $id))
2734 return __FUNCTION__ . ': SQL query #2 failed';
2735 return '';
2736 }
2737
2738 function loadScript ($name)
2739 {
2740 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
2741 $row = $result->fetch (PDO::FETCH_NUM);
2742 return $row[0];
2743 }
2744
2745 function saveScript ($name, $text)
2746 {
2747 if (empty ($name))
2748 {
2749 showError ('Invalid argument');
2750 return FALSE;
2751 }
2752 return useDeleteBlade ('Script', 'script_name', $name, TRUE) && useInsertBlade
2753 (
2754 'Script',
2755 array
2756 (
2757 'script_name' => "'${name}'",
2758 'script_text' => "'${text}'"
2759 )
2760 );
2761 }
2762
2763 function saveUserPassword ($user_id, $newp)
2764 {
2765 $newhash = hash (PASSWORD_HASH, $newp);
2766 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
2767 }
2768
2769 function objectIsPortless ($id = 0)
2770 {
2771 if ($id <= 0)
2772 {
2773 showError ('Invalid argument', __FUNCTION__);
2774 return;
2775 }
2776 if (($result = useSelectBlade ("select count(id) from Port where object_id = ${id}", __FUNCTION__)) == NULL)
2777 {
2778 showError ('SQL query failed', __FUNCTION__);
2779 return;
2780 }
2781 $row = $result->fetch (PDO::FETCH_NUM);
2782 $count = $row[0];
2783 $result->closeCursor();
2784 unset ($result);
2785 return $count === 0;
2786 }
2787
2788 ?>