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