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