root/freepbx/trunk/upgrades/2.6.0beta1/tables.php

Revision 12167, 11.5 kB (checked in by p_lindheimer, 2 years ago)

Merged revisions 11124-11125,11128-11133,11135,11137,11145-11147,11149,11166,11168,11216,11228-11229,11240-11241,11243-11244,11255,11263-11264,11272,11278,11280,11282,11285,11291-11293,11300,11302,11321,11334,11339-11343,11352,11363-11364,11366,11368,11382-11384,11388-11390,11399,11405-11406,11421,11449,11453-11460,11462-11464,11471,11482,11485-11487,11493-11494,11498,11502,11504,11528,11530,11535,11543,11555,11558,11574-11576,11579,11581,11583,11585-11587,11589,11591-11592,11599,11622,11629,11631,11633,11637-11639,11641,11652,11662-11663,11666,11668,11671-11672,11675-11676,11704,11711,11714,11719,11721,11723,11725-11726,11732,11755,11760,11762-11764,11767,11769-11770,11772-11774,11796,11799-11800,11805,11807,11810,11812,11818,11822,11826,11828,11830,11841-11842,11853-11855,11891-11892,11900,11928,11931,11937-11940,11944,11954,11960,11968,11971-11974,11986-11987,12016,12021-12022,12024,12036-12037,12044-12046,12056,12061,12066,12068,12073,12076,12154-12156 via svnmerge from

Merged 2.9 branch to trunk.

Line 
1 <?php
2 if (!function_exists('sql')) {
3   function sql($sql,$type="query",$fetchmode=null) {
4       global $db;
5       $results = $db->$type($sql,$fetchmode);
6       if(DB::IsError($results)) {
7           die($results->getDebugInfo() . "SQL - <br /> $sql" );
8       }
9       return $results;
10   }
11 }
12
13 function encrypt_passwords()
14 {
15     global $db;
16     out("Updating passwords..");
17     $sql = "SELECT * FROM ampusers";
18     $users = $db->getAll($sql,NULL,DB_FETCHMODE_ASSOC);
19     if (DB::IsError($users)) { // Error while getting the users list to update... bad
20         die($users->getMessage());
21     } else {
22         outn("(".count($users)." accounts) ");   
23         foreach ($users as $index => $ufields) {
24             $sql = "UPDATE ampusers SET password_sha1='".sha1($ufields['password'])."' WHERE username='".$ufields['username']."'";
25             $result = $db->query($sql);
26             if (DB::IsError($result)) {
27                 outn("Error while updating account: ".$ufields['username']." (".$result->getMessage.")");
28             }   
29         }
30     }
31     out("Done.");
32 }
33
34 outn("Checking for sha1 passwords..");
35 $sql = "SELECT password_sha1 FROM ampusers";
36 $passfield = $db->getRow($sql, DB_FETCHMODE_ASSOC);
37 if (!DB::IsError($passfield)) { // no error... Already done
38     $sql = "SELECT password FROM ampusers";
39     $passfield = $db->getRow($sql, DB_FETCHMODE_ASSOC);
40     if (DB::IsError($passfield)) { //password field do not exist, done
41         out("OK.");
42     } else { //Field password still exist, update of passwords is needed.
43         encrypt_passwords();
44     }
45 } else {
46     if ($passfield->code == DB_ERROR_NOSUCHFIELD) {
47         outn("Updating database..");
48         $sql = "ALTER TABLE ampusers ADD password_sha1 VARCHAR ( 40 ) NOT NULL AFTER password";
49         $results = $db->query($sql);
50         if (DB::IsError($results)) {
51             die($sql."\n".$results->getMessage());
52         } else {
53             out("Done.");
54             encrypt_passwords();
55             outn("Removing old password column..");
56             $sql = "ALTER TABLE ampusers DROP password";
57             $results = $db->query($sql);
58             if (DB::IsError($results)) {
59                 die($results->getMessage());
60             } else {
61                 out("Done.");
62             }
63         }
64     } else { //The error was not about the field...
65         die($passfield->getMessage());
66     }
67 }
68             
69 // This next set of functions and code are used to migrate from the old
70 // global variable storage of trunk data to the new trunk table and trunk
71 // pattern table for localprefixes.conf
72 // this is taken straight out of the core install.php script, as new installs
73 // with install_amp break and haven't taken the time to figure out why.
74 //
75
76 //Sort trunks for sqlite
77 function __sort_trunks($a,$b)  {
78         global $unique_trunks;
79         preg_match("/OUT_([0-9]+)/",$unique_trunks[$a][0],$trunk_num1);
80         preg_match("/OUT_([0-9]+)/",$unique_trunks[$b][0],$trunk_num2);
81         return ($trunk_num1[1] >= $trunk_num2[1]? 1:-1);
82 }
83
84 // Get values from localprefix configuration file where values are stored
85 // for fixlocalprefix macro
86 //
87 function __parse_DialRulesFile($filename, &$conf, &$section) {
88     if (is_null($conf)) {
89         $conf = array();
90     }
91     if (is_null($section)) {
92         $section = "general";
93     }
94     
95     if (file_exists($filename)) {
96         $fd = fopen($filename, "r");
97         while ($line = fgets($fd, 1024)) {
98             if (preg_match("/^\s*([a-zA-Z0-9-_]+)\s*=\s*(.*?)\s*([;#].*)?$/",$line,$matches)) {
99                 // name = value
100                 // option line
101                 $conf[$section][ $matches[1] ] = $matches[2];
102             } else if (preg_match("/^\s*\[(.+)\]/",$line,$matches)) {
103                 // section name
104                 $section = strtolower($matches[1]);
105             } else if (preg_match("/^\s*#include\s+(.*)\s*([;#].*)?/",$line,$matches)) {
106                 // include another file
107                 
108                 if ($matches[1][0] == "/") {
109                     // absolute path
110                     $filename = $matches[1];
111                 } else {
112                     // relative path
113                     $filename dirname($filename)."/".$matches[1];
114                 }
115                 __parse_DialRulesFile($filename, $conf, $section);
116             }
117         }
118     }
119 }
120
121 function __order_DialRules($a, $b) {
122   return substr($a,4) > substr($b,4);
123 }
124
125 function __migrate_trunks_to_table() {
126
127     global $db;
128     global $amp_conf;
129
130     $sql = "
131     CREATE TABLE `trunks`
132     (
133         `trunkid` INTEGER,
134         `name` VARCHAR( 50 ) NOT NULL DEFAULT '',
135         `tech` VARCHAR( 20 ) NOT NULL ,
136         `outcid` VARCHAR( 40 ) NOT NULL DEFAULT '',
137         `keepcid` VARCHAR( 4 ) DEFAULT 'off',
138         `maxchans` VARCHAR( 6 ) DEFAULT '',
139         `failscript` VARCHAR( 255 ) NOT NULL DEFAULT '',
140         `dialoutprefix` VARCHAR( 255 ) NOT NULL DEFAULT '',
141         `channelid` VARCHAR( 255 ) NOT NULL DEFAULT '',
142         `usercontext` VARCHAR( 255 ) NULL,
143         `provider` VARCHAR( 40 ) NULL,
144         `disabled` VARCHAR( 4 ) DEFAULT 'off',
145     
146         PRIMARY KEY  (`trunkid`, `tech`, `channelid`)
147     )
148     ";
149     $check = $db->query($sql);
150     if(DB::IsError($check)) {
151         if($check->getCode() == DB_ERROR_ALREADY_EXISTS) {
152             //echo ("already exists\n");
153             return false;
154         } else {
155             die_freepbx($check->getDebugInfo());   
156         }
157     }
158     
159     // sqlite doesn't support the syntax required for the SQL so we have to do it the hard way
160     if ($amp_conf["AMPDBENGINE"] == "sqlite3") {
161         $sqlstr = "SELECT variable, value FROM globals WHERE variable LIKE 'OUT\_%' ESCAPE '\'";
162         $my_unique_trunks = sql($sqlstr,"getAll",DB_FETCHMODE_ASSOC);
163
164         $sqlstr = "SELECT variable, value FROM globals WHERE variable LIKE 'OUTDISABLE\_%' ESCAPE '\'";
165         $disable_states = sql($sqlstr,"getAll",DB_FETCHMODE_ASSOC);
166
167         foreach($disable_states as $arr)  {
168             $disable_states_assoc[$arr['variable']] = $arr['value'];
169         }
170         global $unique_trunks;
171         $unique_trunks = array();
172
173         foreach ($my_unique_trunks as $this_trunk) {
174
175             $trunk_num = substr($this_trunk['variable'],4);
176             $this_state = (isset($disable_states_assoc['OUTDISABLE_'.$trunk_num]) ? $disable_states_assoc['OUTDISABLE_'.$trunk_num] : 'off');
177             $unique_trunks[] = array($this_trunk['variable'], $this_trunk['value'], $this_state);
178         }
179         // sort this array using a custom function __sort_trunks(), defined above
180         uksort($unique_trunks,"__sort_trunks");
181         // re-index the newly sorted array
182         foreach($unique_trunks as $arr) {
183             $unique_trunks_t[] = array($arr[0],$arr[1],$arr[2]);
184         }
185         $unique_trunks = $unique_trunks_t;
186
187     } else {
188         $sqlstr  = "SELECT t.variable, t.value, d.value state FROM `globals` t ";
189         $sqlstr .= "JOIN (SELECT x.variable, x.value FROM globals x WHERE x.variable LIKE 'OUTDISABLE\_%') d ";
190         $sqlstr .= "ON substring(t.variable,5) = substring(d.variable,12) WHERE t.variable LIKE 'OUT\_%' ";
191         $sqlstr .= "UNION ALL ";
192         $sqlstr .= "SELECT v.variable, v.value, concat(substring(v.value,1,0),'off') state  FROM `globals` v ";
193         $sqlstr .= "WHERE v.variable LIKE 'OUT\_%' AND concat('OUTDISABLE_',substring(v.variable,5)) NOT IN ";
194         $sqlstr .= " ( SELECT variable from globals WHERE variable LIKE 'OUTDISABLE\_%' ) ";
195         $sqlstr .= "ORDER BY variable";
196         $unique_trunks = sql($sqlstr,"getAll");
197     }
198
199     $trunkinfo = array();
200     foreach ($unique_trunks as $trunk) {
201         list($tech,$name) = explode('/',$trunk[1]);
202         $trunkid = ltrim($trunk[0],'OUT_');
203
204         $sqlstr = "
205             SELECT `variable`, `value` FROM `globals` WHERE `variable` IN (
206                 'OUTCID_$trunkid', 'OUTFAIL_$trunkid', 'OUTKEEPCID_$trunkid',
207                 'OUTMAXCHANS_$trunkid', 'OUTPREFIX_$trunkid')
208         ";
209         $trunk_attribs = sql($sqlstr,'getAll',DB_FETCHMODE_ASSOC);
210         $trunk_attrib_hash = array();
211         foreach ($trunk_attribs as $attribs) {
212             $trunk_attrib_hash[$attribs['variable']] = $attribs['value'];
213         }
214
215         switch ($tech) {
216             case 'SIP':
217                 $tech = 'sip';
218                 $user = sql("SELECT `data` FROM `sip` WHERE `id` = '99999$trunkid' AND `keyword` = 'account'",'getOne');
219                 break;
220             case 'IAX':
221             case 'IAX2':
222                 $tech = 'iax';
223                 $user = sql("SELECT `data` FROM `iax` WHERE `id` = '99999$trunkid' AND `keyword` = 'account'",'getOne');
224                 break;
225             case 'ZAP':
226             case 'DUNDI':
227             case 'ENUM':
228                 $tech = strtolower($tech);
229                 $user = '';
230                 break;
231             default:
232                 if (substr($tech,0,4) == 'AMP:') {
233                     $tech='custom';
234                     $name = substr($trunk[1],4);
235                 } else {
236                     $tech = strtolower($tech);
237                 }
238                 $user = '';
239         }
240
241         $trunkinfo[] = array(
242             'trunkid' =>       $trunkid,
243             'tech' =>          $tech,
244             'outcid' =>        $trunk_attrib_hash['OUTCID_'.$trunkid],
245             'keepcid' =>       $trunk_attrib_hash['OUTKEEPCID_'.$trunkid],
246             'maxchans' =>      $trunk_attrib_hash['OUTMAXCHANS_'.$trunkid],
247             'failscript' =>    $trunk_attrib_hash['OUTFAIL_'.$trunkid],
248             'dialoutprefix' => $trunk_attrib_hash['OUTPREFIX_'.$trunkid],
249             'channelid' =>     $name,
250             'usercontext' =>   $user,
251             'disabled' =>      $trunk[2], // disable state
252         );   
253
254         $sqlstr = "INSERT INTO `trunks`
255             ( trunkid, tech, outcid, keepcid, maxchans, failscript, dialoutprefix, channelid, usercontext, disabled)
256             VALUES (
257                 '".$db->escapeSimple($trunkid)."',
258                 '".$db->escapeSimple($tech)."',
259                 '".$db->escapeSimple($trunk_attrib_hash['OUTCID_'.$trunkid])."',
260                 '".$db->escapeSimple($trunk_attrib_hash['OUTKEEPCID_'.$trunkid])."',
261                 '".$db->escapeSimple($trunk_attrib_hash['OUTMAXCHANS_'.$trunkid])."',
262                 '".$db->escapeSimple($trunk_attrib_hash['OUTFAIL_'.$trunkid])."',
263                 '".$db->escapeSimple($trunk_attrib_hash['OUTPREFIX_'.$trunkid])."',
264                 '".$db->escapeSimple($name)."',
265                 '".$db->escapeSimple($user)."',
266                 '".$db->escapeSimple($trunk[2])."'
267           )
268         ";
269         sql($sqlstr);
270     }
271
272     return $trunkinfo;
273 }
274
275 // __migrate_trunks_to_table will return false if the trunks table already exists and
276 // no migration is needed
277 //
278 outn(_("Checking if trunk table migration required.."));
279 $trunks = __migrate_trunks_to_table();
280 if ($trunks !== false) {
281     outn(_("migrating.."));
282     foreach ($trunks as $trunk) {
283         $tech = $trunk['tech'];
284         $trunkid = $trunk['trunkid'];
285         switch ($tech) {
286             case 'sip':
287             case 'iax':
288                 $sql = "UPDATE `$tech` SET `id` = 'tr-peer-$trunkid' WHERE `id` = '9999$trunkid'";
289                 sql($sql);
290                 $sql = "UPDATE `$tech` SET `id` = 'tr-user-$trunkid' WHERE `id` = '99999$trunkid'";
291                 sql($sql);
292                 $sql = "UPDATE `$tech` SET `id` = 'tr-reg-$trunkid' WHERE `id` = '9999999$trunkid' AND `keyword` = 'register'";
293                 sql($sql);
294                 break;
295             default:
296                 break;
297         }
298     }
299     outn(_("removing globals.."));
300     // Don't do this above, in case something goes wrong
301     //
302     // At this point we have created our trunks table and update the sip and iax files
303     // time to get rid of the old globals which will not be auto-generated
304     //
305     foreach ($trunks as $trunk) {
306         $trunkid = $trunk['trunkid'];
307
308         $sqlstr = "
309             DELETE FROM `globals` WHERE `variable` IN (
310                 'OUTCID_$trunkid', 'OUTFAIL_$trunkid', 'OUTKEEPCID_$trunkid',
311                 'OUTMAXCHANS_$trunkid', 'OUTPREFIX_$trunkid', 'OUT_$trunkid',
312                 'OUTDISABLE_$trunkid'
313             )
314         ";
315         sql($sqlstr);
316     }
317     out(_("done"));
318 } else {
319     out(_("not needed"));
320 }
321
322 $sql = "
323 CREATE TABLE `trunks_dialpatterns`
324 (
325     `trunkid` INTEGER,
326     `rule` VARCHAR( 255 ) NOT NULL,
327     `seq` INTEGER,
328     PRIMARY KEY  (`trunkid`, `rule`, `seq`)
329 )
330 ";
331 outn(_("Checking if trunks_dialpatterns table exists.."));
332 $check = $db->query($sql);
333 if(DB::IsError($check) && $check->getCode() != DB_ERROR_ALREADY_EXISTS) {
334     die_freepbx("Can not create trunks_dialpatterns table");
335 } else if(DB::IsError($check) && $check->getCode() == DB_ERROR_ALREADY_EXISTS) {
336     out(_("already exists"));
337 } else {
338     out(_("created"));
339     outn(_("loading table from localprefixes.conf.."));
340     $localPrefixFile = $amp_conf['ASTETCDIR']."/localprefixes.conf";
341     $conf = array();
342     __parse_DialRulesFile($localPrefixFile, $conf, $section);
343
344     $rules_arr = array();
345     foreach ($conf as $tname => $rules) {
346         $tid = ltrim($tname,'trunk-');
347         uksort($rules,'__order_DialRules'); //make sure they are in order
348         $seq = 1;
349         foreach ($rules as $rule) {
350             $rules_arr[] = array($tid,$rule,$seq);
351             $seq++;
352         }
353     }
354     $compiled = $db->prepare("INSERT INTO `trunks_dialpatterns` (trunkid, rule, seq) VALUES (?,?,?)");
355     $result = $db->executeMultiple($compiled,$rules_arr);
356     if(DB::IsError($result)) {
357         die_freepbx($result->getDebugInfo().'error populating trunks_dialpatterns table');   
358     }
359     out(_("loaded"));
360 }
361
362 // END of trunks migration code
363
Note: See TracBrowser for help on using the browser.