Code

Fixed uid search
[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= get_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     // Use the configured global timezone settings 
108     timezone::get_default_timezone();
110     /* GVet template engine */
111     $smarty= get_smarty();
113     /* Log view */
114     if(!$this->view_logged){
115       $this->view_logged = TRUE;
116       new log("view","fonreport/".get_class($this),$this->dn);
117     }
119     /*****************
120       Variable Init
121      *****************/
123     $fields_str = "";
125     $months= array();
126     for($i = 1 ; $i <= 12 ; $i ++ ){
127       $months[$i] = _(date("F",gmmktime(0,0,0,$i)));
128     }
130     /* Prepare template */
131     $current= date("Y");
132     $years= array();
133     for ($y= $current - 5; $y<=$current; $y++){
134       $years[$y]= $y;
135     }
137     /*****************
138       Smarty 
139      *****************/
140     $bases      = array();
141     $cat_bases  = $this->ui->get_module_departments("fonreport");
142     foreach($this->config->idepartments as $dn => $name){
143       if(in_array_ics($dn,$cat_bases)){
144         $bases[$dn] = $name;
145       }
146     }
148     if(!isset($bases[$this->search_base])){
149       $this->search_base = key($bases);
150     }
152     $smarty->assign("plug",           "?plug=".validate($_GET['plug']));
153     $smarty->assign("launchimage",    get_template_path('images/launch.png'));
154     $smarty->assign("search_image",   get_template_path('images/lists/search.png'));
155     $smarty->assign("search_for",     htmlentities($this->search_for));
156     $smarty->assign("bases",          $bases);
157     $smarty->assign("base_select",    $this->search_base);
158     $smarty->assign("months",         $months);
159     $smarty->assign("month_select",   $this->month);
160     $smarty->assign("years",          $years);
161     $smarty->assign("year_select",    $this->year);
162     $smarty->assign("search_result",  "");
165     /*****************
166       Check Database , Table , Connection 
167      *****************/
169     // Collect servers and allow to select the server in the ui.
170     $servers = array();
171     foreach($this->config->data['SERVERS']['FON'] as $key => $server){
172       $servers[$server['SERVER']] = $server['SERVER'];
173     }
174     $smarty->assign("servers",  $servers);
175     $smarty->assign("selected_server",  $this->selected_server);
177     /* Connecting, selecting database */
178     if (!isset($this->config->data['SERVERS']['FON'][0])){
179       msg_dialog::display(_("Configuration error"), msgPool::noserver(_("GOfon")), WARNING_DIALOG);
180       return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
181     }elseif(!is_callable("mysql_connect")){
182       msg_dialog::display(_("Configuration error"), msgPool::missingext("php-mysql"), WARNING_DIALOG);
183       return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
184     }else{
186       // Get CFG for the selected server, if empty use first.
187       if($this->selected_server == ""){
188         $cfg= $this->config->data['SERVERS']['FON'][0];
189       }else{
190         foreach($this->config->data['SERVERS']['FON'] as $server){
191           if($server['SERVER'] == $this->selected_server){
192             $cfg = $server;
193           }
194         }
195       }
197       $link = @mysql_pconnect($cfg['SERVER'], $cfg['LOGIN'], $cfg['PASSWORD']);
198       if ($link === FALSE){
199         msg_dialog::display(_("Error"), msgPool::dbconnect(_("GOfon"),@mysql_error(),$cfg['SERVER']),ERROR_DIALOG);
200         return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
201       }
202       if (! @mysql_select_db("gophone")){
203         msg_dialog::display(_("Error"), msgPool::dbselect(_("GOfon"),@mysql_error(),$cfg['DB']),ERROR_DIALOG);
204         return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
205       }
206     }
209     /*****************
210       Get Query String && Search
211      *****************/
213     $link   = @mysql_pconnect($cfg['SERVER'], $cfg['LOGIN'], $cfg['PASSWORD']);
215     @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
217     // Get all matching entries to be able to fill the pager
218     $query  = $this->CreateQuerySyntax($limit = FALSE);
219     $count = @mysql_query($query);
220     if ($count === false){
221       msg_dialog::display(_("Error"), msgPool::dbquery(_("GOfon"),@mysql_error(),$cfg['SERVER']),ERROR_DIALOG);
222       return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
223     }
224     $tmp = mysql_fetch_array($count, MYSQL_ASSOC);
225     $res_count = $tmp['count']; 
226     if($res_count < $this->start){
227       $this->start = 0;
228     }
230     // Get entries for the selected range only.
231     $query  = $this->CreateQuerySyntax($limit = TRUE);
232     $result = @mysql_query($query);
233     if ($result === false){
234       msg_dialog::display(_("Error"), msgPool::dbquery(_("GOfon"),@mysql_error(),$cfg['SERVER']),ERROR_DIALOG);
235       return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
236     }
238     /*****************
239       Fetch results 
240      *****************/
241   
242     $report_list= array();
243     
244     /* Restricted attributes will not be displayed, this will be displayed instead */
245     $no_acl = "<img class='center' src='images/lists/locked.png'
246       title='".msgPool::permView()."' alt='"._("Insufficient permissions")."'>";
248     $no_acl = "&nbsp;";
250     while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
252       // Check attribute permissions
253       foreach($line as $attr => $value){
254         if($attr == "duration") continue;
255         $acl = $this->ui->get_permissions($this->search_base,"fonreport/fonreport",$attr);
256         if(!preg_match("/r/",$acl)){
257           $line[$attr] = $no_acl;
258         }
259       }
261       // Check date permissions
262       if($this->ui->get_permissions($this->search_base,"fonreport/fonreport","calldate")){
263         $hour=  substr($line["calldate"], 11, 2);
264         $minute=substr($line["calldate"], 14, 2);
265         $format= _("Y-M-D");
266         $date= preg_replace("/Y/", substr($line["calldate"], 0, 4), $format);
267         $date= preg_replace("/M/", substr($line["calldate"], 5, 2), $date);
268         $date= preg_replace("/D/", substr($line["calldate"], 8, 2), $date);
269         $date_str = $date." ".$hour.":".$minute;
270       }else{
271         $date_str = $no_acl;
272       }
273   
274       $append_str =     "<td class='list1'>".$date_str."</td>";
275       foreach(array("src","dst","channel","lastapp","disposition") as $atr){
276         if(isset($line[$atr])){
277           $append_str .=        "<td class='list1'>".$line[$atr]."</td>";
278         }
279       }
280       if($this->ui->get_permissions($this->search_base,"fonreport/fonreport","duration")){
281         $append_str .=  "<td class='list1'>".$this->gen_duration($line["duration"])."</td>";
282       }else{
283         $append_str .=  "<td class='list1'>".$no_acl."</td>";
284       }
285       $report_list[] = $append_str;
286     }
288     $this->report_list= $report_list;
289     @mysql_close($link);
292     /*****************
293       Create list of results  
294      *****************/
296     /* Generate output */
297     $mod      = 0;
298     $output   = "";
299     foreach($this->report_list as $val){
300       $output.= "<tr>$val</tr>";
301     }
303     /*****************
304       Tell smarty what we have found  
305      *****************/
307     if ($output != ""){
308       $smarty->assign("search_result", $output);
309       $smarty->assign("range_selector", range_selector($res_count, $this->start,$this->range,"EntryPerPage"));
310     } else {
311       $smarty->assign("search_result", "");
312     }
314     /* Show main page */
315     for($i= 0; $i<7; $i++){
316       $smarty->assign("mode$i", "");
317     }
318     $smarty->assign("mode".$this->sort, image("images/lists/sort-".$this->sort_direction.".png"));
320     return($smarty->fetch(get_template_path('contents.tpl', TRUE)));
321   }
323   
324   /* Create duration string   12'11" */
325   function gen_duration($seconds)
326   {
327     if ($seconds / 60 > 1){
328       $minutes= (int)($seconds / 60);
329       $seconds= $seconds % 60;
330       return ("$minutes&rsquo;$seconds&rdquo;");
331     }
332     return ("$seconds&rdquo;");
333   }
336   /* Create WHERE part for our mysql serach */
337   function GetUidMatchingFilter()
338   {
339     $ldap= $this->config->get_ldap_link();
340     $ldap->cd($this->search_base);
341     $s = $this->search_for;
343     $s = preg_replace("/\%/","",$s);  
344     $s2 = preg_replace("/\*/","%",$s);  
346     $filter = "(&(objectClass=gosaAccount)(!(objectClass=gosaUserTemplate))".
347         "(|(uid=$s)(l=$s)(homePhone=$s)(telephoneNumber=$s)(facsimileTelephoneNumber=$s)(mobile=$s)".
348         "(pager=$s)(cn=$s)(givenName=$s)(sn=$s)(personalTitle=$s)(title=$s)))";
350     $attrs  = array("uid");
351     $res    = get_list($filter,"fonreport/fonreport",$this->search_base,$attrs);
352     
353     $str = " AND (";
354     $fields = array("dstchannel","channel");
355     if(count($res)){
356       foreach($res as $attrs){
357         $uid =  $attrs["uid"][0];
358         foreach($fields as $name){
359           $str .= $name." like '%".$uid."%' OR ";
360         }
361       }
362     }
363     $str .= " channel     like '%".$s."%' OR  
364               dstchannel  like '%".$s."%' OR  
365               dst         like '".$s2."' OR 
366               src         like '".$s2."' OR 
367               lastapp     like '".$s2."')"; 
368     return($str);
369   }
372   /* Create query string */
373   function CreateQuerySyntax($limit = TRUE)
374   {
375     /* Get extended search filter which contain uids and so on */
376     $uidstring = $this->GetUidMatchingFilter();
378     /* Create string with all fields seperated by ,*/
379     $fields_str ="";
380     foreach($this->fields as $field){
381       if($field == "calldate") {
382         continue;       
383       }
384       $fields_str .= $field.", ";
385     }
386     $fields_str = preg_replace("/, $/","",$fields_str);
388     /* Create Sort tag */
389     if ($this->sort_direction == "down"){
390       $desc= "DESC";
391     } else {
392       $desc= "ASC";
393     }
394     /* Create times */
395     $start= date ("YmdHis", mktime(0,0,0,$this->month,1,$this->year));
396     $end=   date ("YmdHis", mktime(23,59,59,($this->month +1),0,$this->year));
398     if(!$limit){
399       $fieldset = "count(dst) as `count`";
400     }else{
402       /* Create string with all fields seperated by ,*/
403       $fields_str ="";
404       foreach($this->fields as $field){
405         if($field == "calldate") continue;
406         $fields_str .= $field.", ";
407       }
408       $fields_str = preg_replace("/, $/","",$fields_str);
409       $fieldset = $fields_str.",calldate"; 
410     }
412     $query = "SELECT {$fieldset} FROM cdr ".
413       "WHERE   
414       calldate <= $end 
415       AND 
416       calldate >= $start 
417       ". $uidstring." 
418       ORDER BY ".$this->fields[$this->sort]." $desc";
419    
420     // Set limitations  
421     if($limit){
422       $query.=" LIMIT ".($this->start).", ".$this->range;
423     }
424     $query.=";";
425     return($query);
426   }
429   /* Return plugin informations for acl handling 
430      #FIXME You can only read attributes within this report plugin */
431   static function plInfo()
432   {
433     return (array(
434         "plShortName"   => _("Phone reports"),
435         "plDescription" => _("Phone reports")."&nbsp;<i>"._("All entries are readonly")."</i>",
436         "plSelfModify"  => TRUE,
437         "plDepends"     => array(),
438         "plPriority"    => 0,
439         "plSection"     => array("administration"),
440         "plCategory"    => array(
441           "fonreport" => array(
442             "description" => _("Phone reports"),
443             "objectClass" => "None")),
445   
446         "plProvidedAcls" => array(
447           "calldate"      =>_("Date"), 
448           "src"           =>_("Source"), 
449           "dst"           =>_("Destination"), 
450           "channel"       =>_("Channel"), 
451           "lastapp"       =>_("Application called"),
452           "disposition"   =>_("Disposition"), 
453           "duration"      =>_("Duration"))
454         ));
455   }
457 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
458 ?>