r2027 + reformat IPv4 SLB output a bit
[racktables] / inc / database.php
CommitLineData
b325120a 1<?php
e673ee24
DO
2/*
3*
4* This file is a library of database access functions for RackTables.
5*
6*/
7
5f54485b 8function escapeString ($value, $do_db_escape = TRUE)
e673ee24 9{
6c6f62e8 10 $ret = htmlentities ($value, ENT_QUOTES, 'UTF-8');
5f54485b
DO
11 if ($do_db_escape)
12 {
13 global $dbxlink;
14 $ret = substr ($dbxlink->quote ($ret), 1, -1);
15 }
16 return $ret;
e673ee24
DO
17}
18
11c8e4be 19function getRackspace ($tagfilter = array(), $tfmode = 'any')
489a7502 20{
81736ac1 21 $whereclause = getWhereClause ($tagfilter);
489a7502 22 $query =
a0d54e7e 23 "select dict_key as row_id, dict_value as row_name " .
489a7502
DO
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 .
a0d54e7e 28 " order by dict_value";
065eeb52 29 $result = useSelectBlade ($query, __FUNCTION__);
489a7502 30 $ret = array();
a0d54e7e 31 $clist = array ('row_id', 'row_name');
489a7502 32 while ($row = $result->fetch (PDO::FETCH_ASSOC))
64b95774 33 foreach ($clist as $cname)
a0d54e7e 34 $ret[$row['row_id']][$cname] = $row[$cname];
489a7502
DO
35 $result->closeCursor();
36 return $ret;
37}
38
a8ce7234
DO
39// Return detailed information about one rack row.
40function getRackRowInfo ($rackrow_id)
e673ee24 41{
e673ee24 42 $query =
a8ce7234 43 "select dict_key as id, dict_value as name, count(Rack.id) as count, " .
5332840f
DO
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 " .
a8ce7234
DO
46 "where chapter_name = 'RackRow' and dict_key = ${rackrow_id} " .
47 "group by dict_key";
065eeb52 48 $result = useSelectBlade ($query, __FUNCTION__);
a8ce7234
DO
49 if ($row = $result->fetch (PDO::FETCH_ASSOC))
50 return $row;
e673ee24 51 else
a8ce7234 52 return NULL;
e673ee24
DO
53}
54
55// This function returns id->name map for all object types. The map is used
56// to build <select> input for objects.
57function getObjectTypeList ()
58{
59 return readChapter ('RackObjectType');
60}
61
489a7502
DO
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.
81736ac1 64function getWhereClause ($tagfilter = array())
e673ee24 65{
105cea6e 66 $whereclause = '';
105cea6e 67 if (count ($tagfilter))
7cc02fc1 68 {
105cea6e 69 $whereclause .= ' and (';
11c8e4be 70 $conj = '';
7cc02fc1
DO
71 foreach ($tagfilter as $tag_id)
72 {
11c8e4be 73 $whereclause .= $conj . 'tag_id = ' . $tag_id;
81736ac1 74 $conj = ' or ';
7cc02fc1
DO
75 }
76 $whereclause .= ') ';
77 }
489a7502
DO
78 return $whereclause;
79}
80
e9132485
DO
81// Return a simple object list w/o related information.
82function 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.
11c8e4be 114function getObjectList ($type_id = 0, $tagfilter = array(), $tfmode = 'any')
489a7502 115{
81736ac1 116 $whereclause = getWhereClause ($tagfilter);
489a7502
DO
117 if ($type_id != 0)
118 $whereclause .= " and objtype_id = '${type_id}' ";
e673ee24
DO
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 " .
7cc02fc1 126 "left join TagStorage on RackObject.id = TagStorage.target_id and target_realm = 'object' " .
105cea6e 127 "where RackObject.deleted = 'no' and chapter_name = 'RackObjectType' " .
7cc02fc1
DO
128 $whereclause .
129 "order by name";
065eeb52 130 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24 131 $ret = array();
e673ee24
DO
132 while ($row = $result->fetch (PDO::FETCH_ASSOC))
133 {
2ac47ae4
DO
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)
e673ee24
DO
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
11c8e4be 152function getRacksForRow ($row_id = 0, $tagfilter = array(), $tfmode = 'any')
e673ee24 153{
e673ee24 154 $query =
1c81a02c 155 "select Rack.id, Rack.name, height, Rack.comment, row_id, " .
2d7698a2 156 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name " .
e673ee24 157 "from Rack left join Dictionary on row_id = dict_key natural join Chapter " .
932cf41f 158 "left join TagStorage on Rack.id = TagStorage.target_id and target_realm = 'rack' " .
e673ee24
DO
159 "where chapter_name = 'RackRow' and Rack.deleted = 'no' " .
160 (($row_id == 0) ? "" : "and row_id = ${row_id} ") .
81736ac1 161 getWhereClause ($tagfilter) .
932cf41f 162 " order by row_name, Rack.id";
065eeb52 163 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24 164 $ret = array();
1c81a02c
DO
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 );
e673ee24 176 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1c81a02c 177 foreach ($clist as $cname)
e673ee24
DO
178 $ret[$row['id']][$cname] = $row[$cname];
179 $result->closeCursor();
6a3a37b2 180 usort ($ret, 'sortRacks');
e673ee24
DO
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.
187function getRackData ($rack_id = 0, $silent = FALSE)
188{
189 if ($rack_id == 0)
190 {
191 if ($silent == FALSE)
f41b492f 192 showError ('Invalid rack_id', __FUNCTION__);
e673ee24
DO
193 return NULL;
194 }
e673ee24 195 $query =
1c81a02c 196 "select Rack.id, Rack.name, row_id, height, Rack.comment, " .
2d7698a2 197 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name from " .
e673ee24
DO
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";
065eeb52 200 $result = useSelectBlade ($query, __FUNCTION__);
89fa639f 201 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
e673ee24
DO
202 {
203 if ($silent == FALSE)
f41b492f 204 showError ('Query #1 succeded, but returned no data', __FUNCTION__);
e673ee24
DO
205 return NULL;
206 }
207
208 // load metadata
1c81a02c
DO
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];
89fa639f
DO
222 $result->closeCursor();
223 unset ($result);
e673ee24
DO
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";
065eeb52 235 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24 236 global $loclist;
89fa639f 237 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
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 }
89fa639f 242 $result->closeCursor();
e673ee24
DO
243 return $rack;
244}
245
246// This is a popular helper.
247function getObjectInfo ($object_id = 0)
248{
249 if ($object_id == 0)
250 {
f41b492f 251 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
252 return;
253 }
e673ee24
DO
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";
105a3bc8 258 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
259 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
260 {
105a3bc8 261 showError ('Query succeeded, but returned no data', __FUNCTION__);
e673ee24
DO
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();
105a3bc8 278 unset ($result);
e673ee24
DO
279 return $ret;
280}
281
282function getPortTypes ()
283{
fe6e3bd7 284 return readChapter ('PortType');
e673ee24
DO
285}
286
287function getObjectPortsAndLinks ($object_id = 0)
288{
289 if ($object_id == 0)
290 {
f41b492f 291 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
292 return;
293 }
e673ee24
DO
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";
065eeb52 319 $result = useSelectBlade ($query, __FUNCTION__);
e425f895
DO
320 $ret=array();
321 $count=0;
322 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 323 {
e425f895
DO
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']))
e673ee24 337 {
e425f895
DO
338 $oi = getObjectInfo ($row['RemotePort_object_id']);
339 $ret[$count]['remote_object_name'] = displayedName ($oi);
e673ee24 340 }
e425f895 341 $count++;
e673ee24
DO
342 }
343 $result->closeCursor();
344 return $ret;
345}
346
406b54bd 347function commitAddRack ($name, $height, $row_id, $comment, $taglist)
e673ee24 348{
406b54bd
DO
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)
e673ee24 361 {
406b54bd 362 showError ('useInsertBlade() failed', __FUNCTION__);
e673ee24
DO
363 return FALSE;
364 }
406b54bd 365
065eeb52 366 if (($result = useSelectBlade ('select last_insert_id()', __FUNCTION__)) == NULL)
e673ee24 367 {
406b54bd 368 showError ('Query #2 failed', __FUNCTION__);
e673ee24
DO
369 return FALSE;
370 }
371 // we always have a row
406b54bd 372 $row = $result->fetch (PDO::FETCH_NUM);
e673ee24 373 $last_insert_id = $row[0];
406b54bd 374 $result->closeCursor();
f60bb422 375 $errcount = 0;
406b54bd 376 foreach ($taglist as $tag_id)
42023f03 377 if (addTagForEntity ('rack', $last_insert_id, $tag_id) == FALSE)
406b54bd
DO
378 $errcount++;
379 if ($errcount)
380 showError ("Experienced ${errcount} errors adding tags for the rack");
e673ee24
DO
381 return recordHistory ('Rack', "id = ${last_insert_id}");
382}
383
f60bb422 384function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
e673ee24
DO
385{
386 global $dbxlink;
f60bb422
DO
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 );
e673ee24
DO
401 if ($result1 == NULL)
402 {
f60bb422 403 showError ("SQL query #1 failed", __FUNCTION__);
e673ee24
DO
404 return FALSE;
405 }
065eeb52 406 $result2 = useSelectBlade ('select last_insert_id()', __FUNCTION__);
e673ee24
DO
407 if ($result2 == NULL)
408 {
409 $errorInfo = $dbxlink->errorInfo();
f41b492f 410 showError ("SQL query '${query}' failed: ${errorInfo[2]}", __FUNCTION__);
e673ee24
DO
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();
ad0e4754
DO
417 // Do AutoPorts magic
418 executeAutoPorts ($last_insert_id, $new_type_id);
f60bb422
DO
419 // Now tags...
420 $errcount = 0;
421 foreach ($taglist as $tag_id)
42023f03
DO
422 if (addTagForEntity ('object', $last_insert_id, $tag_id) == FALSE)
423 $errcount++;
f60bb422
DO
424 if ($errcount)
425 showError ("Experienced ${errcount} errors adding tags for the object");
e673ee24
DO
426 return recordHistory ('RackObject', "id = ${last_insert_id}");
427}
428
429function 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 {
f41b492f 433 showError ('Not all required args are present.', __FUNCTION__);
e673ee24
DO
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 {
f41b492f 446 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
447 return FALSE;
448 }
e673ee24
DO
449 $result->closeCursor();
450 return recordHistory ('RackObject', "id = ${object_id}");
451}
452
453function 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 {
f41b492f 457 showError ('Not all required args are present.', __FUNCTION__);
e673ee24
DO
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 {
f41b492f 466 showError ('Error updating rack information', __FUNCTION__);
e673ee24
DO
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.
478function 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)
4d2e93f2 515 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL DELETE query failed");
e673ee24
DO
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)
4d2e93f2 523 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL INSERT query failed");
e673ee24
DO
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)
c7fe33be
DO
540 {
541 resetThumbCache ($rack_id);
e673ee24 542 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
c7fe33be 543 }
e673ee24
DO
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.
550function getMoleculeForObject ($object_id = 0)
551{
552 if ($object_id == 0)
553 {
f41b492f 554 showError ("object_id == 0", __FUNCTION__);
e673ee24
DO
555 return NULL;
556 }
e673ee24
DO
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";
065eeb52 560 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
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.
567function getMolecule ($mid = 0)
568{
569 if ($mid == 0)
570 {
f41b492f 571 showError ("mid == 0", __FUNCTION__);
e673ee24
DO
572 return NULL;
573 }
e673ee24
DO
574 $query =
575 "select rack_id, unit_no, atom from Atom " .
576 "where molecule_id=${mid}";
065eeb52 577 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
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.
585function createMolecule ($molData)
586{
587 global $dbxlink;
588 $query = "insert into Molecule values()";
589 $result1 = $dbxlink->query ($query);
590 if ($result1->rowCount() != 1)
591 {
f41b492f 592 showError ('Error inserting into Molecule', __FUNCTION__);
e673ee24
DO
593 return NULL;
594 }
595 $query = 'select last_insert_id()';
596 $result2 = $dbxlink->query ($query);
597 if ($result2 == NULL)
598 {
f41b492f 599 showError ('Cannot get last ID.', __FUNCTION__);
e673ee24
DO
600 return NULL;
601 }
602 $row = $result2->fetch (PDO::FETCH_NUM);
603 $molecule_id = $row[0];
604 $result2->closeCursor();
64b95774 605 foreach ($molData as $rua)
e673ee24
DO
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 {
f41b492f 616 showError ('Error inserting into Atom', __FUNCTION__);
e673ee24
DO
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'.
628function 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 {
863b199a 635 showError ("SQL query '${query}' failed for table ${tableName}", __FUNCTION__);
e673ee24
DO
636 return FALSE;
637 }
638 return TRUE;
639}
640
641function getRackspaceHistory ()
642{
e673ee24
DO
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";
065eeb52 648 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
649 $ret = $result->fetchAll(PDO::FETCH_ASSOC);
650 $result->closeCursor();
651 return $ret;
652}
653
654// This function is used in renderRackspaceHistory()
655function getOperationMolecules ($op_id = 0)
656{
657 if ($op_id <= 0)
658 {
f41b492f 659 showError ("Missing argument", __FUNCTION__);
e673ee24
DO
660 return;
661 }
e673ee24 662 $query = "select old_molecule_id, new_molecule_id from MountOperation where id = ${op_id}";
065eeb52 663 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
664 // We expect one row.
665 $row = $result->fetch (PDO::FETCH_ASSOC);
666 if ($row == NULL)
667 {
f41b492f 668 showError ("SQL query succeded, but returned no results.", __FUNCTION__);
e673ee24
DO
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
c7fe33be 677function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
e673ee24
DO
678{
679 if ($object_id <= 0)
680 {
f41b492f 681 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
682 return;
683 }
684 $query = "select distinct rack_id from RackSpace where object_id = ${object_id} order by rack_id";
065eeb52 685 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
686 $rows = $result->fetchAll (PDO::FETCH_NUM);
687 $result->closeCursor();
688 $ret = array();
689 foreach ($rows as $row)
690 {
b422aee6
DO
691 if (!$fetch_rackdata)
692 {
693 $ret[$row[0]] = $row[0];
694 continue;
695 }
e673ee24
DO
696 $rackData = getRackData ($row[0]);
697 if ($rackData == NULL)
698 {
f41b492f 699 showError ('getRackData() failed', __FUNCTION__);
e673ee24
DO
700 return NULL;
701 }
702 $ret[$row[0]] = $rackData;
703 }
704 $result->closeCursor();
705 return $ret;
706}
707
7cc02fc1 708function getObjectGroupInfo ()
e673ee24
DO
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" ' .
7cc02fc1 714 'group by dict_key order by dict_value';
065eeb52 715 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24 716 $ret = array();
105cea6e 717 $ret[0] = array ('id' => 0, 'name' => 'ALL types');
e673ee24 718 $clist = array ('id', 'name', 'count');
105cea6e 719 $total = 0;
e673ee24 720 while ($row = $result->fetch (PDO::FETCH_ASSOC))
7cc02fc1 721 if ($row['count'] > 0)
105cea6e
DO
722 {
723 $total += $row['count'];
64b95774 724 foreach ($clist as $cname)
7cc02fc1 725 $ret[$row['id']][$cname] = $row[$cname];
105cea6e 726 }
e673ee24 727 $result->closeCursor();
105cea6e 728 $ret[0]['count'] = $total;
7cc02fc1 729 return $ret;
e673ee24
DO
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.
735function getUnmountedObjects ()
736{
e673ee24
DO
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 '.
068ffc0c 741 'where rack_id is null and chapter_name = "RackObjectType" order by dict_value, name, label, asset_no, barcode';
065eeb52 742 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
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 {
64b95774 747 foreach ($clist as $cname)
e673ee24
DO
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
755function getProblematicObjects ()
756{
e673ee24
DO
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';
065eeb52 761 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
762 $ret = array();
763 $clist = array ('id', 'name', 'objtype_name', 'objtype_id', 'asset_no');
764 while ($row = $result->fetch (PDO::FETCH_ASSOC))
765 {
64b95774 766 foreach ($clist as $cname)
e673ee24
DO
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
774function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
775{
776 if ($object_id <= 0)
777 {
f41b492f 778 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
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
800function 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
818function delObjectPort ($port_id)
819{
820 if (unlinkPort ($port_id) != '')
4d2e93f2 821 return __FUNCTION__ . ': unlinkPort() failed';
e673ee24 822 if (useDeleteBlade ('Port', 'id', $port_id) != TRUE)
4d2e93f2 823 return __FUNCTION__ . ': useDeleteBlade() failed';
e673ee24
DO
824 return '';
825}
826
827function getObjectAddressesAndNames ()
828{
e673ee24
DO
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 ";
065eeb52 835 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
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
e673ee24
DO
850function getEmptyPortsOfType ($type_id)
851{
e673ee24
DO
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";
065eeb52 869 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
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
886function 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 '';
e673ee24
DO
903}
904
905function 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 '';
e673ee24
DO
912}
913
4b2bf583
DO
914// FIXME: after falling back to using existing getObjectInfo we don't
915// need that large query. Shrink it some later.
e673ee24
DO
916function getObjectAddresses ($object_id = 0)
917{
918 if ($object_id == 0)
919 {
f41b492f 920 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
921 return;
922 }
e673ee24
DO
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";
065eeb52 941 $result = useSelectBlade ($query, __FUNCTION__);
e425f895
DO
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)
e673ee24 952 {
e425f895 953 if ($prev_ip != $row['IPBonds_ip'])
e673ee24 954 {
e425f895
DO
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 }
e673ee24 965
e425f895
DO
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
e673ee24 974 {
e425f895
DO
975 $oi = getObjectInfo ($row['RemoteBonds_object_id']);
976 $ret[$count]['references'][$refcount]['object_name'] = displayedName ($oi);
e673ee24 977 }
e425f895 978 $refcount++;
e673ee24
DO
979 }
980 }
e673ee24
DO
981 return $ret;
982}
983
11c8e4be 984function getAddressspaceList ($tagfilter = array(), $tfmode = 'any')
e673ee24 985{
81736ac1 986 $whereclause = getWhereClause ($tagfilter);
e673ee24 987 $query =
0b4c0f17 988 "select distinct ".
e673ee24
DO
989 "id as IPRanges_id, ".
990 "INET_NTOA(ip) as IPRanges_ip, ".
991 "mask as IPRanges_mask, ".
992 "name as IPRanges_name ".
74ccacff 993 "from IPRanges left join TagStorage on IPRanges.id = TagStorage.target_id and target_realm = 'ipv4net' " .
489a7502 994 "where true ${whereclause} " .
74ccacff 995 " order by ip";
065eeb52 996 $result = useSelectBlade ($query, __FUNCTION__);
e425f895
DO
997 $ret=array();
998 $count=0;
999 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 1000 {
e425f895
DO
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++;
e673ee24
DO
1009 }
1010 $result->closeCursor();
1011 return $ret;
1012
1013}
1014
1015function getRangeByIp ($ip = '', $id = 0)
1016{
e673ee24
DO
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
065eeb52 1028 $result = useSelectBlade ($query, __FUNCTION__);
e425f895
DO
1029 $ret=array();
1030 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 1031 {
e425f895
DO
1032 $binmask=binMaskFromDec($row['mask']);
1033 if ((ip2long($ip) & $binmask) == ip2long($row['ip']))
e673ee24 1034 {
e425f895
DO
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;
e673ee24
DO
1042 }
1043 }
1044 $result->closeCursor();
1045 return NULL;
1046}
1047
1048function 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 '';
e673ee24
DO
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).
b4c1ef87 1060function updateAddress ($ip = 0, $name = '', $reserved = 'no')
e673ee24
DO
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
b4c1ef87 1070 return __FUNCTION__ . '(): useInsertBlade() failed';
e673ee24
DO
1071}
1072
e673ee24
DO
1073function 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
1083function 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.
11c8e4be 1094function getUserAccounts ($tagfilter = array(), $tfmode = 'any')
e673ee24 1095{
81736ac1 1096 $whereclause = getWhereClause ($tagfilter);
e673ee24
DO
1097 $query =
1098 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
ebae41b3
DO
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';
065eeb52 1103 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
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))
64b95774 1107 foreach ($clist as $cname)
e673ee24
DO
1108 $ret[$row['user_name']][$cname] = $row[$cname];
1109 $result->closeCursor();
1110 return $ret;
1111}
1112
e673ee24
DO
1113function searchByl2address ($l2addr)
1114{
e673ee24
DO
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}";
065eeb52 1118 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
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];
f41b492f 1125 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__);
e673ee24
DO
1126 return NULL;
1127}
1128
ea5fc465
DO
1129function 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 }
065eeb52 1138 $result = useSelectBlade ($query, __FUNCTION__);
ea5fc465
DO
1139 $ret = array();
1140 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1141 $ret[] = $row;
1142 return $ret;
1143}
1144
1145function 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 }
065eeb52 1154 $result = useSelectBlade ($query, __FUNCTION__);
ea5fc465
DO
1155 $ret = array();
1156 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1157 $ret[] = $row;
1158 return $ret;
1159}
1160
05411ccd
DO
1161function 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 }
065eeb52 1170 $result = useSelectBlade ($query, __FUNCTION__);
05411ccd
DO
1171 $ret = array();
1172 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1173 $ret[] = $row;
1174 return $ret;
1175}
1176
1177function 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 }
065eeb52 1186 $result = useSelectBlade ($query, __FUNCTION__);
05411ccd
DO
1187 $ret = array();
1188 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1189 $ret[] = $row;
1190 return $ret;
1191}
1192
6a88e734
DO
1193function 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
1205function 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
e673ee24
DO
1230// This function returns either port ID or NULL for specified arguments.
1231function getPortID ($object_id, $port_name)
1232{
e673ee24 1233 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
065eeb52 1234 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
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
1243function 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
1257function 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 {
f41b492f 1266 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1267 die;
1268 }
1269 return TRUE;
1270}
1271
1272function 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 {
f41b492f 1281 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1282 die;
1283 }
1284 return TRUE;
1285}
1286
e673ee24
DO
1287// This function returns an array of all port type pairs from PortCompat table.
1288function getPortCompat ()
1289{
e673ee24
DO
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'";
065eeb52 1297 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1298 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1299 $result->closeCursor();
1300 return $ret;
1301}
1302
1303function removePortCompat ($type1 = 0, $type2 = 0)
1304{
1305 global $dbxlink;
1306 if ($type1 == 0 or $type2 == 0)
1307 {
f41b492f 1308 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
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 {
f41b492f 1315 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1316 die;
1317 }
1318 return TRUE;
1319}
1320
1321function addPortCompat ($type1 = 0, $type2 = 0)
1322{
1323 if ($type1 <= 0 or $type2 <= 0)
1324 {
f41b492f 1325 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
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.
2dd59b15 1338function getDict ($parse_links = FALSE)
e673ee24 1339{
6bb8e41d 1340 $query1 =
e673ee24
DO
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";
065eeb52 1343 $result = useSelectBlade ($query1, __FUNCTION__);
e673ee24 1344 $dict = array();
89fa639f 1345 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
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)
6bb8e41d 1356 {
2dd59b15
DO
1357 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1358 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
6bb8e41d
DO
1359 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1360 }
e673ee24 1361 }
89fa639f
DO
1362 $result->closeCursor();
1363 unset ($result);
6bb8e41d
DO
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";
065eeb52 1373 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 1374 while ($row = $result->fetch (PDO::FETCH_ASSOC))
6bb8e41d 1375 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
89fa639f 1376 $result->closeCursor();
e673ee24
DO
1377 return $dict;
1378}
1379
da95280e
DO
1380function getDictStats ()
1381{
82f7e2e8 1382 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
da95280e 1383 $query =
5aa28abb
DO
1384 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1385 "Chapter natural left join Dictionary group by Chapter.chapter_no";
065eeb52 1386 $result = useSelectBlade ($query, __FUNCTION__);
da95280e 1387 $tc = $tw = $uc = $uw = 0;
89fa639f 1388 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
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 }
89fa639f
DO
1397 $result->closeCursor();
1398 unset ($result);
08b4cb24
DO
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";
065eeb52 1401 $result = useSelectBlade ($query, __FUNCTION__);
08b4cb24 1402 $to = $ta = $so = 0;
89fa639f 1403 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1404 {
1405 $to++;
1406 if ($row['attrc'] != 0)
1407 {
1408 $so++;
1409 $ta += $row['attrc'];
1410 }
1411 }
89fa639f 1412 $result->closeCursor();
da95280e
DO
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;
08b4cb24
DO
1418 $ret['Total objects'] = $to;
1419 $ret['Objects with stickers'] = $so;
1420 $ret['Total stickers attached'] = $ta;
da95280e
DO
1421 return $ret;
1422}
1423
9ec5fdf1
DO
1424function getIPv4Stats()
1425{
9ec5fdf1
DO
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 {
065eeb52 1439 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1
DO
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
1448function getRackspaceStats()
1449{
9ec5fdf1
DO
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 {
065eeb52 1459 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1 1460 $row = $result->fetch (PDO::FETCH_NUM);
82f7e2e8 1461 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1462 $result->closeCursor();
1463 unset ($result);
1464 }
1465 return $ret;
1466}
1467
5bbbeaa2
DO
1468function 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";
065eeb52 1474 $result = useSelectBlade ($query, __FUNCTION__);
5bbbeaa2
DO
1475 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1476 $ret[$row['tag']] = $row['refcnt'];
1477 $result->closeCursor();
1478 return $ret;
1479}
1480
e673ee24
DO
1481function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1482{
1483 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1484 {
f41b492f 1485 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
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 {
f41b492f 1495 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1496 die;
1497 }
1498 return TRUE;
1499}
1500
1501function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1502{
1503 if ($chapter_no <= 0 or empty ($dict_value))
1504 {
f41b492f 1505 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1506 die;
1507 }
1508 return useInsertBlade
1509 (
1510 'Dictionary',
1511 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1512 );
1513}
1514
1515function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1516{
1517 if ($chapter_no <= 0 or $dict_key <= 0)
1518 {
f41b492f 1519 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
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 {
f41b492f 1529 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1530 die;
1531 }
1532 return TRUE;
1533}
1534
1535function commitAddChapter ($chapter_name = '')
1536{
1537 if (empty ($chapter_name))
1538 {
f41b492f 1539 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1540 die;
1541 }
1542 return useInsertBlade
1543 (
1544 'Chapter',
1545 array ('chapter_name' => "'${chapter_name}'")
1546 );
1547}
1548
1549function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1550{
1551 if ($chapter_no <= 0 or empty ($chapter_name))
1552 {
f41b492f 1553 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
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 {
f41b492f 1563 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1564 die;
1565 }
1566 return TRUE;
1567}
1568
1569function commitDeleteChapter ($chapter_no = 0)
1570{
1571 if ($chapter_no <= 0)
1572 {
f41b492f 1573 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
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 {
f41b492f 1582 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1583 die;
1584 }
1585 return TRUE;
1586}
1587
4c330a14
DO
1588// This is a dictionary accessor. We perform link rendering, so the user sees
1589// nice <select> drop-downs.
e673ee24
DO
1590function readChapter ($chapter_name = '')
1591{
1592 if (empty ($chapter_name))
1593 {
f41b492f 1594 showError ('invalid argument', __FUNCTION__);
e673ee24
DO
1595 return NULL;
1596 }
e673ee24
DO
1597 $query =
1598 "select dict_key, dict_value from Dictionary natural join Chapter " .
4aa8609b 1599 "where chapter_name = '${chapter_name}'";
065eeb52 1600 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1601 $chapter = array();
1602 while ($row = $result->fetch (PDO::FETCH_ASSOC))
4c330a14 1603 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
e673ee24 1604 $result->closeCursor();
4aa8609b
DO
1605 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1606 asort ($chapter);
e673ee24
DO
1607 return $chapter;
1608}
1609
1610function getAttrMap ()
1611{
e673ee24
DO
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";
065eeb52 1621 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
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
1648function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1649{
1650 if ($attr_id <= 0 or empty ($attr_name))
1651 {
f41b492f 1652 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
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 {
f41b492f 1662 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
1663 die;
1664 }
1665 return TRUE;
1666}
1667
1668function commitAddAttribute ($attr_name = '', $attr_type = '')
1669{
1670 if (empty ($attr_name))
1671 {
f41b492f 1672 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1673 die;
1674 }
1675 switch ($attr_type)
1676 {
1677 case 'uint':
1678 case 'float':
1679 case 'string':
1680 case 'dict':
1681 break;
1682 default:
f41b492f 1683 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1684 die;
1685 }
1686 return useInsertBlade
1687 (
1688 'Attribute',
1689 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1690 );
1691}
1692
1693function commitDeleteAttribute ($attr_id = 0)
1694{
1695 if ($attr_id <= 0)
1696 {
f41b492f 1697 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1698 die;
1699 }
aedf18af 1700 return useDeleteBlade ('Attribute', 'attr_id', $attr_id, FALSE);
e673ee24
DO
1701}
1702
1703// FIXME: don't store garbage in chapter_no for non-dictionary types.
1704function 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 {
f41b492f 1708 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
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
1723function commitReduceAttrMap ($attr_id = 0, $objtype_id)
1724{
1725 if ($attr_id <= 0 or $objtype_id <= 0)
1726 {
f41b492f 1727 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
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 {
f41b492f 1737 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
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.
24cbe8af 1746function getAttrValues ($object_id, $strip_optgroup = FALSE)
e673ee24
DO
1747{
1748 if ($object_id <= 0)
1749 {
f41b492f 1750 showError ('Invalid argument', __FUNCTION__);
e673ee24
DO
1751 return NULL;
1752 }
e673ee24
DO
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 " .
1a576609 1762 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
065eeb52 1763 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
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':
24cbe8af
DO
1775 $record['value'] = $row[$row['attr_type'] . '_value'];
1776 $record['a_value'] = parseWikiLink ($record['value'], 'a');
1777 break;
e673ee24 1778 case 'dict':
24cbe8af
DO
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);
e673ee24
DO
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
1794function commitResetAttrValue ($object_id = 0, $attr_id = 0)
1795{
1796 if ($object_id <= 0 or $attr_id <= 0)
1797 {
f41b492f 1798 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
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 {
f41b492f 1806 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1807 die;
1808 }
1809 return TRUE;
1810}
1811
1812// FIXME: don't share common code with use commitResetAttrValue()
1813function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
1814{
1815 if ($object_id <= 0 or $attr_id <= 0)
1816 {
f41b492f 1817 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
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 {
f41b492f 1827 showError ('SQL query #1 failed', __FUNCTION__);
e673ee24
DO
1828 die;
1829 }
1830 $row = $result->fetch (PDO::FETCH_NUM);
1831 if ($row == NULL)
1832 {
f41b492f 1833 showError ('SQL query #1 returned no results', __FUNCTION__);
e673ee24
DO
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:
f41b492f 1849 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
e673ee24
DO
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 {
f41b492f 1858 showError ('SQL query #2 failed', __FUNCTION__);
e673ee24
DO
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 {
f41b492f 1868 showError ('SQL query #3 failed', __FUNCTION__);
e673ee24
DO
1869 die;
1870 }
1871 return TRUE;
1872}
1873
1874function commitUseupPort ($port_id = 0)
1875{
1876 if ($port_id <= 0)
1877 {
f41b492f 1878 showError ("Invalid argument", __FUNCTION__);
e673ee24
DO
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 {
f41b492f 1886 showError ("SQL query failed", __FUNCTION__);
e673ee24
DO
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).
1898function 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.
fe7044ad 1916function useDeleteBlade ($tablename, $keyname, $keyvalue, $quotekey = TRUE, $deleteall = FALSE)
e673ee24
DO
1917{
1918 global $dbxlink;
1919 if ($quotekey == TRUE)
fe7044ad
DO
1920 $keyvalue = "'${keyvalue}'";
1921 $query = "delete from ${tablename} where ${keyname}=$keyvalue";
1922 if (!$deleteall)
1923 $query .= ' limit 1';
e673ee24
DO
1924 $result = $dbxlink->exec ($query);
1925 if ($result === NULL)
1926 return FALSE;
aedf18af 1927 elseif (!$deleteall && $result != 1)
e673ee24
DO
1928 return FALSE;
1929 else
1930 return TRUE;
1931}
1932
5967b83d
DO
1933function useSelectBlade ($query, $caller = 'N/A')
1934{
1935 global $dbxlink;
1936 $result = $dbxlink->query ($query);
1937 if ($result == NULL)
1938 {
1939 $ei = $dbxlink->errorInfo();
105a3bc8 1940 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
5967b83d
DO
1941 return NULL;
1942 }
1943 return $result;
1944}
1945
9c0b0016
DO
1946function loadConfigCache ()
1947{
4fe32e78 1948 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
065eeb52 1949 $result = useSelectBlade ($query, __FUNCTION__);
9c0b0016
DO
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
1958function storeConfigVar ($varname = NULL, $varvalue = NULL)
1959{
c461c579 1960 global $dbxlink;
bb6b9880 1961 if (empty ($varname) || $varvalue === NULL)
9c0b0016 1962 {
f41b492f 1963 showError ('Invalid arguments', __FUNCTION__);
9c0b0016
DO
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 {
f41b492f 1970 showError ("SQL query '${query}' failed", __FUNCTION__);
9c0b0016
DO
1971 return FALSE;
1972 }
1973 $rc = $result->rowCount();
1974 $result->closeCursor();
f7ee57a1 1975 if ($rc == 0 or $rc == 1)
9c0b0016 1976 return TRUE;
f41b492f 1977 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
9c0b0016
DO
1978 return FALSE;
1979}
1980
fbbb74fb
DO
1981// Database version detector. Should behave corretly on any
1982// working dataset a user might have.
1983function 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';
4d2e93f2 1993 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
1994 }
1995 $rows = $result->fetchAll (PDO::FETCH_NUM);
1996 if (count ($rows) != 1 || empty ($rows[0][0]))
1997 {
1998 $result->closeCursor();
4d2e93f2 1999 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
2000 }
2001 $ret = $rows[0][0];
2002 $result->closeCursor();
2003 return $ret;
2004}
2005
da04825a
DO
2006// Return an array of virtual services. For each of them list real server pools
2007// with their load balancers and other stats.
62a1dcb5
DO
2008function getSLBSummary ()
2009{
6fec9f39
DO
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 ' .
3e56d972 2013 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
6fec9f39
DO
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';
065eeb52 2016 $result = useSelectBlade ($query, __FUNCTION__);
c3bdc503
DO
2017 $ret = array();
2018 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2019 {
4cadac8f 2020 $vsid = $row['vsid'];
da04825a 2021 $object_id = $row['object_id'];
4cadac8f
DO
2022 if (!isset ($ret[$vsid]))
2023 {
2024 $ret[$vsid] = array();
13bffb29 2025 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2026 $ret[$vsid][$cname] = $row[$cname];
da04825a 2027 $ret[$vsid]['lblist'] = array();
4cadac8f 2028 }
6fec9f39
DO
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 );
c3bdc503 2036 }
060ba26e 2037 $result->closeCursor();
c3bdc503 2038 return $ret;
62a1dcb5
DO
2039}
2040
da04825a
DO
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.
060ba26e
DO
2044function getVServiceInfo ($vsid = 0)
2045{
2b4eee17
DO
2046 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2047 "from IPVirtualService where id = ${vsid}";
065eeb52 2048 $result = useSelectBlade ($query1, __FUNCTION__);
060ba26e 2049 $vsinfo = array ();
89fa639f 2050 $row = $result->fetch (PDO::FETCH_ASSOC);
2b4eee17
DO
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();
89fa639f
DO
2056 $result->closeCursor();
2057 unset ($result);
2b4eee17
DO
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";
065eeb52 2062 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 2063 while ($row = $result->fetch (PDO::FETCH_ASSOC))
060ba26e 2064 {
2b4eee17 2065 if (!isset ($vsinfo['rspool'][$row['id']]))
060ba26e 2066 {
2b4eee17
DO
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();
060ba26e 2071 }
2b4eee17
DO
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 );
060ba26e 2079 }
89fa639f 2080 $result->closeCursor();
060ba26e
DO
2081 return $vsinfo;
2082}
2083
71b8bda1
DO
2084// Collect and return the following info about the given real server pool:
2085// basic information
2086// parent virtual service information
c1ca768c 2087// load balancers list (each with a list of VSes)
71b8bda1
DO
2088// real servers list
2089
2090function getRSPoolInfo ($id = 0)
2091{
c1ca768c 2092 $query1 = "select id, name, vsconfig, rsconfig from " .
481a7f8b 2093 "IPRSPool where id = ${id}";
065eeb52 2094 $result = useSelectBlade ($query1, __FUNCTION__);
71b8bda1 2095 $ret = array();
89fa639f 2096 $row = $result->fetch (PDO::FETCH_ASSOC);
71b8bda1
DO
2097 if (!$row)
2098 return NULL;
70c24883 2099 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
71b8bda1 2100 $ret[$c] = $row[$c];
89fa639f
DO
2101 $result->closeCursor();
2102 unset ($result);
71b8bda1
DO
2103 $ret['lblist'] = array();
2104 $ret['rslist'] = array();
1519d6fa
DO
2105 $query2 = "select object_id, vs_id, vsconfig, rsconfig from IPLoadBalancer " .
2106 "where rspool_id = ${id} order by object_id, vs_id";
065eeb52 2107 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 2108 while ($row = $result->fetch (PDO::FETCH_ASSOC))
71b8bda1 2109 foreach (array ('vsconfig', 'rsconfig') as $c)
c1ca768c 2110 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
89fa639f
DO
2111 $result->closeCursor();
2112 unset ($result);
1f7d18fa 2113 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
676a8268 2114 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
065eeb52 2115 $result = useSelectBlade ($query3, __FUNCTION__);
89fa639f 2116 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2117 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
71b8bda1 2118 $ret['rslist'][$row['id']][$c] = $row[$c];
89fa639f 2119 $result->closeCursor();
71b8bda1
DO
2120 return $ret;
2121}
2122
7e7a8387 2123function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127
DO
2124{
2125 if ($pool_id <= 0 or $rsport <= 0)
2126 {
2127 showError ('Invalid arguments', __FUNCTION__);
2128 die;
2129 }
ca461127
DO
2130 return useInsertBlade
2131 (
2132 'IPRealServer',
2133 array
2134 (
2135 'rsip' => "inet_aton('${rsip}')",
2136 'rsport' => $rsport,
2137 'rspool_id' => $pool_id,
bcbeadb4 2138 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
3241551e
DO
2139 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2140 )
2141 );
2142}
2143
d6517a21
DO
2144function 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
c1ca768c 2166function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2167{
c1ca768c 2168 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
3241551e
DO
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,
c1ca768c 2180 'vs_id' => $vs_id,
3241551e
DO
2181 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2182 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2183 )
ca461127
DO
2184 );
2185}
2186
fb1c4a54
DO
2187function commitDeleteRS ($id = 0)
2188{
2189 if ($id <= 0)
2190 return FALSE;
aedf18af 2191 return useDeleteBlade ('IPRealServer', 'id', $id, FALSE);
fb1c4a54
DO
2192}
2193
d6517a21
DO
2194function commitDeleteVS ($id = 0)
2195{
2196 if ($id <= 0)
2197 return FALSE;
aedf18af 2198 return useDeleteBlade ('IPVirtualService', 'id', $id, FALSE) && deleteTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2199}
2200
c1ca768c 2201function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e
DO
2202{
2203 global $dbxlink;
c4d85fd1 2204 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e 2205 return FALSE;
c1ca768c
DO
2206 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2207 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
3241551e
DO
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
fb1c4a54
DO
2217function 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 = " .
3241551e 2232 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
fb1c4a54
DO
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
c1ca768c 2243function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2244{
c1ca768c 2245 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e
DO
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}'") .
c1ca768c
DO
2256 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2257 "and vs_id = ${vs_id} limit 1";
3241551e
DO
2258 $result = $dbxlink->exec ($query);
2259 if ($result === NULL)
2260 return FALSE;
3241551e
DO
2261 else
2262 return TRUE;
2263}
2264
d6517a21
DO
2265function 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}', ") .
5ad76f01
DO
2279 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2280 " where id = ${vsid} limit 1";
d6517a21
DO
2281 $result = $dbxlink->exec ($query);
2282 if ($result === NULL)
2283 return FALSE;
d6517a21
DO
2284 else
2285 return TRUE;
2286}
2287
e57dca7f 2288// Return the list of virtual services, indexed by vs_id.
70c24883 2289// Each record will be shown with its basic info plus RS pools counter.
11c8e4be 2290function getVSList ($tagfilter = array(), $tfmode = 'any')
e57dca7f 2291{
81736ac1 2292 $whereclause = getWhereClause ($tagfilter);
70c24883
DO
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 " .
996b02ba 2295 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
83d3dde9 2296 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
065eeb52 2297 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2298 $ret = array ();
e57dca7f 2299 while ($row = $result->fetch (PDO::FETCH_ASSOC))
d6517a21 2300 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
4b0932b6 2301 $ret[$row['id']][$cname] = $row[$cname];
e57dca7f 2302 $result->closeCursor();
4b0932b6 2303 return $ret;
e57dca7f
DO
2304}
2305
9a81d416 2306// Return the list of RS pool, indexed by pool id.
11c8e4be 2307function getRSPoolList ($tagfilter = array(), $tfmode = 'any')
9a81d416 2308{
81736ac1 2309 $whereclause = getWhereClause ($tagfilter);
70c24883
DO
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 " .
2e4170aa 2312 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
83d3dde9 2313 "where true ${whereclause} group by pool.id order by pool.id, name";
065eeb52 2314 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2315 $ret = array ();
9a81d416 2316 while ($row = $result->fetch (PDO::FETCH_ASSOC))
70c24883 2317 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
4b0932b6 2318 $ret[$row['id']][$cname] = $row[$cname];
9a81d416 2319 $result->closeCursor();
4b0932b6 2320 return $ret;
9a81d416
DO
2321}
2322
5a1680d2
DO
2323function loadThumbCache ($rack_id = 0)
2324{
5a1680d2
DO
2325 $ret = NULL;
2326 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
065eeb52 2327 $result = useSelectBlade ($query, __FUNCTION__);
5a1680d2
DO
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
2335function 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}
9a81d416 2347
c7fe33be
DO
2348function 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
748805bf
DO
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.
78e7b769
DO
2364function getRSPoolsForObject ($object_id = 0)
2365{
2366 if ($object_id <= 0)
2367 {
2368 showError ('Invalid object_id', __FUNCTION__);
2369 return NULL;
2370 }
748805bf 2371 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2372 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
748805bf
DO
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';
065eeb52 2378 $result = useSelectBlade ($query, __FUNCTION__);
748805bf 2379 $ret = array ();
78e7b769 2380 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2381 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2382 $ret[$row['vs_id']][$cname] = $row[$cname];
78e7b769 2383 $result->closeCursor();
748805bf 2384 return $ret;
78e7b769
DO
2385}
2386
70c24883 2387function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '')
5ad76f01 2388{
5ad76f01
DO
2389 return useInsertBlade
2390 (
2391 'IPRSPool',
2392 array
2393 (
5ad76f01
DO
2394 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2395 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2396 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2397 )
2398 );
2399}
2400
2401function commitDeleteRSPool ($pool_id = 0)
2402{
2403 global $dbxlink;
2404 if ($pool_id <= 0)
2405 return FALSE;
aedf18af 2406 return useDeleteBlade ('IPRSPool', 'id', $pool_id, FALSE) && deleteTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2407}
2408
2409function 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
8253d9f0
DO
2431function getRSList ()
2432{
1f7d18fa 2433 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
8253d9f0 2434 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
065eeb52 2435 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2436 $ret = array ();
8253d9f0 2437 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2438 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6
DO
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.
2445function getLBList ()
2446{
4b0932b6
DO
2447 $query = "select object_id, count(rspool_id) as poolcount " .
2448 "from IPLoadBalancer group by object_id order by object_id";
065eeb52 2449 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6
DO
2450 $ret = array ();
2451 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2452 $ret[$row['object_id']] = $row['poolcount'];
8253d9f0 2453 $result->closeCursor();
4b0932b6 2454 return $ret;
8253d9f0
DO
2455}
2456
9e677cbd
DO
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.
2461function buildLBConfig ($object_id)
2462{
2463 if ($object_id <= 0)
2464 {
2465 showError ('Invalid arg', __FUNCTION__);
2466 return NULL;
2467 }
9e677cbd 2468 $ret = array();
d91f08f3
DO
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, ' .
9e677cbd 2472 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3
DO
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 ' .
9e677cbd 2476 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
1f7d18fa
DO
2477 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2478 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
065eeb52 2479 $result = useSelectBlade ($query, __FUNCTION__);
9e677cbd
DO
2480 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2481 {
d91f08f3
DO
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];
9e677cbd
DO
2491 }
2492 $result->closeCursor();
2493 return $ret;
2494}
1f7d18fa
DO
2495
2496function 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
ad0e4754
DO
2514function 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 }
f3f0161f 2521 $ret = TRUE;
118e4c38 2522 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2523 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2524 return $ret;
ad0e4754
DO
2525}
2526
6e49bd1f 2527// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 2528// generated/deducted later at higher levels.
f9bc186f 2529function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2530{
f9bc186f
DO
2531 if ($entity_realm == '' or $entity_id <= 0)
2532 {
2533 showError ('Invalid or missing arguments', __FUNCTION__);
2534 return NULL;
2535 }
a6e8d544 2536 $ret = array();
065eeb52 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__);
5967b83d 2538 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2539 $ret[$row['id']] = $row;
a6e8d544
DO
2540 $result->closeCursor();
2541 return $ret;
5967b83d
DO
2542}
2543
f9bc186f
DO
2544function loadRackObjectTags ($id)
2545{
2546 return loadEntityTags ('object', $id);
2547}
2548
2549function loadIPv4PrefixTags ($id)
2550{
2551 return loadEntityTags ('ipv4net', $id);
2552}
2553
41bd8c87
DO
2554function loadRackTags ($id)
2555{
2556 return loadEntityTags ('rack', $id);
2557}
2558
d817ba03
DO
2559function loadIPv4VSTags ($id)
2560{
2561 return loadEntityTags ('ipv4vs', $id);
2562}
2563
2564function loadIPv4RSPoolTags ($id)
2565{
2566 return loadEntityTags ('ipv4rspool', $id);
2567}
2568
ebae41b3
DO
2569function loadUserTags ($user_id)
2570{
2571 return loadEntityTags ('user', $user_id);
2572}
2573
5967b83d
DO
2574function getTagList ()
2575{
20c901a7 2576 $ret = array();
5b7bd02e
DO
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";
065eeb52 2580 $result = useSelectBlade ($query, __FUNCTION__);
5967b83d 2581 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2582 {
7cc02fc1 2583 if (!isset ($ret[$row['id']]))
20c901a7 2584 $ret[$row['id']] = array
5b7bd02e
DO
2585 (
2586 'id' => $row['id'],
2587 'tag' => $row['tag'],
2588 'parent_id' => $row['parent_id'],
2589 'refcnt' => array()
2590 );
2591 if ($row['realm'])
20c901a7 2592 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
5b7bd02e 2593 }
5967b83d 2594 $result->closeCursor();
20c901a7 2595 return $ret;
5967b83d
DO
2596}
2597
fe7044ad
DO
2598function 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
2617function 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}
f9bc186f 2626
49fb1027 2627function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2628{
49fb1027
DO
2629 if ($parent_id == 0)
2630 $parent_id = 'NULL';
f9bc186f 2631 global $dbxlink;
49fb1027
DO
2632 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2633 "where id = ${tag_id} limit 1";
f9bc186f
DO
2634 $result = $dbxlink->exec ($query);
2635 if ($result === NULL)
49fb1027
DO
2636 return 'SQL query failed in ' . __FUNCTION__;
2637 return '';
f9bc186f
DO
2638}
2639
aedf18af
DO
2640function 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
eb6ea26f
DO
2651function 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
42023f03
DO
2665function 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
065eeb52 2710 $result = useSelectBlade ($query, __FUNCTION__);
42023f03
DO
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 '';
065eeb52 2743 if (($result = useSelectBlade ('select last_insert_id()', __FUNCTION__)) == NULL)
42023f03
DO
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.
2760function 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
ebae41b3
DO
2771function 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
2778function 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
2796function saveUserPassword ($user_id, $newp)
bcd37231 2797{
ebae41b3
DO
2798 $newhash = hash (PASSWORD_HASH, $newp);
2799 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
bcd37231
DO
2800}
2801
cf6c472b
DO
2802function 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);
81736ac1 2818 return $count === '0';
cf6c472b
DO
2819}
2820
e673ee24 2821?>