root/freepbx/branches/2.6/upgrades/2.6.0beta1/tables.php

Revision 8006, 11.4 kB (checked in by p_lindheimer, 4 years ago)

add sql() function definition if not there

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         ereg("OUT_([0-9]+)",$unique_trunks[$a][0],$trunk_num1);
80         ereg("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 __migrate_trunks_to_table() {
122
123     global $db;
124     global $amp_conf;
125
126     $sql = "
127     CREATE TABLE `trunks`
128     (
129         `trunkid` INTEGER,
130         `name` VARCHAR( 50 ) NOT NULL DEFAULT '',
131         `tech` VARCHAR( 20 ) NOT NULL ,
132         `outcid` VARCHAR( 40 ) NOT NULL DEFAULT '',
133         `keepcid` VARCHAR( 4 ) DEFAULT 'off',
134         `maxchans` VARCHAR( 6 ) DEFAULT '',
135         `failscript` VARCHAR( 255 ) NOT NULL DEFAULT '',
136         `dialoutprefix` VARCHAR( 255 ) NOT NULL DEFAULT '',
137         `channelid` VARCHAR( 255 ) NOT NULL DEFAULT '',
138         `usercontext` VARCHAR( 255 ) NULL,
139         `provider` VARCHAR( 40 ) NULL,
140         `disabled` VARCHAR( 4 ) DEFAULT 'off',
141     
142         PRIMARY KEY  (`trunkid`, `tech`, `channelid`)
143     )
144     ";
145     $check = $db->query($sql);
146     if(DB::IsError($check)) {
147         if($check->getCode() == DB_ERROR_ALREADY_EXISTS) {
148             //echo ("already exists\n");
149             return false;
150         } else {
151             die_freepbx($check->getDebugInfo());   
152         }
153     }
154     
155     // sqlite doesn't support the syntax required for the SQL so we have to do it the hard way
156     if ($amp_conf["AMPDBENGINE"] == "sqlite3") {
157         $sqlstr = "SELECT variable, value FROM globals WHERE variable LIKE 'OUT\_%' ESCAPE '\'";
158         $my_unique_trunks = sql($sqlstr,"getAll",DB_FETCHMODE_ASSOC);
159
160         $sqlstr = "SELECT variable, value FROM globals WHERE variable LIKE 'OUTDISABLE\_%' ESCAPE '\'";
161         $disable_states = sql($sqlstr,"getAll",DB_FETCHMODE_ASSOC);
162
163         foreach($disable_states as $arr)  {
164             $disable_states_assoc[$arr['variable']] = $arr['value'];
165         }
166         global $unique_trunks;
167         $unique_trunks = array();
168
169         foreach ($my_unique_trunks as $this_trunk) {
170
171             $trunk_num = substr($this_trunk['variable'],4);
172             $this_state = (isset($disable_states_assoc['OUTDISABLE_'.$trunk_num]) ? $disable_states_assoc['OUTDISABLE_'.$trunk_num] : 'off');
173             $unique_trunks[] = array($this_trunk['variable'], $this_trunk['value'], $this_state);
174         }
175         // sort this array using a custom function __sort_trunks(), defined above
176         uksort($unique_trunks,"__sort_trunks");
177         // re-index the newly sorted array
178         foreach($unique_trunks as $arr) {
179             $unique_trunks_t[] = array($arr[0],$arr[1],$arr[2]);
180         }
181         $unique_trunks = $unique_trunks_t;
182
183     } else {
184         $sqlstr  = "SELECT t.variable, t.value, d.value state FROM `globals` t ";
185         $sqlstr .= "JOIN (SELECT x.variable, x.value FROM globals x WHERE x.variable LIKE 'OUTDISABLE\_%') d ";
186         $sqlstr .= "ON substring(t.variable,5) = substring(d.variable,12) WHERE t.variable LIKE 'OUT\_%' ";
187         $sqlstr .= "UNION ALL ";
188         $sqlstr .= "SELECT v.variable, v.value, concat(substring(v.value,1,0),'off') state  FROM `globals` v ";
189         $sqlstr .= "WHERE v.variable LIKE 'OUT\_%' AND concat('OUTDISABLE_',substring(v.variable,5)) NOT IN ";
190         $sqlstr .= " ( SELECT variable from globals WHERE variable LIKE 'OUTDISABLE\_%' ) ";
191         $sqlstr .= "ORDER BY variable";
192         $unique_trunks = sql($sqlstr,"getAll");
193     }
194
195     $trunkinfo = array();
196     foreach ($unique_trunks as $trunk) {
197         list($tech,$name) = explode('/',$trunk[1]);
198         $trunkid = ltrim($trunk[0],'OUT_');
199
200         $sqlstr = "
201             SELECT `variable`, `value` FROM `globals` WHERE `variable` IN (
202                 'OUTCID_$trunkid', 'OUTFAIL_$trunkid', 'OUTKEEPCID_$trunkid',
203                 'OUTMAXCHANS_$trunkid', 'OUTPREFIX_$trunkid')
204         ";
205         $trunk_attribs = sql($sqlstr,'getAll',DB_FETCHMODE_ASSOC);
206         $trunk_attrib_hash = array();
207         foreach ($trunk_attribs as $attribs) {
208             $trunk_attrib_hash[$attribs['variable']] = $attribs['value'];
209         }
210
211         switch ($tech) {
212             case 'SIP':
213                 $tech = 'sip';
214                 $user = sql("SELECT `data` FROM `sip` WHERE `id` = '99999$trunkid' AND `keyword` = 'account'",'getOne');
215                 break;
216             case 'IAX':
217             case 'IAX2':
218                 $tech = 'iax';
219                 $user = sql("SELECT `data` FROM `iax` WHERE `id` = '99999$trunkid' AND `keyword` = 'account'",'getOne');
220                 break;
221             case 'ZAP':
222             case 'DUNDI':
223             case 'ENUM':
224                 $tech = strtolower($tech);
225                 $user = '';
226                 break;
227             default:
228                 if (substr($tech,0,4) == 'AMP:') {
229                     $tech='custom';
230                     $name = substr($trunk[1],4);
231                 } else {
232                     $tech = strtolower($tech);
233                 }
234                 $user = '';
235         }
236
237         $trunkinfo[] = array(
238             'trunkid' =>       $trunkid,
239             'tech' =>          $tech,
240             'outcid' =>        $trunk_attrib_hash['OUTCID_'.$trunkid],
241             'keepcid' =>       $trunk_attrib_hash['OUTKEEPCID_'.$trunkid],
242             'maxchans' =>      $trunk_attrib_hash['OUTMAXCHANS_'.$trunkid],
243             'failscript' =>    $trunk_attrib_hash['OUTFAIL_'.$trunkid],
244             'dialoutprefix' => $trunk_attrib_hash['OUTPREFIX_'.$trunkid],
245             'channelid' =>     $name,
246             'usercontext' =>   $user,
247             'disabled' =>      $trunk[2], // disable state
248         );   
249
250         $sqlstr = "INSERT INTO `trunks`
251             ( trunkid, tech, outcid, keepcid, maxchans, failscript, dialoutprefix, channelid, usercontext, disabled)
252             VALUES (
253                 '".$db->escapeSimple($trunkid)."',
254                 '".$db->escapeSimple($tech)."',
255                 '".$db->escapeSimple($trunk_attrib_hash['OUTCID_'.$trunkid])."',
256                 '".$db->escapeSimple($trunk_attrib_hash['OUTKEEPCID_'.$trunkid])."',
257                 '".$db->escapeSimple($trunk_attrib_hash['OUTMAXCHANS_'.$trunkid])."',
258                 '".$db->escapeSimple($trunk_attrib_hash['OUTFAIL_'.$trunkid])."',
259                 '".$db->escapeSimple($trunk_attrib_hash['OUTPREFIX_'.$trunkid])."',
260                 '".$db->escapeSimple($name)."',
261                 '".$db->escapeSimple($user)."',
262                 '".$db->escapeSimple($trunk[2])."'
263           )
264         ";
265         sql($sqlstr);
266     }
267
268     return $trunkinfo;
269 }
270
271 // __migrate_trunks_to_table will return false if the trunks table already exists and
272 // no migration is needed
273 //
274 outn(_("Checking if trunk table migration required.."));
275 $trunks = __migrate_trunks_to_table();
276 if ($trunks !== false) {
277     outn(_("migrating.."));
278     foreach ($trunks as $trunk) {
279         $tech = $trunk['tech'];
280         $trunkid = $trunk['trunkid'];
281         switch ($tech) {
282             case 'sip':
283             case 'iax':
284                 $sql = "UPDATE `$tech` SET `id` = 'tr-peer-$trunkid' WHERE `id` = '9999$trunkid'";
285                 sql($sql);
286                 $sql = "UPDATE `$tech` SET `id` = 'tr-user-$trunkid' WHERE `id` = '99999$trunkid'";
287                 sql($sql);
288                 $sql = "UPDATE `$tech` SET `id` = 'tr-reg-$trunkid' WHERE `id` = '9999999$trunkid' AND `keyword` = 'register'";
289                 sql($sql);
290                 break;
291             default:
292                 break;
293         }
294     }
295     outn(_("removing globals.."));
296     // Don't do this above, in case something goes wrong
297     //
298     // At this point we have created our trunks table and update the sip and iax files
299     // time to get rid of the old globals which will not be auto-generated
300     //
301     foreach ($trunks as $trunk) {
302         $trunkid = $trunk['trunkid'];
303
304         $sqlstr = "
305             DELETE FROM `globals` WHERE `variable` IN (
306                 'OUTCID_$trunkid', 'OUTFAIL_$trunkid', 'OUTKEEPCID_$trunkid',
307                 'OUTMAXCHANS_$trunkid', 'OUTPREFIX_$trunkid', 'OUT_$trunkid',
308                 'OUTDISABLE_$trunkid'
309             )
310         ";
311         sql($sqlstr);
312     }
313     out(_("done"));
314 } else {
315     out(_("not needed"));
316 }
317
318 $sql = "
319 CREATE TABLE `trunks_dialpatterns`
320 (
321     `trunkid` INTEGER,
322     `rule` VARCHAR( 255 ) NOT NULL,
323     `seq` INTEGER,
324     PRIMARY KEY  (`trunkid`, `rule`, `seq`)
325 )
326 ";
327 outn(_("Checking if trunks_dialpatterns table exists.."));
328 $check = $db->query($sql);
329 if(DB::IsError($check) && $check->getCode() != DB_ERROR_ALREADY_EXISTS) {
330     die_freepbx("Can not create trunks_dialpatterns table");
331 } else if(DB::IsError($check) && $check->getCode() == DB_ERROR_ALREADY_EXISTS) {
332     out(_("already exists"));
333 } else {
334     out(_("created"));
335     outn(_("loading table from localprefixes.conf.."));
336     $localPrefixFile = $amp_conf['ASTETCDIR']."/localprefixes.conf";
337     $conf == array();
338     __parse_DialRulesFile($localPrefixFile, $conf, $section);
339
340     $rules_arr = array();
341     foreach ($conf as $tname => $rules) {
342         $tid = ltrim($tname,'trunk-');
343         ksort($rules); //make sure they are in order
344         $seq = 1;
345         foreach ($rules as $rule) {
346             $rules_arr[] = array($tid,$rule,$seq);
347             $seq++;
348         }
349     }
350     $compiled = $db->prepare("INSERT INTO `trunks_dialpatterns` (trunkid, rule, seq) VALUES (?,?,?)");
351     $result = $db->executeMultiple($compiled,$rules_arr);
352     if(DB::IsError($result)) {
353         die_freepbx($result->getDebugInfo().'error populating trunks_dialpatterns table');   
354     }
355     out(_("loaded"));
356 }
357
358 // END of trunks migration code
359
Note: See TracBrowser for help on using the browser.