Code

Made asterisk server selectable in phonereports.
[gosa.git] / gosa-plugins / gofon / gofon / fonreports / class_fonreport.inc
1 <?php
3 class fonreport extends plugin
4 {
5   /* Definitions */
6   var $plHeadline= "Phone Reports";
7   var $plDescription= "This does something";
8   var $plIcon       = "plugins/gofon/images/phonereport.png";
10   /* For internal use */
11   var $start                              = 0;
12   var $search_for                 = "*";
13   var $search_base        = "";
14   var $fields                             = array("calldate", "src", "dst", "channel", "lastapp", "disposition", "duration");
15   var $year                                       = "";
16   var $month                              = "";
17   var $sort                                       = 0;
18   var $sort_direction   = "down";
19   var $report_list              = array();
20   var $userfilter                       = "";
21   var $ui                                           = NULL;
22   var $range                              = 20;
23   var $EntryPerPage   = 20;
25   var $selected_server = "";
27   /* attribute list for save action */
28   var $attributes_SO  = array("start","search_for","search_base","range","month","sort_direction","sort","year");
29   var $objectclasses  = array();
30   var $view_logged = FALSE;
31   
32   /* Construct class */
33   function fonreport (&$config, $ui)
34   {
35     /* Include config object */
36     $this->config                       = $config;
37     $this->ui                             = $ui;
38     $this->search_base= get_base_from_people($ui->dn);
39   
40     $this->month      = date("m");
41     $this->year       = date("Y");
43     /* Use filter settings if we have already searched */
44     if (!session::is_set("fonfilter")){
45       $fonfilter = array();
46       foreach($this->attributes_SO as $name){
47         $fonfilter[$name]=$this->$name;
48       }
49       session::set("fonfilter", $fonfilter);
50     }else{
51       $fonfilter = session::get("fonfilter");
52       foreach($this->attributes_SO as $name){
53         $this->$name = $fonfilter[$name];
54       }
55     }
56   }
59   /* Save ui interactions and store results in session, 
60       to remember settings */
61   function save_object()
62   {
63     $fonfilter= session::get("fonfilter");
64     if(isset($_POST['EntryPerPage'])){
65       $this->range = $_POST['EntryPerPage'];
66     }
67     if (isset($_GET['start'])){
68       $this->start= (int)$_GET['start'];
69     }
70     foreach( array("year", "month", "search_for", "search_base","selected_server") as $type){
71       if (isset($_POST[$type])){
72         $this->$type= $_POST[$type];
73       }
74     }
75     
76     /* Adapt sorting */
77     if (isset($_GET['sort'])){
78       if ($this->sort == (int)$_GET['sort']){
79         if ($this->sort_direction == "down"){
80           $this->sort_direction= "up";
81         } else {
82           $this->sort_direction= "down";
83         }
84       }
85       $this->sort= (int)$_GET['sort'];
86       if ($this->sort < 0 || $this->sort > 6){
87         $this->sort= 0;
88       }
89     }
91     /* remove unwanted tags */
92     $this->search_for = stripslashes(preg_replace("/[^0-9a-z\*\+ \-]/i","",$this->search_for));
93   
94     foreach($this->attributes_SO as $name){
95       $fonfilter[$name] = $this->$name;
96     }
97     session::set("fonfilter", $fonfilter);
98   }
101   /* Search & display results */
102   function execute()
103   {
104     /* Call parent execute */
105     plugin::execute();
107     /* GVet template engine */
108     $smarty= get_smarty();
110     /* Log view */
111     if(!$this->view_logged){
112       $this->view_logged = TRUE;
113       new log("view","fonreport/".get_class($this),$this->dn);
114     }
116     /*****************
117       Variable Init
118      *****************/
120     $fields_str = "";
122     $months= array();
123     for($i = 1 ; $i <= 12 ; $i ++ ){
124       $months[$i] = _(date("F",gmmktime(0,0,0,$i)));
125     }
127     /* Prepare template */
128     $current= date("Y");
129     $years= array();
130     for ($y= $current - 5; $y<=$current; $y++){
131       $years[$y]= $y;
132     }
134     /*****************
135       Smarty 
136      *****************/
137     $bases      = array();
138     $cat_bases  = $this->ui->get_module_departments("fonreport");
139     foreach($this->config->idepartments as $dn => $name){
140       if(in_array_ics($dn,$cat_bases)){
141         $bases[$dn] = $name;
142       }
143     }
145     if(!isset($bases[$this->search_base])){
146       $this->search_base = key($bases);
147     }
149     $smarty->assign("plug",           "?plug=".validate($_GET['plug']));
150     $smarty->assign("launchimage",    get_template_path('images/launch.png'));
151     $smarty->assign("search_image",   get_template_path('images/lists/search.png'));
152     $smarty->assign("search_for",     $this->search_for);
153     $smarty->assign("bases",          $bases);
154     $smarty->assign("base_select",    $this->search_base);
155     $smarty->assign("months",         $months);
156     $smarty->assign("month_select",   $this->month);
157     $smarty->assign("years",          $years);
158     $smarty->assign("year_select",    $this->year);
159     $smarty->assign("search_result",  "");
162     /*****************
163       Check Database , Table , Connection 
164      *****************/
166     // Collect servers and allow to select the server in the ui.
167     $servers = array();
168     foreach($this->config->data['SERVERS']['FON'] as $key => $server){
169       $servers[$server['SERVER']] = $server['SERVER'];
170     }
171     $smarty->assign("servers",  $servers);
172     $smarty->assign("selected_server",  $this->selected_server);
174     /* Connecting, selecting database */
175     if (!isset($this->config->data['SERVERS']['FON'][0])){
176       msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
177       return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
178     }elseif(!is_callable("mysql_connect")){
179       msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
180       return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
181     }else{
183       // Get CFG for the selected server, if empty use first.
184       if($this->selected_server == ""){
185         $cfg= $this->config->data['SERVERS']['FON'][0];
186       }else{
187         foreach($this->config->data['SERVERS']['FON'] as $server){
188           if($server['SERVER'] == $this->selected_server){
189             $cfg = $server;
190           }
191         }
192       }
194       $link = @mysql_pconnect($cfg['SERVER'], $cfg['LOGIN'], $cfg['PASSWORD']);
195       if ($link === FALSE){
196         msg_dialog::display(_("Error"), msgPool::dbconnect(_("GOfon"),@mysql_error(),$cfg['SERVER']),ERROR_DIALOG);
197         return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
198       }
199       if (! @mysql_select_db("gophone")){
200         msg_dialog::display(_("Error"), msgPool::dbselect(_("GOfon"),@mysql_error(),$cfg['DB']),ERROR_DIALOG);
201         return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
202       }
203     }
206     /*****************
207       Get Query String && Search
208      *****************/
210     $query  = $this->CreateQuerySyntax();
211     $link   = @mysql_pconnect($cfg['SERVER'], $cfg['LOGIN'], $cfg['PASSWORD']);
213     @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
215     $result = @mysql_query($query);
216     if ($result === false){
217       msg_dialog::display(_("Error"), msgPool::dbquery(_("GOfon"),@mysql_error(),$cfg['SERVER']),ERROR_DIALOG);
218       return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
219     }
221     /*****************
222       Fetch results 
223      *****************/
224   
225     $report_list= array();
226     
227     /* Restricted attributes will not be displayed, this will be displayed instead */
228     $no_acl = "<img class='center' src='images/lists/locked.png'
229       title='".msgPool::permView()."' alt='"._("Insufficient permissions")."'>";
231     $no_acl = "&nbsp;";
233     while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
235       foreach($line as $attr => $value){
237         if($attr == "duration") continue;
238   
239         $acl = $this->ui->get_permissions($this->search_base,"fonreport/fonreport",$attr);
240         if(!preg_match("/r/",$acl)){
241           $line[$attr] = $no_acl;
242         }
243       }
245       if($this->ui->get_permissions($this->search_base,"fonreport/fonreport","calldate")){
246         $hour=  substr($line["calldate"], 11, 2);
247         $minute=substr($line["calldate"], 14, 2);
248         $format= _("Y-M-D");
249         $date= preg_replace("/Y/", substr($line["calldate"], 0, 4), $format);
250         $date= preg_replace("/M/", substr($line["calldate"], 5, 2), $date);
251         $date= preg_replace("/D/", substr($line["calldate"], 8, 2), $date);
252         $date_str = $date." ".$hour.":".$minute;
253       }else{
254         $date_str = $no_acl;
255       }
256   
257       $append_str = "";
258       $append_str .=    "<td>".$date_str."</td>";
260       foreach(array("src","dst","channel","lastapp","disposition") as $atr){
261         if(isset($line[$atr])){
262           $append_str .=        "<td>".$line[$atr]."</td>";
263         }
264       }
266       if($this->ui->get_permissions($this->search_base,"fonreport/fonreport","duration")){
267         $append_str .=  "<td>".$this->gen_duration($line["duration"])."</td>";
268       }else{
269         $append_str .=  "<td>".$no_acl."</td>";
270       }
271       $report_list[] = $append_str;
272     }
274     $this->report_list= $report_list;
275     @mysql_close($link);
278     /*****************
279       Create list of results  
280      *****************/
282     /* Generate output */
283     $mod      = 0;
284     $output   = "";
285     if(count($this->report_list) < $this->start){
286       $this->start = 0;
287     }
288     foreach($this->report_list as $val){
289       if ($mod < $this->start) {
290         $mod++;
291         continue;
292       }
293       if ($mod >= ($this->start + $this->range)){
294         $mod++;
295         break;
296       }
297       if ( ($mod++) & 1){
298         $col= "background-color: #ECECEC;";
299       } else {
300         $col= "background-color: #F5F5F5;";
301       }
302       $output.= "<tr style=\"height:22px; $col\">$val</tr>";
303     }
305     /*****************
306       Tell smarty what we have found  
307      *****************/
309     if ($output != ""){
310       $smarty->assign("search_result", $output);
311       $smarty->assign("range_selector", range_selector(count($this->report_list), $this->start,$this->range,"EntryPerPage"));
312     } else {
313       $smarty->assign("search_result", "");
314     }
316     /* Show main page */
317     for($i= 0; $i<7; $i++){
318       $smarty->assign("mode$i", "");
319     }
320     $smarty->assign("mode".$this->sort, "<img alt=\"\" src=\"images/sort_".$this->sort_direction.".png\" border=0 align=middle>");
322     return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
323   }
325   
326   /* Create duration string   12'11" */
327   function gen_duration($seconds)
328   {
329     if ($seconds / 60 > 1){
330       $minutes= (int)($seconds / 60);
331       $seconds= $seconds % 60;
332       return ("$minutes&rsquo;$seconds&rdquo;");
333     }
334     return ("$seconds&rdquo;");
335   }
338   /* Create WHERE part for our mysql serach */
339   function GetUidMatchingFilter()
340   {
341     $ldap       = $this->config->get_ldap_link();
342     $ldap->cd     ($this->search_base);
343     $s          = $this->search_for;
345     $s          = preg_replace("/\%/","",$s);  
346     $s2         = preg_replace("/\*/","%",$s);  
348     $filter = "(&(objectClass=gosaAccount)(!(objectClass=gosaUserTemplate))".
349         "(|(uid=$s)(l=$s)(homePhone=$s)(telephoneNumber=$s)(facsimileTelephoneNumber=$s)(mobile=$s)".
350         "(pager=$s)(cn=$s)(givenName=$s)(sn=$s)(personalTitle=$s)(title=$s)))";
352     $attrs  = array("uid");
353     $res    = get_sub_list($filter,"fonreport/fonreport",get_people_ou(),$this->search_base,$attrs);
354     
355     $str = " AND (";
356     $fields = array("dstchannel","channel");
357     if(count($res)){
358       foreach($res as $attrs){
359         $uid =  $attrs["uid"][0];
360         foreach($fields as $name){
361           $str .= $name." like '%".$uid."%' OR ";
362         }
363       }
364     }
365     $str .= " channel     like '%".$s."%' OR  
366               dstchannel  like '%".$s."%' OR  
367               dst         like '".$s2."' OR 
368               src         like '".$s2."' OR 
369               lastapp     like '".$s2."')"; 
370     return($str);
371   }
374   /* Create query string */
375   function CreateQuerySyntax()
376   {
377     /* Get extended search filter which contain uids and so on */
378     $uidstring = $this->GetUidMatchingFilter();
380     /* Create string with all fields seperated by ,*/
381     $fields_str ="";
382     foreach($this->fields as $field){
383       if($field == "calldate") {
384         continue;       
385       }
386       $fields_str .= $field.", ";
387     }
388     $fields_str = preg_replace("/, $/","",$fields_str);
390     /* Create Sort tag */
391     if ($this->sort_direction == "down"){
392       $desc= "DESC";
393     } else {
394       $desc= "ASC";
395     }
396     /* Create times */
397     $start= date ("YmdHis", mktime(0,0,0,$this->month,1,$this->year));
398     $end=   date ("YmdHis", mktime(23,59,59,($this->month +1),0,$this->year));
399     $query = "SELECT ".$fields_str.",calldate FROM cdr ".
400       "WHERE   
401       calldate <= $end 
402       AND 
403       calldate >= $start 
404       ". $uidstring." 
405       ORDER BY ".$this->fields[$this->sort]." $desc;";
406     return($query);
407   }
410   /* Return plugin informations for acl handling 
411      #FIXME You can only read attributes within this report plugin */
412   static function plInfo()
413   {
414     return (array(
415         "plShortName"   => _("Phone reports"),
416         "plDescription" => _("Phone reports")."&nbsp;<i>"._("All entries are readonly")."</i>",
417         "plSelfModify"  => TRUE,
418         "plDepends"     => array(),
419         "plPriority"    => 0,
420         "plSection"     => array("administration"),
421         "plCategory"    => array(
422           "fonreport" => array(
423             "description" => _("Phone reports"),
424             "objectClass" => "None")),
426   
427         "plProvidedAcls" => array(
428           "calldate"      =>_("Date"), 
429           "src"           =>_("Source"), 
430           "dst"           =>_("Destination"), 
431           "channel"       =>_("Channel"), 
432           "lastapp"       =>_("Application called"),
433           "disposition"   =>_("Disposition"), 
434           "duration"      =>_("Duration"))
435         ));
436   }
438 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
439 ?>