Ticket #3291: retrieve_op_conf_from_mysql.2.php

File retrieve_op_conf_from_mysql.2.php, 23.0 kB (added by Nick_Lewis, 3 years ago)
Line 
1 #!/usr/bin/php
2 <?php
3
4 # Retrieves the sip user/peer entries from the database for the flash operator panel
5
6 //include("/var/www/html/admin/functions.inc.php");
7 //include("DB.php");
8 require_once("/var/www/html/admin/functions.inc.php");
9 require_once("DB.php");
10
11 ################### BEGIN OF CONFIGURATION ####################
12
13 if ($argc == 2)
14 {
15   $amportalconf = $argv[0];
16   $zapataconf = $argv[1]."/zapata.conf";
17   $zapataautoconf = $argv[1]."/zapata-auto.conf";
18 } else
19 {
20   $amportalconf = "/etc/amportal.conf";
21   $zapataconf="/etc/asterisk/zapata.conf";
22   $zapataautoconf="/etc/asterisk/zapata-auto.conf";
23 }
24
25 ######## LAYOUT INFO #########
26
27 # NOTE - These values may be overwritten by values in a table in the freepbx database named "panel"
28
29 # structure is - ID, Legend, startpos, stoppos, color1, color2
30 $rectangle1 = array("trunk","Trunks", 53, 80, "10ff10", "009900");
31 $rectangle2 = array("extension","Extensions", 1, 40, "1010ff", "99cccc");
32 $rectangle3 = array("parking","Parking lots", 49, 72, "ffff10", "cc9933");
33 $rectangle4 = array("conference","Conferences", 45, 68, "006666", "00a010");
34 $rectangle5 = array("queue","Queues", 41, 64, "ff1010", "a01000");
35 $rectangles = array($rectangle1,$rectangle2,$rectangle3,$rectangle4,$rectangle5);
36
37 $rectmarginx = 1;
38 $rectmarginy = 1;
39 $legendoffsetx = 3;
40 $legendoffsety = 1;
41
42 # $layoutbuttonsonly = 0 : allow display of buttons even if no corresponding layout info
43 # $layoutbuttonsonly = 1 : suppress display of buttons if no corresponding layout info
44 $layoutbuttonsonly = 1;
45
46 ######## BUTTON INFO #########
47 $buttonsizex = 246; # 1+244+1 from information in op_style.cfg
48 $buttonsizey = 28; # 1+26+1 from information in op_style.cfg
49 $numbuttonsx = 4;
50 $numbuttonsy = 20;
51 $buttonsoriginx = -1;
52 $buttonsoriginy = 32;
53
54
55 ######## STYLE INFO #########
56
57 # NOTE - These values may be overwritten by the syleinfo function with values generated from the layout info
58
59 $extenpos="2-40";
60 $trunkpos="53-60,72-80";
61 $parkingpos="50-51,69-71";
62 $confepos="46-48,65-68";
63 $queuepos="42-44,61-64";
64
65
66
67 # Remove or add Zap trunks as needed
68 # Note: ZAP/* will match any ZAP channel that *is not referenced* in another button (ie: extensions)
69 $zaplines=array(); # zap channel, description
70 #array_push($zaplines,array( "Zap/*","PSTN" ));
71 #array_push($zaplines,array( "Zap/1","Zap 1" ));
72 #array_push($zaplines,array( "Zap/2","Zap 2" ));
73 #array_push($zaplines,array( "Zap/3","Zap 3" ));
74 #array_push($zaplines,array( "Zap/4","Zap 4" ));
75
76
77
78 if (file_exists($zapataconf)) {
79   $zaplines = parse_zapata($zapataconf);
80 }
81 // TODO: it would be better if it followed the includes in zapata.conf in case there are other zapataxxx.conf files
82 if (file_exists($zapataautoconf)) {
83   $zaplines = parse_zapata($zapataautoconf);
84 }
85
86 function parse_zapata($conffile) {
87   # LETS PARSE zapata.conf
88   # Allowed format options
89   # %c Zap Channel number
90   # %n Line number
91   # %N Line number, but restart counter
92   # Example:
93   # ;AMPLABEL:Channel %c - Button %n
94
95   global $zaplines;
96   global $ampwildcard;
97   global $zaplabel;
98   global $istrunk;
99   global $lastlabelnum;
100
101   if (!isset($zaplabel)) {$zaplabel="Zap \%c";}
102   $lastlabelnum=0; //should be safe as long as channel defs are not spread across files
103   $ampwildcard=false;
104   $filearray = file($conffile);
105   if ($filearray === false) {die("Cannot open config file: $conffile\n");}
106   foreach ($filearray as $line) {
107     $line = trim($line);
108     if ($line == '') {next;}
109     $temparray = @explode(";AMPWILDCARDLABEL(",$line,2);
110     if (count($temparray) == 2) {
111
112      $temparray = @explode("):",$temparray[1],2);
113      if (count($temparray) != 2)  {next;}
114      array_push($zaplines,array("Zap/*",trim($temparray[1]),($temparray[0])));
115      $ampwildcard=true;
116      next;
117     }
118
119     $temparray = @explode(";AMPLABEL:",$line,2);
120     if (count($temparray) == 2) {
121      $zaplabel=trim($temparray[1]);
122      $ampwildcard=false;
123      if (strpos($temparray[1],"%N") === false) {next;}
124      $lastlabelnum=0;
125      next;
126     }
127
128                 # check if trunk or extension
129                 //note that some versions of php do not support !== but only ===
130                 if (!(strpos($line,"context=from-pstn") === false)) {
131                         $istrunk=true;
132                         next;
133                 }
134                 if (!(strpos($line,"context=from-zaptel") === false)) {
135                         $istrunk=true;
136                         next;
137                 }
138                 if (!(strpos($line,"context=from-internal") === false)) {
139                         $istrunk=false;
140                         next;
141                 }
142
143     $crud = array(" ", "\t" , ">");
144     $line = str_replace($crud,"",$line);
145     $line = trim($line);
146     $temparray = @explode("channel=",$line,2);
147     if ((count($temparray) == 2) and ($ampwildcard === false))  {
148       $temparray = @explode(",",$temparray[1],2);
149       foreach ($temparray as $range) {
150         list($start,$end) = @explode("-",$range,2);
151         if (!isset($end)) {$end = $start;}
152         for ($i = $start; $i <= $end; $i++) {
153           $lastlabelnum++;
154           $newlabel=$zaplabel;
155           $newlabel=str_replace("%c",$i,$newlabel);
156           $newlabel=str_replace("%n",$lastlabelnum,$newlabel);
157           $newlabel=str_replace("%N",$lastlabelnum,$newlabel);
158
159 # only add if A) this is a trunk
160 # and B) we have not already defined any zaplines at the top of the file
161 # (I use this to customize it so instead of saying "Zap 1" it will
162 # say something more useful -- like the phone # of the line)
163
164           if($istrunk) {
165             $inzaplines=false;
166             foreach ($zaplines as $tempvalue) {
167               if($tempvalue[0] == "Zap/$i") {
168                 $inzaplines=true;
169                 break;
170               }
171             }
172
173             if (!($inzaplines)) {
174               array_push($zaplines,array( "Zap/$i","$newlabel" ));
175             }
176           } //istrunk
177         } //for $i
178       } //foreach $range
179     } // if "channel="
180   } //foreach $line
181   return $zaplines;
182 }
183 #Finished parsing zapata.conf
184
185
186 # Conference Rooms not yet implemented in AMP config
187 $conferences=array();   #### ext#, description
188 #array_push($conferences,array( "810","Conf.10" ));
189 #array_push($conferences,array( "811","Conf.11" ));
190
191 # cool hack by Julien BLACHE <jblache@debian.org>
192 $ampconf = parse_amportal_conf( $amportalconf );
193 # WARNING: this file will be substituted by the output of this program
194 $op_conf = $ampconf["AMPWEBROOT"]."/panel/op_buttons_additional.cfg";
195 # username to connect to the database
196 $username = $ampconf["AMPDBUSER"];
197 # password to connect to the database
198 $password = $ampconf["AMPDBPASS"];
199 # the name of the box the MySQL database is running on
200 $hostname = $ampconf["AMPDBHOST"];
201 # the name of the database our tables are kept
202 $database = $ampconf["AMPDBNAME"];
203 #sort option: extension or lastname
204 $sortoption = $ampconf["FOPSORT"];
205
206 # the engine to be used for the SQL queries,
207 # if none supplied, backfall to mysql
208 $db_engine = "mysql";
209 if (isset($ampconf["AMPDBENGINE"])){
210   $db_engine = $ampconf["AMPDBENGINE"];
211 }
212 ################### END OF CONFIGURATION #######################
213
214 $warning_banner =
215 "; do not edit this file, this is an auto-generated file by freepbx
216 ; all modifications must be done from the web gui
217 ";
218
219 switch ($db_engine)
220 {
221         case "pgsql":
222         case "mysql":
223                 /* datasource in in this style:
224                 dbengine://username:password@host/database */
225
226                 $datasource = $db_engine.'://'.$username.':'.$password.'@'.$hostname.'/'.$database;
227                 $db = DB::connect($datasource); // attempt connection
228                 break;
229
230         case "sqlite":
231                 require_once('DB/sqlite.php');
232
233                 if (!isset($amp_conf["AMPDBFILE"]))
234                         die("You must setup properly AMPDBFILE in /etc/amportal.conf");
235
236                 if (isset($amp_conf["AMPDBFILE"]) == "")
237                         die("AMPDBFILE in /etc/amportal.conf cannot be blank");
238
239                 $DSN = array (
240                         "database" => $amp_conf["AMPDBFILE"],
241                         "mode" => 0666
242                 );
243
244                 $db = new DB_sqlite();
245                 $db->connect( $DSN );
246                 break;
247
248         default:
249                 die( "Unknown SQL engine: [$db_engine]");
250 }
251
252 if(DB::isError($db)) {
253        echo("FAILED\n");
254        echo("Cannot connect to database\n");
255      die($db->getMessage());
256
257 }
258
259 # Get layout-info from a "panel" table in the freepbx database
260 if (table_exists($db,"panel")) {
261
262   $statement = "SELECT id, legend, startpos, stoppos, color1, color2 from panel";
263   $results = $db->getAll($statement);
264   if(DB::IsError($results)) {
265      die($results->getMessage());
266   }
267   if (count($results) < 1) {
268     print "Notice: no panel defined\n";
269   }
270   $rectangles = $results;
271 }
272
273 // pass layout info to function explicitly rather than via globals
274 $layoutinfo = array('rectangles'=>$rectangles,'numbuttonsx'=>$numbuttonsx,'numbuttonsy'=>$numbuttonsy);
275
276 # Automated generation of style-info from layout-info
277 $autoextenpos=get_styleinfo("extension",$layoutinfo);
278 $autotrunkpos=get_styleinfo("trunk",$layoutinfo);
279 $autoparkingpos=get_styleinfo("parking",$layoutinfo);
280 $autoconfepos=get_styleinfo("conference",$layoutinfo);
281 $autoqueuepos=get_styleinfo("queue",$layoutinfo);
282
283 if ($layoutbuttonsonly == 1) {$extenpos = ""; $trunkpos = ""; $parkingpos = ""; $confepos = ""; $queuepos = "";}
284
285 if (isset($autoextenpos)) {$extenpos = $autoextenpos;}
286 if (isset($autotrunkpos)) {$trunkpos = $autotrunkpos;}
287 if (isset($autoparkingpos)) {$parkingpos = $autoparkingpos;}
288 if (isset($autoconfepos)) {$confepos = $autoconfepos;}
289 if (isset($autoqueuepos)) {$queuepos = $autoqueuepos;}
290
291
292 $fhandle = fopen($op_conf,"w" );
293 if ($fhandle === false) {die("Cannot create/overwrite config file: $op_conf \n");}
294 fwrite($fhandle, $warning_banner);
295
296 #First, populate extensions
297
298 $extensionlist=array();
299
300 if (table_exists($db,"devices")) {
301   $statement = "SELECT description,id,dial,tech from devices";
302   $results = $db->getAll($statement);
303   if(DB::IsError($results)) {
304      die($results->getMessage());
305   }
306   if (count($results) < 1) {
307     print "Notice: no Devices defined\n";
308   }
309   $extensionlist = $results;
310 }
311 else { print "Table does not exist: devices\n"; }
312
313 # sort the extensions
314 foreach ($extensionlist as $key=>$extension) {
315   $temparray = explode(" ",$extension[0]);
316   $lastname[$key] = end($temparray);
317   $extnum[$key] = $extension[1];
318 }
319
320 if  (isset($sortoption) && ($sortoption == "lastname")) {
321   array_multisort($lastname,$extensionlist);
322 } else {
323   array_multisort($extnum,SORT_STRING,$extensionlist);
324 }
325
326 #Next, populate queues
327 $queues=array();
328 if (table_exists($db,"queues_config")) {
329   $statement = "SELECT extension,descr from queues_config order by extension";
330   $results = $db->getAll($statement);
331   if(DB::IsError($results)) {
332      die($results->getMessage());
333   }
334   if (count($results) < 1) {
335     print "Notice: no Queues defined\n";
336   }
337   $queues = $results;
338 }
339 else { print "Table does not exist: queues_config\n"; }
340
341
342 ## SME server chnges
343
344 #Next, populate conferences
345 $conferences=array();
346 if(table_exists($db,"meetme")) {
347   $statement = "SELECT exten,description FROM meetme ORDER BY exten";
348   $results = $db->getAll($statement);
349   if(DB::IsError($results)) {
350      die($results->getMessage());
351   }
352   if (count($results) < 1) {
353     print "Notice: no Conferences defined\n";
354   }
355   $conferences = $results;
356 }
357 else { print "Table does not exist: meetme\n"; }
358
359
360 #Next, populate parkings
361 $parkings=array();
362 if(table_exists($db,"parkinglot")) {
363   $statement = "SELECT keyword,data FROM parkinglot";
364   $results = $db->getAll($statement);
365   if(DB::IsError($results)) {
366      die($results->getMessage());
367   }
368   if (count($results) < 1) {
369     print "Notice: no Parking Lots defined\n";
370   }
371   $parkings = $results;
372 }
373 else { print "Table does not exist: parkinglot\n"; }
374
375 ## End of changes
376 #Next, populate trunks (sip and iax)
377 $trunklist=array();
378 $tables = array("sip","iax");
379 foreach ($tables as $table) {
380   if (table_exists($db,$table)) {
381     $statement = "SELECT data,id,'$table' from $table where keyword='account' and flags <> 1 and id>99990 group by data order by id";
382     $results = $db->getAll($statement);
383     if(DB::IsError($results)) {
384        die($results->getMessage());
385     }
386     if (count($results) < 1) {
387       print "Notice: no $table trunks defined\n";
388     }
389     $trunklist = array_merge($trunklist,$results);
390 }
391 else { print "Table does not exist: $table \n"; }
392 }
393
394 #Determine AMP Users
395 $ampusers=array(array("default","0","0"));
396 if (table_exists($db,"ampusers")) {
397   $statement = 'SELECT deptname,extension_low,extension_high from ampusers WHERE NOT extension_low = "" AND NOT extension_high = ""';
398     $results = $db->getAll($statement);
399     if(DB::IsError($results)) {
400        die($results->getMessage());
401     }
402     if (count($results) < 1) {
403       print "Notice: no AMP Users defined\n";
404     }
405     else {
406       $ampusers = $results;
407     }
408 }
409 else { print "Table does not exist: ampusers\n"; }
410
411 #Write a separate panel context from each AMP User department
412 foreach ($ampusers as $pcontext) {
413   $exten_low = $pcontext[1];
414   $exten_high = $pcontext[2];
415   $panelcontext = $pcontext[0];
416   if ($panelcontext == "") { $panelcontext = $exten_low."to".$exten_high; }
417
418
419   # WRITE EXTENSIONS
420
421   $btn=0;
422   if ($exten_low != 0 && $exten_high != 0) {  #display only allowed range of extensions for panel_contexts
423     $extensionrange = array();
424     foreach ($extensionlist as $value) {
425       if (!is_numeric($value)) {array_push($extensionrange,$value);}
426       if (($value >= $exten_low) && ($value <= $exten_high))  {array_push($extensionrange,$value);}
427     }
428   } else {
429     $extensionrange = $extensionlist;
430   }
431   foreach ( $extensionrange as $row ) {
432     $description = $row[0];
433     $id = $row[1];
434     $dial = $row[2];
435
436
437     # Support for real mailbox settings -
438     $tech = $row[3];
439     # some sensible defaults for voicemail ext and context
440     $vmext = $row[1];
441     $vmcontext = "default";
442     # the device tech table should also have a dial context - if not assume from-internal
443     $context = "from-internal";
444     # database table name for iax2 is just iax but sip and zap are ok
445     if ($tech == "iax2") {$tech = "iax";}
446     # get mailbox setting from relevant tech table and split into ext and content
447     if (table_exists($db,$tech)) {
448       $statement = "SELECT data from $tech WHERE id = '$id' AND keyword = 'mailbox' ";
449       $results = $db->getAll($statement);
450       if(DB::IsError($results)) {
451          die($results->getMessage());
452       }
453       if (count($results) < 1) {
454         print "Notice: no Mailboxes defined\n";
455       }
456       else {
457       $mailbox = $results[0][0];
458       $values = @explode('@', $mailbox,2);
459       if (strlen($values[0]) > 0) {$vmext = $values[0];}
460       if (strlen($values[1]) > 0) {$vmcontext = $values[1];}
461       }
462       #while in this table lets get the dial context as well
463       $statement = "SELECT data from $tech WHERE id = '$id' AND keyword = 'context' ";
464       $results = $db->getAll($statement);
465       if(DB::IsError($results)) {
466          die($results->getMessage());
467       }
468       if (count($results) < 1) {
469         print "Notice: no Context defined\n";
470       }
471       else {
472       $context = $results[0][0];
473       }
474     } else { print "Table does not exist: $tech\n"; }
475     # - Support for real mailbox settings
476
477
478     # Support for real VM_PREFIX -
479     $vmprefix = "*";
480     if (table_exists($db,"globals")) {
481       $statement = "SELECT value from globals WHERE variable = 'VM_PREFIX' ";
482       $results = $db->getAll($statement);
483       if(DB::IsError($results)) {
484          die($results->getMessage());
485       }
486       if (count($results) < 1) {
487         print "Notice: no VM Prefix defined\n";
488       }
489       else {
490       $vmprefix = $results[0][0];
491       }
492     } else { print "Table does not exist: global\n"; }
493     # - Support for real VM_PREFIX
494
495     $btn=get_next_btn($extenpos,$btn);
496     $icon='4';
497     fwrite($fhandle, "[$dial]\nPosition=$btn\nLabel=\"$id : $description\"\nExtension=$id\nContext=$context\nIcon=$icon\nVoicemail_Context=$vmcontext\nVoiceMailExt=$vmprefix$vmext@$context\nPanel_Context=$panelcontext\n");
498   }
499
500
501   ### NOW WRITE TRUNKS.. WE START WITH ZAP TRUNKS DEFINED ABOVE
502
503
504
505
506   $btn=0;
507
508   foreach ($zaplines as $row) {
509     $zapdef=$row[0];
510     $zapdesc=$row[1];
511     $icon='3';
512     # zaplines and trunklist share the trunk positions so need to store previous btn on overflow from zaplines
513     $previousbtn = $btn;
514     $btn=get_next_btn($trunkpos,$btn);
515     if ($btn == 0) {$btn = $previousbtn; last;}
516     if ($zapdef == "Zap/*") {
517       $numbuttons=$row[2]-1;
518       fwrite($fhandle, "[$zapdef]\nLabel=\"$zapdesc\"\nExtension=-1\nIcon=$icon\nPanel_Context=$panelcontext\nPosition=".$btn);
519       while($numbuttons-->0) {
520         $btn=get_next_btn($trunkpos,$btn);
521         fwrite($fhandle, ",".$btn);
522       }
523
524       fwrite($fhandle, "\n");
525     } else {
526       fwrite($fhandle, "[$zapdef]\nPosition=$btn\nLabel=\"$zapdesc\"\nExtension=-1\nIcon=$icon\nPanel_Context=$panelcontext\n");
527     }
528   }
529
530
531   foreach ($trunklist as $row) {
532     $account = $row[0];
533     $id = $row[1];
534     $table = $row[2];
535     if ($account == "") {next;};
536     $btn=get_next_btn($trunkpos,$btn);
537     if ($btn == 0) {last;}
538     if (table_exists($db,$table)) {
539     $statement = "SELECT keyword,data from $table where id=$id and keyword <> 'account' and flags <> 1 order by keyword";
540       $results = $db->getAll($statement);
541       if(DB::IsError($results)) {
542          die($results->getMessage());
543       }
544       if (count($results) < 1) {
545         print "Notice: no Trunks defined\n";
546       }
547     } else { print "Table does not exist: $table \n"; }
548
549     if ($table == "sip") {$tech="SIP";}
550     if ($table == "iax") {$tech="IAX2";}
551     #if ($table == "zap") {$tech="ZAP";} #no zap trunks in db
552
553     $callerid = $account;  #default callerid to account
554
555     foreach ($results as $drow) {
556       if ( $drow[0] == "callerid" ) {
557         $callerid = $drow[1];
558         $fields = explode("<",$callerid);
559         $callerid=$fields[1] ." ". $fields[0];
560         $callerid = str_replace("\t","",$callerid);
561         $callerid = str_replace("\"","",$callerid);
562         $callerid = str_replace("<","",$callerid);
563         $callerid = str_replace(">","",$callerid);
564       }
565     }
566     $icon='3';
567     fwrite($fhandle, "[$tech/$account]\nPosition=$btn\nLabel=\"$callerid\"\nExtension=-1\nIcon=$icon\nPanel_Context=$panelcontext\n");
568   }
569
570
571   ## SME server changes
572
573
574
575         ### Write Parkings lots
576   $btn=0;
577   $parken="" ;
578   $extpark ;
579   $parkcontext ;
580   $numberlots ;
581   $maxparkingslots ;
582
583   foreach ($parkings as $row) {
584     if ($row[0] == "parkingenabled") {
585       $parken = $row[1] ;
586     }
587     if ($row[0] == "parkext") {
588       $extpark = $row[1] ;
589     }
590     if ($row[0] == "parkingcontext") {
591       $parkcontext = $row[1] ;
592     }
593     if ($row[0] == "numslots") {
594       $numberlots = $row[1] ;
595     }
596   }
597   if ($parken == "s") {
598     for ($i = 1 ; $i <= $numberlots ; $i++ ) {
599       $btn=get_next_btn($parkingpos,$btn);
600       if ($btn == 0) {last;}
601       $parknum = $extpark + $i ;
602       $icon='1';
603       fwrite($fhandle, "[PARK$parknum]\nPosition=$btn\nLabel=\"Parked ($parknum)\"\nExtension=$parknum\nContext=$parkcontext\nIcon=$icon\nPanel_Context=$panelcontext\n");
604     }
605   }
606
607   ## End of chagnes
608   ### Write conferences (meetme)
609
610   $btn=0;
611   if ($exten_low != 0 && $exten_high != 0) {  #display only allowed range of extensions for panel_contexts
612     $confrange = array();
613     foreach ($conferences as $value) {
614       if (!is_numeric($value)) {array_push($confrange,$value);}
615       if (($value >= $exten_low) && ($value <= $exten_high))  {array_push($confrange,$value);}
616     }
617   } else {
618     $confrange = $conferences;
619   }
620   foreach ($confrange as $row) {
621     $btn=get_next_btn($confepos,$btn);
622     if ($btn == 0) {last;}
623     $confenum=$row[0];
624     $confedesc=$row[1];
625     $icon='6';
626     fwrite($fhandle, "[$confenum]\nPosition=$btn\nLabel=\"$confedesc\"\nExtension=$confenum\nContext=from-internal\nIcon=$icon\nPanel_Context=$panelcontext\n");
627   }
628
629   ### Write Queues
630
631   $btn=0;
632   if ($exten_low != 0 && $exten_high != 0) {  #display only allowed range of extensions for panel_contexts
633     $queuerange = array();
634     foreach ($queues as $value) {
635       if (!is_numeric($value)) {array_push($queuerange,$value);}
636       if (($value >= $exten_low) && ($value <= $exten_high))  {array_push($queuerange,$value);}
637     }
638   } else {
639     $queuerange = $queues;
640   }
641   foreach ($queuerange as $row) {
642     $btn=get_next_btn($queuepos,$btn);
643     if ($btn == 0) {last;}
644     $queuename=$row[0];
645     $queuedesc=$row[1];
646     $icon='5';
647     fwrite($fhandle, "[QUEUE/$queuename]\nPosition=$btn\nLabel=\"$queuedesc\"\nExtension=-1\nContext=from-internal\nIcon=$icon\nPanel_Context=$panelcontext\n");
648   }
649
650   ### Write rectangles
651
652   foreach ($rectangles as $rect) {
653     $comment = $rect[0];
654     $color1 = $rect[4];
655     $color2 = $rect[5];
656     $start = $rect[2];
657     $stop = $rect[3];
658
659     $xposition = $buttonsoriginx + $buttonsizex * floor(($start-1)/$numbuttonsy);
660     $yposition = $buttonsoriginy + $buttonsizey * (($start-1)%$numbuttonsy);
661     $xsize = $buttonsizex * (1 + floor(($stop-1)/$numbuttonsy) - floor(($start-1)/$numbuttonsy));
662     $ysize = $buttonsizey * (1 + (($stop-1)%$numbuttonsy) - (($start-1)%$numbuttonsy));
663
664     if (($xsize <= 0) || ($ysize <= 0)) {next;}
665
666     $xposition += $rectmarginx;
667     $yposition += $rectmarginy;
668     $xsize -= 2 * $rectmarginx;
669     $ysize -= 2 * $rectmarginy;
670
671     fwrite($fhandle, "\n; $comment\n[rectangle]\nx=$xposition\ny=$yposition\nwidth=$xsize\nheight=$ysize\nline_width=0\nline_color=$color1\nfade_color1=$color1\nfade_color2=$color2\nrnd_border=2\nalpha=20\nlayer=bottom\n");
672   }
673
674   ### Write legends
675
676   foreach ($rectangles as $legend) {
677     $text = $legend[1];
678     $start = $legend[2];
679     $stop = $legend[3];
680
681     $xposition = $buttonsoriginx + $buttonsizex * floor(($start-1)/$numbuttonsy);
682     $yposition = $buttonsoriginy + $buttonsizey * (($start-1)%$numbuttonsy);
683     $xsize = $buttonsizex * (1 + floor(($stop-1)/$numbuttonsy) - floor(($start-1)/$numbuttonsy));
684     $ysize = $buttonsizey * (1 + (($stop-1)%$numbuttonsy) - (($start-1)%$numbuttonsy));
685
686     if (($xsize <= 0) || ($ysize <= 0)) {next;}
687
688     $xposition += $legendoffsetx;
689     $yposition += $legendoffsety;
690
691     fwrite($fhandle, "\n[LEGEND]\nx=$xposition\ny=$yposition\ntext=$text\nfont_size=18\nfont_family=Arial\nuse_embed_fonts=1\n");
692   }
693
694 }
695
696 function get_next_btn($data,$last) {
697   $rangelist=explode(",",$data);
698   foreach ($rangelist as $range) {
699     $rangeval=explode("-",$range,2);
700     if ($last < $rangeval[0]) {return $rangeval[0] ;}
701     if (isset($rangeval[1]) && ($last < $rangeval[1])) {return $last+1;}
702     #Need to try another range def...
703   }
704   #If we get here, we ran out of positions :(
705   return 0; #?????
706 }
707 #this sub checks for the existance of a table
708 function table_exists($db,$table) {
709          $result = mysql_query("SHOW TABLES LIKE '" . $table . "'");
710          if(mysql_fetch_row($result) === false) {return(false);}
711          return(true);
712          }
713
714 function get_styleinfo($id,$layoutinfo) {
715 // do not use globals - instead pass layout info into function explicitly
716 //  global $rectangles;
717 //  global $numbuttonsx;
718 //  global $numbuttonsy;
719 $rectangles = $layoutinfo['rectangles'];
720 $numbuttonsx = $layoutinfo['numbuttonsx'];
721 $numbuttonsy = $layoutinfo['numbuttonsy'];
722
723
724   foreach ($rectangles as $rect) {
725     if ($id == $rect[0]) {
726
727       $start = $rect[2];
728       $stop = $rect[3];
729
730       $xposition = floor(($start-1)/$numbuttonsy);
731       $yposition = (($start-1)%$numbuttonsy);
732       $xsize = 1 + floor(($stop-1)/$numbuttonsy) - floor(($start-1)/$numbuttonsy);
733       $ysize = 1 + (($stop-1)%$numbuttonsy) - (($start-1)%$numbuttonsy);
734
735       if (($xsize <= 0) || ($ysize <= 0)) {print "Warning: rectange '$id' has negative area\n"; last;}
736       $styleinfo = "";
737       if ($ysize > 2) {
738         $styleinfo .= ($start + 1) . "-" . ($start + $ysize - 1) . ",";
739       }
740       elseif ($ysize == 2) {
741         $styleinfo .= ($start + 1) . ",";
742       }
743
744       for ($i = 1 ; $i < $xsize ; $i++ ) {
745         if ($ysize > 1) {
746           $styleinfo .= (($i + $xposition) * $numbuttonsy + $yposition + 1) . "-" . (($i + $xposition) * $numbuttonsy + $yposition + $ysize) . ",";
747         }
748         else {
749           $styleinfo .= (($i + $xposition) * $numbuttonsy + $yposition + 1) . ",";
750         }
751       }
752       $retval = $styleinfo;
753       last;
754     }
755   }
756   return $retval;
757 }
758 ?>