Merge pull request #15 from madmax2012/merge_branch
[racktables-contribs] / local_copy_object.php
CommitLineData
3fcf109f 1<?php
3fcf109f 2$tab['object']['objectcopier'] = 'Object Copier ';
3fcf109f 3$tabhandler['object']['objectcopier'] = 'localfunc_ObjectCopier';
3fcf109f
DO
4$ophandler['object']['objectcopier']['copyLotOfObjects'] = 'copyLotOfObjects';
5
a0aa39e6 6function amplifyCell_object_Backend_Port (&$record, $dummy = NULL)
3fcf109f 7{
a0aa39e6 8 switch ($record['realm'])
9 {
10 case 'object':
11 $record['BackendPorts'] = getObjectBackendPortsAndLinks ($record['id']);
12 break;
13 default:
14 }
15}
3fcf109f 16
a0aa39e6 17function getObjectBackendPortsAndLinks ($object_id)
18{
19 $ret = fetchBackendPortList ("Port.object_id = ?", array ($object_id));
20 return sortPortList ($ret, TRUE);
3fcf109f 21}
0909f149 22
a0aa39e6 23function fetchBackendPortList ($sql_where_clause, $query_params = array())
0909f149 24{
a0aa39e6 25 $query = <<<END
26SELECT
27 Port.id,
28 Port.name,
29 Port.object_id,
30 Object.name AS object_name,
31 Port.l2address,
32 Port.label,
33 Port.reservation_comment,
34 Port.iif_id,
35 Port.type AS oif_id,
36 (SELECT PortInnerInterface.iif_name FROM PortInnerInterface WHERE PortInnerInterface.id = Port.iif_id) AS iif_name,
37 (SELECT Dictionary.dict_value FROM Dictionary WHERE Dictionary.dict_key = Port.type) AS oif_name,
38 IF(lba.porta, lba.cable, lbb.cable) AS cableid,
39 IF(lba.porta, pa.id, pb.id) AS remote_id,
40 IF(lba.porta, pa.name, pb.name) AS remote_name,
41 IF(lba.porta, pa.object_id, pb.object_id) AS remote_object_id,
42 IF(lba.porta, oa.name, ob.name) AS remote_object_name,
43 (SELECT COUNT(*) FROM PortLog WHERE PortLog.port_id = Port.id) AS log_count,
44 PortLog.user,
45 UNIX_TIMESTAMP(PortLog.date) as time
46FROM
47 Port
48 INNER JOIN Object ON Port.object_id = Object.id
49 LEFT JOIN LinkBackend AS lba ON lba.porta = Port.id
50 LEFT JOIN Port AS pa ON pa.id = lba.portb
51 LEFT JOIN Object AS oa ON pa.object_id = oa.id
52 LEFT JOIN LinkBackend AS lbb on lbb.portb = Port.id
53 LEFT JOIN Port AS pb ON pb.id = lbb.porta
54 LEFT JOIN Object AS ob ON pb.object_id = ob.id
55 LEFT JOIN PortLog ON PortLog.id = (SELECT id FROM PortLog WHERE PortLog.port_id = Port.id ORDER BY date DESC LIMIT 1)
56WHERE
57 $sql_where_clause
58END;
59
60 $result = usePreparedSelectBlade ($query, $query_params);
61 $ret = array();
62 while ($row = $result->fetch (PDO::FETCH_ASSOC))
0909f149 63 {
a0aa39e6 64 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
65 $row['linked'] = isset ($row['remote_id']) ? 1 : 0;
66
67 // last changed log
68 $row['last_log'] = array();
69 if ($row['log_count'])
70 {
71 $row['last_log']['user'] = $row['user'];
72 $row['last_log']['time'] = $row['time'];
73 }
74 unset ($row['user']);
75 unset ($row['time']);
76
77 $ret[] = $row;
0909f149 78 }
a0aa39e6 79 return $ret;
80}
81
82
83function varDumpToString ($var)
84{
85 ob_start();
86 var_dump($var);
87 $result = ob_get_clean();
88 return $result;
89}
90
91function localfunc_ObjectCopier($object_id)
92{
93$object = spotEntity ('object', $object_id );
94amplifyCell($object);
95global $virtual_obj_types, $tagtree, $taglist, $target_given_tags;
96$typelist = readChapter (CHAP_OBJTYPE, 'o');
97$typelist[0] = 'select type...';
98$typelist = cookOptgroups ($typelist);
99$max = getConfigVar ('MASSCOUNT');
100$tabindex = 100;
101
102echo "\n";
103echo "\n<!-- printOpFormIntro ('copyLotOfObjects') -->\n";
104printOpFormIntro ('copyLotOfObjects');
105echo "\n";
106startPortlet ('Make many copies of this object');
107echo "\n" . sprintf('<table border=%s align=center>', TABLE_BORDER);
108echo "\n" . '<tr><th align=left>name or "name","label","asset_no" (no csv escaping)<br><br>';
109echo 'Example:<br> "server.example.com","server.example.com","12345"<br>www.example.com<br>testmachine<br>';
110echo '</th><th>Copy Tags</th></tr>';
111//echo "<tr><td><input type=submit name=got_very_fast_data value='Go!'></td><td></td></tr>\n";
112echo "\n" . "<tr><td valign=top ><textarea name=namelist cols=60 rows=35>\n</textarea></td>";
113echo "<td valign=top>";
114printf ("<input type=hidden name=global_type_id value='%s'>\n", $object['objtype_id']);
115//renderCopyEntityTagsPortlet ('Tag tree', $tagtree, $target_given_tags, $etype_by_pageno[$pageno]);
116renderCopyEntityTags($object);
117echo "</td></tr>";
118echo "<tr><td colspan=2><input type=submit name=got_very_fast_data value='Go!'></td></tr></table>\n";
119echo "</form>\n";
120finishPortlet();
121
0909f149
DO
122}
123
a0aa39e6 124function copyLotOfObjects()//$template_object)
3fcf109f
DO
125{
126 global $dbxlink;
127 $dbrollback = 0;
842d0f76 128 if (! $dbxlink->beginTransaction() )
3fcf109f 129 throw new RTDatabaseError ("can not start transaction");
a0aa39e6 130 // do we need this ?
3fcf109f
DO
131 $log = emptyLog();
132 $taglist = isset ($_REQUEST['taglist']) ? $_REQUEST['taglist'] : array();
133 assertUIntArg ('global_type_id', TRUE);
134 assertStringArg ('namelist', TRUE);
135 $global_type_id = $_REQUEST['global_type_id'];
136 $source_object_id = $_REQUEST['object_id'];
137 $source_object = spotEntity ('object', $source_object_id);
138 amplifyCell($source_object);
b97cb06c 139 // only call amplifyCell_object_Backend_Port if we have function linkmgmt_linkPorts from linkmgmt.php
140 if ( function_exists ( 'amplifyCell_object_Backend_Port' ) && function_exists ('linkmgmt_linkPorts') )
842d0f76 141 {
a0aa39e6 142 amplifyCell_object_Backend_Port($source_object);
842d0f76 143 }
3fcf109f 144 if ($global_type_id == 0 or !strlen ($_REQUEST['namelist']))
a0aa39e6 145 {
842d0f76 146 // Log something reasonable with showError Here
a0aa39e6 147 // We do not have names to copy our object to !
842d0f76 148 // Pls check what makes $global_type_id == 0 an error
3fcf109f 149 $log = mergeLogs ($log, oneLiner (186));
a0aa39e6 150 return ;
151 }
152 // The name extractor below was stolen from ophandlers.php:addMultiPorts()
153 $names1 = explode ("\n", $_REQUEST['namelist']);
154 $names2 = array();
155 foreach ($names1 as $line)
156 {
157 $parts = explode ('\r', $line);
158 reset ($parts);
159 if (!strlen ($parts[0]))
160 continue;
161 else
162 $names2[] = rtrim ($parts[0]);
163 }
164 foreach ($names2 as $name_or_csv)
3fcf109f 165 {
a0aa39e6 166 $label = '';
167 $asset_no = '';
168 $object_name = '';
169 $regexp='/^\"([^\"]*)\","([^\"]*)\","([^\"]*)\"/';
842d0f76 170 $object_name_or_csv = htmlspecialchars_decode($name_or_csv, ENT_QUOTES);
a0aa39e6 171 // error_log( "$regexp $object_name" );
842d0f76 172 if (preg_match($regexp, $object_name_or_csv, $matches) )
3fcf109f 173 {
a0aa39e6 174 $object_name = $matches[1];
175 $label = $matches[2];
176 $asset_no = $matches[3];
842d0f76 177 }
178 else
a0aa39e6 179 $object_name = $name_or_csv;
180 try
3fcf109f 181 {
a0aa39e6 182 $object_id = commitAddObject ($object_name, $label, $global_type_id, $asset_no, $taglist);
183 if (!$object_id)
184 throw new RTDatabaseError("could not create $object_name");
185 $info = spotEntity ('object', $object_id);
186 amplifyCell ($info);
187 foreach ($source_object['ports'] as $source_port)
3fcf109f 188 {
a0aa39e6 189 $update_port=0;
842d0f76 190 foreach ($info['ports'] as $new_port)
3fcf109f 191 {
842d0f76 192 if ($new_port['name'] == $source_port['name'] )
3fcf109f 193 {
a0aa39e6 194 commitUpdatePort ($object_id, $new_port['id'], $new_port['name'], $new_port['oif_id'], $source_port['label'], "" );
195 $update_port=1;
3fcf109f 196 }
3fcf109f 197 }
a0aa39e6 198 if ($update_port)
199 true;
842d0f76 200 else
a0aa39e6 201 commitAddPort ( $object_id, $source_port['name'], sprintf("%s-%s", $source_port['iif_id'], $source_port['oif_id']), $source_port['label'], "" );
202 }
203 // Copy Backendlinks only start if we ghave function linkmgmt_linkPorts from linkmgmt.php
204 if ( function_exists ( 'amplifyCell_object_Backend_Port' ) && function_exists ('linkmgmt_linkPorts') )
842d0f76 205 {
3fcf109f
DO
206 $info = spotEntity ('object', $object_id);
207 amplifyCell ($info);
a0aa39e6 208 amplifyCell_object_Backend_Port($info);
842d0f76 209
a0aa39e6 210 /* showError( '<div align="left"><pre>\n===== Source Object ======\n\n' .
842d0f76 211 varDumpToString ( $source_object ) .
212 '\n\n===== New Object ======\n\n' .
a0aa39e6 213 varDumpToString ( $info ) . '</pre></div>' );
842d0f76 214 */
3fcf109f 215 $name_by_id = array();
842d0f76 216 foreach ($info['BackendPorts'] as $new_be_port)
3fcf109f 217 {
a0aa39e6 218 $name_by_id[$new_be_port['name']] = $new_be_port['id'];
219 }
220
221 $linked_ports = array();
222 foreach ($source_object['BackendPorts'] as $source_be_port)
223 {
224 if ( $source_be_port['object_id'] == $source_be_port['remote_object_id'] )
3fcf109f 225 {
a0aa39e6 226 // We have a Port that has the own object as remote object we want to copy this type of Linko
842d0f76 227 // We have backend Links
a0aa39e6 228 $new_be_port_a = $name_by_id[$source_be_port['name']] ;
229 $new_be_port_b = $name_by_id[$source_be_port['remote_name']] ;
230 if ( $new_be_port_a && $new_be_port_b && ! array_key_exists($new_be_port_a, $linked_ports ) && ! array_key_exists($new_be_port_b, $linked_ports ) )
842d0f76 231 {
a0aa39e6 232 // error_log ( sprintf ('new_be_port_a %s // new_be_port_b %s // cableid %s', $new_be_port_a , $new_be_port_b, $source_be_port['cableid'] ));
233 $ret_val = linkmgmt_linkPorts( $new_be_port_a , $new_be_port_b , 'back', $source_be_port['cableid'] );
234 // error_log ( sprintf (' linkmgmt_linkPorts ret val: "%s" ', $ret_val)) ;
235 if ($ret_val)
236 {
237 throw new RTDatabaseError("could not copy Backend Links for $object_name because: $ret_val");
238 }
842d0f76 239 else
a0aa39e6 240 {
241 $linked_ports[$new_be_port_a] = True;
242 $linked_ports[$new_be_port_b] = True;
842d0f76 243 }
3fcf109f
DO
244 }
245 }
246 }
842d0f76 247 }
a0aa39e6 248 // Copy attributes
249 foreach (getAttrValues ($source_object_id) as $record)
250 {
251 $value = $record['value'];
252 switch ($record['type'])
3fcf109f 253 {
a0aa39e6 254 case 'uint':
255 case 'float':
256 case 'string':
257 $value = $record['value'];
258 break;
259 case 'dict':
260 $value = $record['key'];
261 break;
262 default:
3fcf109f 263 }
842d0f76 264
a0aa39e6 265 if (permitted (NULL, NULL, NULL, array (array ('tag' => '$attr_' . $record['id'] ))))
266 if (empty($value))
267 commitUpdateAttrValue ($object_id, $record['id'] );
268 else
269 commitUpdateAttrValue ($object_id, $record['id'], $value ) ;
270 else
271 showError ('Permission denied, "' . $record['id'] . '"can not be set');
3fcf109f 272
3fcf109f 273 }
a0aa39e6 274
842d0f76 275 //$log = mergeLogs ($log, oneLiner (5, array ('<a href="' .
a0aa39e6 276 // makeHref (array ('page' => 'object', 'tab' => 'default', 'object_id' => $object_id)) .
277 // '">' . $info['dname'] . '</a>'))
278 //);
279 showSuccess (sprintf ("Copied Object %s ; new Object: %s", $source_object['name'] , formatPortLink($object_id, $info['dname'], 1, '', '')) );
280 }
281 catch (RTDatabaseError $e)
282 {
283 error_log("rolling back DB");
284 $dbrollback = 1;
285 $dbxlink->rollBack();
286 $log = mergeLogs ($log, oneLiner (147, array ($object_name)));
287 throw new RTDatabaseError ( $e->getMessage() . sprintf(' (%s)', $name_or_csv ));
3fcf109f
DO
288 }
289 }
290 if (! $dbrollback )
291 $dbxlink->commit();
a0aa39e6 292 // return buildWideRedirectURL ($log);
293}
294
295//MOD
296//MOD
297//MOD
298function renderCopyEntityTagsPortlet ($title, $tags, $preselect, $realm)
299{
300 startPortlet ($title);
301 echo '<a class="toggleTreeMode" style="display:none" href="#"></a>';
302 echo '<table border=0 cellspacing=0 cellpadding=1 align=center class="tagtree">';
303 printTagCheckboxTable ('taglist', $preselect, array(), $tags, $realm);
304 echo '<tr><td class=tdleft>';
305 //echo "</form></td><td class=tdright>";
306 echo '</td></tr></table>';
307 finishPortlet();
308}
309
310function renderCopyEntityTags ($entity_id)
311{
312 global $tagtree, $taglist, $target_given_tags, $pageno, $etype_by_pageno;
313 echo '<table border=0 width="10%"><tr>';
314
315 if (count ($taglist) > getConfigVar ('TAGS_QUICKLIST_THRESHOLD'))
316 {
317 $minilist = getTagChart (getConfigVar ('TAGS_QUICKLIST_SIZE'), $etype_by_pageno[$pageno], $target_given_tags);
318 // It could happen, that none of existing tags have been used in the current realm.
319 if (count ($minilist))
320 {
321 $js_code = "tag_cb.setTagShortList ({";
322 $is_first = TRUE;
323 foreach ($minilist as $tag)
324 {
325 if (! $is_first)
326 $js_code .= ",";
327 $is_first = FALSE;
328 $js_code .= "\n\t${tag['id']} : 1";
329 }
330 $js_code .= "\n});\n$(document).ready(tag_cb.compactTreeMode);";
331 addJS ('js/tag-cb.js');
332 addJS ($js_code, TRUE);
333 }
334 }
335
336 // do not do anything about empty tree, trigger function ought to work this out
337 echo '<td class=pcright>';
338 renderCopyEntityTagsPortlet ('', $tagtree, $target_given_tags, $etype_by_pageno[$pageno]);
339 echo '</td>';
340
341 echo '</tr></table>';
3fcf109f 342}
a0aa39e6 343function mergeLogs ($log1, $log2)
344{
345 $ret = emptyLog();
346 $ret['m'] = array_merge ($log1['m'], $log2['m']);
347 return $ret;
348}
349
350
3fcf109f 351
a0aa39e6 352function emptyLog ()
353{
354 return array
355 (
356 'v' => 2,
357 'm' => array()
358 );
359}
360function oneLiner ($code, $args = array())
361{
362 $ret = emptyLog();
363 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
364 return $ret;
365}
3fcf109f 366?>