Ticket #3291: retrieve_op_conf_from_mysql.php

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