223. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 5/25/2018 9:22:54 AM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

223.1 Files compared

# Location File Last Modified
1 C:\AraxisMergeCompare\Pri_un\ZIP\DSM-cif\Webmail\application\controllers Adminpanel.php Tue May 22 12:03:50 2018 UTC
2 C:\AraxisMergeCompare\Pri_re\ZIP\DSM-cif\Webmail\application\controllers Adminpanel.php Tue May 22 22:14:40 2018 UTC

223.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 2 2308
Changed 1 2
Inserted 0 0
Removed 0 0

223.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

223.4 Active regular expressions

No regular expressions were active.

223.5 Comparison detail

  1   <?php if (  ! defined ('BASEPATH ')) exit(' No direct  script acc ess allowe d');
  2  
  3   /**
  4   * @package  direct-pr oject-inno vation-ini tiative
  5   * @subpack age contro llers
  6   *//** */
  7  
  8   require_on ce APPPATH .'controll ers/restri cted_contr oller.php' ;
  9  
  10  
  11   /**
  12   * @package  direct-pr oject-inno vation-ini tiative
  13   * @subpack age contro llers
  14   */
  15   class Admi nPanel ext ends Restr icted_cont roller {
  16  
  17           fu nction __c onstruct()  {
  18                    pare nt::__cons truct();
  19                    $thi s->verify_ permission ("adminpan el");
  20           }
  21  
  22  
  23           pu blic funct ion index( )
  24           {
  25                    if($ this->has_ permission ("reports" )){
  26                             redire ct("adminp anel/repor ts");
  27                    }
  28                    else  if($this- >has_permi ssion("log s")){
  29                             redire ct("adminp anel/logs" );
  30                    }
  31                    else  if($this- >has_permi ssion("man age_users" )){
  32                             redire ct("adminp anel/manag e_users");
  33                    }
  34                    else  if($this- >has_permi ssion("man age_groups ")){
  35                             redire ct("adminp anel/manag e_groups") ;
  36                    }
  37                    else  if($this- >has_permi ssion("con tact_list" )){
  38                             redire ct("adminp anel/globa l_contacts ");
  39                    }
  40                    else  if($this- >has_permi ssion("dis tribution_ lists")){
  41                             redire ct("adminp anel/distr ibution_li sts");
  42                    }
  43                    else  if($this- >has_permi ssion("the mes")){
  44                             redire ct("adminp anel/theme s");
  45                    }
  46                    else {
  47                             redire ct("auth") ;
  48                    }
  49           }
  50  
  51  
  52           /* load log v iew */
  53           fu nction log s($action  = NULL, $v alue = NUL L) {
  54                    $thi s->verify_ permission ("logs");
  55                    if(i s_null($ac tion)) {
  56                             redire ct("adminp anel/logs/ logins");
  57                    }
  58                    else  {
  59                             $data  = $this->l og_view($a ction,$val ue);
  60                             $this- >load->vie w("adminpa nel/logs", $data);
  61                    }
  62           }
  63  
  64           /* This funct ion displa ys the exp ort form v iew, meant  for use w ith modal  window or  pop-up */
  65           pu blic funct ion export _form($log ) {
  66                    $thi s->load->v iew('admin panel/expo rt_form',a rray('log' =>$log));
  67           }
  68  
  69           /*  This func tion expor ts a log f or a given  time peri od to csv  format
  70            * /
  71           pu blic funct ion export ($log) {
  72                    $thi s->verify_ permission ("logs");
  73                    $thi s->load->l ibrary('lo cale');
  74                    $tim ezone_abbr ev = $this ->locale-> timezone_a bbr_from_n ame(date_d efault_tim ezone_get( ));
  75  
  76                    $sta rt_date =  $this->inp ut->post(" start_date ",TRUE);
  77                    $end _date = $t his->input ->post("en d_date",TR UE);
  78                    $sta rt_udate =  strtotime ($start_da te);
  79                    $end _udate = s trtotime($ end_date)  ? strtotim e($end_dat e) + 86400  : strtoti me($end_da te);
  80                    $thi s->load->m odel('webm ailmodel') ;
  81                    $log _query = $ this->webm ailmodel-> get_log_ex port($log, $start_uda te,$end_ud ate);
  82  
  83                    if($ log == "lo gins") {
  84                             $this- >verify_pe rmission(" logs_login s");
  85                             if($lo g_query) {
  86                    head er('Conten t-Type: ap plication/ download') ;
  87                                      header(" Content-Tr ansfer-Enc oding: bin ary");
  88                                      header(' Content-Di sposition:  attachmen t; filenam e="logins. csv"');
  89                                      echo "FO R OFFICIAL  USE ONLY\ n";
  90                                      echo "Lo g Date";
  91                                      if(isset ($timezone _abbrev))  { echo ' ( ' . $timez one_abbrev  . ')'; }
  92                                      echo ",U sername,IP  Address,L ogin Succe ss,Error M essage\n";
  93                                      for($i =  0; $i < $ log_query- >num_rows( ); $i++) {
  94                                               $row = $lo g_query->r ow_array($ i);
  95                                               foreach($r ow as $key  => $val)  { $row[$ke y] = str_r eplace("\" ","\"\"",$ val); }
  96                                               if($row["s uccess"])  { $success  = "Succes s"; } else  { $succes s = "Failu re"; }
  97                                               echo date( "m/d/y h:i :s A",$row ["login_ti me"]) . ", \"" . $row ["username "] . "\","  . $row["i p_address" ] . "," .  $success .  ",\"" . $ row["error _msg"] . " \"\n";
  98                                      }
  99                             }
  100                    }
  101                    else  if($log = = "sent_ma il") {
  102                             $this- >verify_pe rmission(" logs_sent_ mail");
  103                             if($lo g_query) {
  104                                      header(' Content-Ty pe: applic ation/down load');
  105                                      header(" Content-Tr ansfer-Enc oding: bin ary");
  106                    head er('Conten t-Disposit ion: attac hment; fil ename="sen t_mail.csv "');
  107                                      echo "FO R OFFICIAL  USE ONLY\ n";
  108                                      echo "Lo g Date";
  109                                      if(isset ($timezone _abbrev))  { echo ' ( ' . $timez one_abbrev  . ')'; }
  110                                      echo ",S ender,Reci pient(s),M essage Siz e (KB),Sen d Success\ n";
  111                                      for($i =  0; $i < $ log_query- >num_rows( ); $i++) {
  112                                               $row = $lo g_query->r ow_array($ i);
  113                                               if($row["s uccess"])  { $success  = "Succes s"; } else  { $succes s = "Failu re"; }
  114                                               echo date( "m/d/y h:i :s A",$row ["time"])  . ",\"" .  $this->san itize_expo rt($row["s ender"]) .  "\",\"" .  implode(" , ",$this- >sanitize_ export($th is->json-> decode($ro w["recipie nt"]))) .  "\"," . $r ow["size"]  . "," . $ success .  "\n";
  115                                      }
  116                             }
  117                    }
  118                    else  if($log = = "receive d_mail") {
  119                             $this- >verify_pe rmission(" logs_recei ved_mail") ;
  120                             if($lo g_query) {
  121                                      header(' Content-Ty pe: applic ation/down load');
  122                                      header(" Content-Tr ansfer-Enc oding: bin ary");
  123                    head er('Conten t-Disposit ion: attac hment; fil ename="rec eived_mail .csv"');
  124                                      echo "FO R OFFICIAL  USE ONLY\ n";
  125                                      echo "Lo g Date";
  126                                      if(isset ($timezone _abbrev))  { echo ' ( ' . $timez one_abbrev  . ')'; }
  127                                      echo ",S ender,Reci pient(s),M essage Siz e (KB),Rec eipt Succe ss\n";
  128                                      for($i =  0; $i < $ log_query- >num_rows( ); $i++) {
  129                                               $row = $lo g_query->r ow_array($ i);
  130                                               if($row["s uccess"])  { $success  = "Succes s"; } else  { $succes s = "Failu re"; }
  131                                               echo date( "m/d/y h:i :s A",$row ["time"])  . ",\"" .  $this->san itize_expo rt($row["s ender"]) .  "\",\"" .  implode(" , ",$this- >sanitize_ export($th is->json-> decode($ro w["recipie nt"]))) .  "\"," . $r ow["size"]  . "," . $ success .  "\n";
  132                                      }
  133                             }
  134                    }
  135                    else  if($log = = "edit")  {
  136                             $this- >verify_pe rmission(" logs_edit" );
  137                             if($lo g_query) {
  138                                      header(' Content-Ty pe: applic ation/down load');
  139                                      header(" Content-Tr ansfer-Enc oding: bin ary");
  140                    head er('Conten t-Disposit ion: attac hment; fil ename="edi t_log.csv" ');
  141                                      echo "FO R OFFICIAL  USE ONLY\ n";
  142                                      echo "Lo g Date";
  143                                      if(isset ($timezone _abbrev))  { echo ' ( ' . $timez one_abbrev  . ')'; }
  144                                      echo ",T arget,Acto r,Action\n ";
  145                                      for($i =  0; $i < $ log_query- >num_rows( ); $i++) {
  146                                               $row = $lo g_query->r ow_array($ i);
  147                                               $target_id _query = $ this->db-> query("SEL ECT user_n ame FROM u sers WHERE  user_id="  . $this-> db->escape ($row["tar get_user_i d"]));
  148                                               $actor_id_ query = $t his->db->q uery("SELE CT user_na me FROM us ers WHERE  user_id="  . $this->d b->escape( $row["acto r_user_id" ]));
  149                                               if($target _id_query  && $actor_ id_query)  {
  150                                                       $t arget_id_r ow = $targ et_id_quer y->row_arr ay();
  151                                                       $a ctor_id_ro w = $actor _id_query- >row_array ();
  152                                                       $t arget_name  = isset($ target_id_ row ["user _name"]) ?  $target_i d_row ["us er_name"]  : "Unknown  User";
  153                                                       $a ctor_name  = isset($a ctor_id_ro w ["user_n ame"]) ? $ actor_id_r ow ["user_ name"] : " Unknown Us er";
  154                                                       ec ho date("m /d/y h:i:s  A",$row[" edit_datet ime"]) . " ,\"" . $th is->saniti ze_export( $target_na me) . "\", \"" . $thi s->sanitiz e_export($ actor_name ) . "\","  . $this->s anitize_ex port($row[ "edit_acti on"]) . "\ n";
  155                                               }
  156                                      }
  157                             }
  158                    }
  159                    else  if($log = = "feedbac k") {
  160                             $this- >verify_pe rmission(" logs_feedb ack");
  161                             if($lo g_query) {
  162                                      header(' Content-Ty pe: applic ation/down load');
  163                                      header(" Content-Tr ansfer-Enc oding: bin ary");
  164                    head er('Conten t-Disposit ion: attac hment; fil ename="fee dback.csv" ');
  165                                      echo "FO R OFFICIAL  USE ONLY\ n";
  166                                      echo "Lo g Date";
  167                                      if(isset ($timezone _abbrev))  { echo ' ( ' . $timez one_abbrev  . ')'; }
  168                                      echo ",U sername,Fe edback Typ e,Feedback  Comments\ n";
  169                                      for($i =  0; $i < $ log_query- >num_rows( ); $i++) {
  170                                               $row = $lo g_query->r ow_array($ i);
  171                                               $actor_id_ query = $t his->db->q uery("SELE CT user_na me FROM us ers WHERE  user_id="  . $this->d b->escape( $row["user _id"]));
  172                                               if($actor_ id_query)  {
  173                                                       $a ctor_id_ro w = $actor _id_query- >row_array ();
  174                                                       $a ctor_name  = isset($a ctor_id_ro w["user_na me"]) ? $a ctor_id_ro w["user_na me"] : "Un known User ";
  175                                                       ec ho date("m /d/y h:i:s  A",$row[" feedback_d atetime"])  . ",\"" .  $this->sa nitize_exp ort($actor _name) . " \",\"" . $ this->sani tize_expor t($row["fe edback_typ e"]) . "\" ," . $this ->sanitize _export($r ow["feedba ck_comment s"]) . "\n ";
  176                                               }
  177                                      }
  178                             }
  179                    }
  180                    else  { show_40 4(); }
  181           }
  182           /*  This func tion loads  statistic s from the  database  into html  tables whi ch are the n converte d into
  183            *  chart vis ualization s by a jqu ery librar y
  184            * /
  185           pu blic funct ion chart( $chart = N ULL) {
  186                    $dat a["title"]  = PORTAL_ TITLE_PREF IX . "Admi n Panel";
  187                    if(i s_null($ch art)) { $c hart = "se nt_message s"; }
  188                    swit ch ($chart ) {
  189                             case " sent_messa ges":
  190                                               $this->ver ify_permis sion("repo rts_sent_m essages");
  191                                               //create t otal messa ges sent p er day cha rt
  192                                               $stmt = $t his->db->q uery("SELE CT time AS  date, COU NT(time) A S msg_coun t FROM mai l_log WHER E inbound_ outbound=0  AND time  BETWEEN (d atediff(ss , '1970010 1', GetUtc Date()) -  518400) AN D (datedif f(ss, '197 00101', Ge tUtcDate() )) GROUP B Y time");
  193                                               $i = 0;
  194                                               $chartdata  = array() ;
  195                                               $results =  array();
  196                                               foreach($s tmt->resul t_array()  as $row) {
  197                                                       $d ate = date ("m/d", $r ow['date'] );
  198                                                       $c ount = $ro w['msg_cou nt'];
  199                                                       if (array_key _exists($d ate,$resul ts)) { $re sults[$dat e] = $resu lts[$date]  + $count;  }
  200                                                       el se { $resu lts[$date]  = $count;  }
  201                                               }
  202                                               foreach($r esults as  $key => $r ow) {
  203                                                       $c hartdata[$ i]["date"]  = $key;
  204                                                       $c hartdata[$ i]["count" ] = $row;
  205                                                       $i ++;
  206                                               }
  207                                               //add date s with no  records to  chart
  208                                               $j = 0;
  209                                      for($i =  (date("U" ) - (86400 *6)); $i < = date("U" ); $i = $i  + 86400)  {
  210                                               if(isset($ chartdata[ $j]) && $c hartdata[$ j]["date"]  != date(" m/d",$i))  { array_sp lice($char tdata,$j,0 ,array(arr ay("date"  => date("m /d",$i), " count" =>  0))); }
  211                                               else if(!i sset($char tdata[$j]) ){ $chartd ata[$j]["d ate"] = da te("m/d",$ i); $chart data[$j][" count"] =  0; }
  212                                               $j++;
  213                                      }
  214                                      $data['c hart_title '] = 'Mess ages Sent  Daily Char t';
  215                                      $data["c hart"] = $ this->mark up_for_jqu ery_chart( "line","Me ssages Sen t Daily",$ chartdata,  "sent_dai ly_chart", "650px","3 25px");
  216                                      $data['h idden_char t'] = '<ta ble><capti on>Table r epresentin g data in  Messages S ent Daily  chart</cap tion><tr>< th>Date</t h><th>Mess ages Sent< /th></tr>' ;
  217                                      foreach( $chartdata  as $cdata ) {
  218                                               $data['hid den_chart' ] .= '<tr> <td>' . $c data['date '] . '</td ><td>' . $ cdata['cou nt'] . '</ td></tr>';
  219                                      }
  220                                      $data['h idden_char t'] .= '</ table>';
  221                                      break;
  222                             case " message_su ccess":
  223                                      $this->v erify_perm ission("re ports_mess age_succes s");
  224                                      //create  success v s fail sen t messages  chart
  225                                      $stmt =  $this->db- >query("SE LECT SUM(C ASE WHEN s uccess = 1  THEN 1 EL SE 0 END)  AS success , SUM(CASE  WHEN succ ess = 0 TH EN 1 ELSE  0 END) AS  fail FROM  mail_log W HERE inbou nd_outboun d=0");
  226                                      $chartda ta = array ();
  227                                      foreach( $stmt->res ult_array( ) as $row)  {
  228                                               $chartdata ["success" ]["label"]  = "Succee ded";
  229                                               $chartdata ["success" ]["val"] =  empty($ro w['success ']) ? 0 :  $row['succ ess'];
  230                                               $chartdata ["fail"][" label"] =  "Failed";
  231                                               $chartdata ["fail"][" val"] = em pty($row[' fail']) ?  0 : $row[' fail'];
  232                                      }
  233                                      $data['c hart_title '] = 'Send  Success/F ailure Cha rt';
  234                                      $data["c hart"] = $ this->mark up_for_jqu ery_chart( "pie","Sen d Success/ Failure",$ chartdata,  "success_ fail_chart ", "650px" ,"325px"," ['#0162A2' ,'#FFA500' ]");
  235                                      $data['h idden_char t'] = '<ta ble>';
  236                                      $data['h idden_char t'] .= '<c aption>Tab le represe nting data  in Send S uccess/Fai lure chart </caption> ';
  237                                      $data['h idden_char t'] .= '<t r><th scop e="col">Da ta Type</t h><th scop e="col">'  . $chartda ta['succes s']['label '] . '</th ><th scope ="col">' .  $chartdat a['fail'][ 'label'] .  '</th></t r>';
  238                                      $data['h idden_char t'] .= '<t r><th scop e="row">Co unt</th><t d>'.$chart data['succ ess']['val '].'</td>< td>'.$char tdata['fai l']['val'] .'</td></t r>';
  239                                      $data['h idden_char t'] .= '<t r><th scop e="row">Pe rcentage o f Total</t h><td>'.$t his->_calc MessagePer centage($c hartdata,  'success') .'</td><td >'.$this-> _calcMessa gePercenta ge($chartd ata, 'fail ').'</td>< /tr>';
  240                                      $data['h idden_char t'] .= '</ table>';
  241                                      break;
  242                             case " average_si ze":
  243                                      $this->v erify_perm ission("re ports_aver age_size") ;
  244                                      //create  average m essage siz e per day  chart
  245                                      $stmt =  $this->db- >query("SE LECT time  AS date, A VG(size) A S msg_size  FROM mail _log WHERE  inbound_o utbound=0  AND time B ETWEEN (da tediff(ss,  '19700101 ', GetUtcD ate()) - 5 18400) AND  (datediff (ss, '1970 0101', Get UtcDate()) ) GROUP BY  time");
  246                                      $chartda ta = array ();
  247                                      $results  = array() ;
  248                                      foreach( $stmt->res ult_array( ) as $row)  {
  249                                                       $d ate = date ("m/d", $r ow['date'] );
  250                                                       $s ize = $row ['msg_size '];
  251                                                       if (array_key _exists($d ate,$resul ts)) {
  252                                                                $res ults[$date ]['size']  = $results [$date]['s ize'] + $s ize;
  253                                                                $res ults[$date ]['count']  = $result s[$date][' count'] +  1;
  254                                                       }
  255                                                       el se { $resu lts[$date] ['size'] =  $size; $r esults[$da te]['count '] = 1; }
  256                                      }
  257                                      $i = 0;
  258                                      foreach( $results a s $key =>  $row) {
  259                                               $chartdata [$i]["date "] = $key;
  260                                               $chartdata [$i]["size "] = round (($row['si ze'] / $ro w['count'] ),2);
  261                                               $i++;
  262                                      }
  263                                      //add da tes with n o records  to chart
  264                                      $j = 0;
  265                                      for($i =  (date("U" ) - (86400 *6)); $i < = date("U" ); $i = $i  + 86400)  {
  266                                               if(isset($ chartdata[ $j]) && $c hartdata[$ j]["date"]  != date(" m/d",$i))  { array_sp lice($char tdata,$j,0 ,array(arr ay("date"  => date("m /d",$i), " size" => 0 ))); }
  267                                               else if(!i sset($char tdata[$j]) ){ $chartd ata[$j]["d ate"] = da te("m/d",$ i); $chart data[$j][" size"] = 0 ; }
  268                                               $j++;
  269                                      }
  270                                      $data['c hart_title '] = 'Avg.  Daily Mes sage Size  (KB) Chart ';
  271                                      $data["c hart"] = $ this->mark up_for_jqu ery_chart( "line","Av g. Daily M essage Siz e (KB)",$c hartdata,  "avg_size_ chart","65 0px","325p x");
  272                                      $data['h idden_char t'] = '<ta ble><capti on>Table r epresentin g data in  Average Da ily Messag e Size cha rt</captio n><tr><th> Date</th>< th>Size (K B)</th></t r>';
  273                                      foreach( $chartdata  as $cdata ) {
  274                                               $data['hid den_chart' ] .= '<tr> <td>' . $c data['date '] . '</td ><td>' . $ cdata['siz e'] . '</t d></tr>';
  275                                      }
  276                                      $data['h idden_char t'] .= '</ table>';
  277                                      break;
  278                             case " unique_log ins":
  279                                      $this->v erify_perm ission("re ports_uniq ue_logins" );
  280                                      //create  unique lo gins per d ay chart
  281                                      $stmt =  $this->db- >query("SE LECT login _time AS d ate, usern ame, ip_ad dress FROM  logins WH ERE succes s=1 AND (l ogin_time  BETWEEN (d atediff(ss , '1970010 1', GetUtc Date()) -  518400) AN D (datedif f(ss, '197 00101', Ge tUtcDate() )))");
  282                                      $chartda ta = array ();
  283                                      $results  = array() ;
  284                                      foreach( $stmt->res ult_array( ) as $row)  {
  285                                                       $d ate = date ("m/d", $r ow['date'] );
  286                                                       $u sername =  $row['user name'];
  287                                                       $i p = $row[' ip_address '];
  288                                                       $u ser_ip = $ username .  '#' . $ip ;
  289                                                       if (array_key _exists($d ate,$resul ts)) {
  290                                                                if(a rray_key_e xists($use r_ip,$resu lts[$date] )) {
  291                                                                         $resul ts[$date][ $user_ip][ 'count'] =  $results[ $date][$us er_ip]['co unt'] + 1;
  292                                                                }
  293                                                                else  { $result s[$date][$ user_ip][' count'] =  1; }
  294                                                       }
  295                                                       el se {
  296                                                                $res ults[$date ][$user_ip ]['count']  = 1;
  297                                                       }
  298                                      }
  299                                      foreach( $results a s $date =>  $logins)  {
  300                                               $day_count  = 0;
  301                                               foreach($l ogins as $ user_ip) {
  302                                                       $d ay_count++ ;
  303                                               }
  304                                               $results[$ date]['cou nt'] = $da y_count;
  305                                      }
  306                                      $i = 0;
  307                                      foreach( $results a s $key =>  $row) {
  308                                               $chartdata [$i]["date "] = $key;
  309                                               $chartdata [$i]["coun t"] = $row ['count'];
  310                                               $i++;
  311                                      }
  312  
  313                                      //add da tes with n o records  to chart
  314                                      $j = 0;
  315                                      for($i =  (date("U" ) - (86400 *6)); $i < = date("U" ); $i = $i  + 86400)  {
  316                                               if(isset($ chartdata[ $j]) && $c hartdata[$ j]["date"]  != date(" m/d",$i))  { array_sp lice($char tdata,$j,0 ,array(arr ay("date"  => date("m /d",$i), " count" =>  0))); }
  317                                               else if(!i sset($char tdata[$j]) ){ $chartd ata[$j]["d ate"] = da te("m/d",$ i); $chart data[$j][" count"] =  0; }
  318                                               $j++;
  319                                      }
  320                                      $data['c hart_title '] = 'Uniq ue Success ful Logins  Daily Cha rt';
  321                                      $data["c hart"] = $ this->mark up_for_jqu ery_chart( "bar","Uni que Succes sful Login s Daily",$ chartdata,  "unique_l ogin_chart ","650px", "325px","[ 'blue']");
  322                                      $data['h idden_char t'] = '<ta ble><capti on>Table r epresentin g data in  Unique Suc cessful Lo gins Daily  chart</ca ption><tr> <th>Date</ th><th>Log in Count</ th></tr>';
  323                                      foreach( $chartdata  as $cdata ) {
  324                                               $data['hid den_chart' ] .= '<tr> <td>' . $c data['date '] . '</td ><td>' . $ cdata['cou nt'] . '</ td></tr>';
  325                                      }
  326                                      $data['h idden_char t'] .= '</ table>';
  327                                      break;
  328                             case " login_succ ess":
  329                                      $this->v erify_perm ission("re ports_logi n_success" );
  330                                      //create  success v s fail log in chart
  331                                      $stmt =  $this->db- >query("SE LECT SUM(C ASE WHEN s uccess = 1  THEN 1 EL SE 0 END)  AS success , SUM(CASE  WHEN succ ess = 0 TH EN 1 ELSE  0 END) AS  fail FROM  logins");
  332                                      $chartda ta = array ();
  333                                      foreach( $stmt->res ult_array( ) as $row)  {
  334                                               $chartdata ["success" ]["label"]  = "Succee ded";
  335                                               $chartdata ["success" ]["val"] =  $row['suc cess'];
  336                                               $chartdata ["fail"][" label"] =  "Failed";
  337                                               $chartdata ["fail"][" val"] = $r ow['fail'] ;
  338                                      }
  339                                      $data['c hart_title '] = 'Logi n Success/ Failure Ch art';
  340                                      $data["c hart"] = $ this->mark up_for_jqu ery_chart( "pie","Log in Success /Failure", $chartdata , "login_s uccess_fai l_chart",  "650px","3 25px","['# 0162A2','# FFA500']") ;
  341                                      $data['h idden_char t'] = '<ta ble>';
  342                                      $data['h idden_char t'] .= '<c aption>Tab le represe nting data  in Login  Success/Fa ilure char t</caption >';
  343                                      $data['h idden_char t'] .= '<t r><th scop e="col">Da ta Type</t h><th scop e="col">'  . $chartda ta['succes s']['label '] . '</th ><th scope ="col">' .  $chartdat a['fail'][ 'label'] .  '</th></t r>';
  344                                      $data['h idden_char t'] .= '<t r><th scop e="row">Co unt</th><t d>' . $cha rtdata['su ccess']['v al'] . '</ td><td>' .  $chartdat a['fail'][ 'val'] . ' </td></tr> ';
  345                                      $data['h idden_char t'] .= '<t r><th scop e="row">Pe rcentage o f Total</t h><td>' .  round((($c hartdata[' success'][ 'val']/($c hartdata[' success'][ 'val']+$ch artdata['f ail']['val ']))*100), 2).'%'.'</ td><td>' .  round((($ chartdata[ 'fail']['v al']/($cha rtdata['su ccess']['v al']+$char tdata['fai l']['val'] ))*100),2) .'%'. '</t d></tr>';
  346                                      $data['h idden_char t'] .= '</ table>';
  347                                      break;
  348                             case " login_erro rs":
  349                                      $this->v erify_perm ission("re ports_logi n_errors") ;
  350                                      //create  failed lo gin error  chart
  351                                      $stmt =  $this->db- >query("SE LECT TOP(5 ) username , error_ms g FROM log ins WHERE  success =  0 ORDER BY  login_tim e DESC");
  352                                      $chartda ta = array ();
  353                                      $i = 0;
  354                                      foreach( $stmt->res ult_array( ) as $row)  {
  355                                               $chartdata [$i]["user name"] = $ row['usern ame'];
  356                                               $chartdata [$i]["erro r"] = $row ['error_ms g'];
  357                                               $i++;
  358                                      }
  359                                      $data['c hart_title '] = 'Rece nt Login F ailure Rea sons Chart ';
  360                                      $data["c hart"] = $ this->mark up_for_jqu ery_chart( "table","R ecent Logi n Failure  Reasons",$ chartdata,  "failed_l ogin_chart ", "650px" ,"325px"," ",FALSE);
  361                                      $data['h idden_char t'] = '';
  362                                      break;
  363                             case " attachment _types":
  364                                      $this->v erify_perm ission("re ports_atta chment_typ es");
  365                                      //create  unique at tachment t ypes chart
  366                                      $stmt =  $this->db- >query("SE LECT attac hment_type s FROM mai l_log");
  367                                      $chartda ta = array ();
  368                                      foreach( $stmt->res ult_array( ) as $row)  {
  369                                               if(strlen( trim($row[ "attachmen t_types"]) ) > 0) {
  370                                                       $c ounts = ar ray_count_ values(exp lode(" ",t rim($row[" attachment _types"])) );
  371                                                       fo reach($cou nts as $ke y => $coun t) {
  372                                                                if(! array_key_ exists($ke y,$chartda ta)) {
  373                                                                         $chart data[$key] ["type"] =  $key;
  374                                                                         $chart data[$key] ["count"]  = $count;
  375                                                                }
  376                                                                else  {
  377                                                                         $chart data[$key] ["type"] =  $key;
  378                                                                         $chart data[$key] ["count"]  = $chartda ta[$key][" count"] +  $count;
  379                                                                }
  380                                                       }
  381                                               }
  382                                               else if(st rlen(trim( $row["atta chment_typ es"])) ==  0) {
  383                                                       if (!array_ke y_exists(" none",$cha rtdata)) {
  384                                                                $cha rtdata["no ne"]["type "] = "none ";
  385                                                                $cha rtdata["no ne"]["coun t"] = 0;
  386                                                       }
  387                                                       el se {
  388                                                                $cha rtdata["no ne"]["type "] = "none ";
  389                                                                $cha rtdata["no ne"]["coun t"] = $cha rtdata["no ne"]["coun t"] + 1;
  390                                                       }
  391                                               }
  392                                      }
  393                                      $data['c hart_title '] = 'Uniq ue Attachm ent Type V olumes Cha rt';
  394                                      $data["c hart"] = $ this->mark up_for_jqu ery_chart( "bar","Uni que Attach ment Type  Volumes",$ chartdata, "unique_at tachments_ chart","65 0px","325p x","['blue ']");
  395                                      $data['h idden_char t'] = '<ta ble><capti on>Table r epresentin g data in  Unique Att achment Ty pe Volumes  chart</ca ption><tr> <th>Type</ th><th>Att achment Co unt</th></ tr>';
  396                                      foreach( $chartdata  as $cdata ) {
  397                                               $data['hid den_chart' ] .= '<tr> <td>' . $c data['type '] . '</td ><td>' . $ cdata['cou nt'] . '</ td></tr>';
  398                                      }
  399                                      $data['h idden_char t'] .= '</ table>';
  400                                      break;
  401                             defaul t:
  402                                      $data["c hart"] = " Unrecogniz ed chart t ype";
  403                                      break;
  404                    }
  405                    //lo ad view
  406                    $thi s->load->v iew("admin panel/char t",$data);
  407           }
  408  
  409           pu blic funct ion report s() {
  410                    $thi s->verify_ permission ("reports" );
  411                    $dat a["title"]  = PORTAL_ TITLE_PREF IX . "Admi n Panel";
  412                    $thi s->load->v iew("admin panel/repo rts",$data );
  413           }
  414  
  415           pu blic funct ion archiv e_setting( $action =  NULL) {
  416                    $thi s->verify_ permission ("archive_ settings") ;
  417                    if(i s_null($ac tion)) {
  418  
  419                             $data[ "title"] =  PORTAL_TI TLE_PREFIX  . "Archiv e Settings ";
  420                             $messa ge_archive _settings  = $this->d b->query(" SELECT TOP  1 * FROM  dbo.archiv e_settings ")->result ();
  421                             $data[ 'message_a rchive_set tings'] =  $message_a rchive_set tings;
  422  
  423                             $this- >load->vie w("adminpa nel/archiv e_settings ",$data);
  424                    }
  425  
  426           }
  427  
  428           pu blic funct ion themes ($action =  NULL) {
  429                    $thi s->verify_ permission ("themes") ;
  430                    if(i s_null($ac tion)) {
  431  
  432                             $data[ "title"] =  PORTAL_TI TLE_PREFIX  . "Admin  Panel";
  433                             $get_t hemes = $t his->db->q uery("SELE CT * FROM  themes");
  434                             $data[ "themes"]  = array();
  435                             if($ge t_themes)  {
  436                                      for($i =  0; $i < $ get_themes ->num_rows (); $i++)  {
  437                                               array_push ($data["th emes"],$ge t_themes-> row_array( $i));
  438                                      }
  439                             }
  440                             $this- >load->vie w("adminpa nel/themes ",$data);
  441                    }
  442                    //TO -DO: These  else stat ements on  failure sh ould lead  to error m essage giv en to user
  443                    else  if($actio n == "load _theme") {
  444                             $theme _id = $thi s->input-> post("them e_id",TRUE );
  445                             $check _theme =   $this->db- >query("SE LECT theme _id FROM t hemes WHER E theme_id  = " . $th is->db->es cape($them e_id));
  446                             if($ch eck_theme- >num_rows( ) > 0) {
  447                                      $update_ default_th eme = $thi s->db->que ry("UPDATE  themes SE T theme_is _default=0  WHERE the me_id !="  . $this->d b->escape( $theme_id) );
  448                                      if($upda te_default _theme) {
  449                                               $update_de fault_them e = $this- >db->query ("UPDATE t hemes SET  theme_is_d efault=1 W HERE theme _id=" . $t his->db->e scape($the me_id));
  450                                               if($update _default_t heme) {
  451                                                       $u pdate_them e = $this- >db->query ("UPDATE u sers SET u ser_theme= " . $this- >db->escap e($theme_i d));
  452                                                       if ($update_t heme) {
  453                                                                redi rect("admi npanel/the mes");
  454                                                       }
  455                                                       el se { redir ect("admin panel/them es"); }
  456                                               }
  457                                               else { red irect("adm inpanel/th emes"); }
  458                                      }
  459                             }
  460                             else {  redirect( "adminpane l/themes") ; }
  461                    }
  462                    else  { show_40 4(); }
  463           }
  464  
  465           
  466           // This funct ion loads  the webmai l ldap use rs for the  user to p ick from w hen decidi ng who to  share the  contact wi th.
  467           pu blic funct ion contac t_list_sea rch($input =null) {
  468                    $pro perties =  array('dis playname', 'mail','ui d');
  469                    $per son_result  = $this-> ldap->sear ch(rawurld ecode($inp ut),null,$ properties );
  470  
  471                    arra y_walk_rec ursive($pe rson_resul t, functio n (&$value ) {
  472                             $value  = htmlent ities($val ue);
  473                    });
  474                    //so rt result  array (nat ural order , case ins ensitive)
  475                    usor t($person_ result, fu nction( $e l1, $el2)  { return s trnatcasec mp( $el1[' displaynam e'], $el2[ 'displayna me']); });
  476  
  477                    echo  $this->js on->encode ($person_r esult);
  478           }
  479  
  480           pu blic funct ion distri bution_lis ts() {
  481                    $thi s->paginat e_distribu tion_lists (1);
  482           }
  483  
  484           pu blic funct ion pagina te_distrib ution_list s($page) {
  485                    $thi s->verify_ permission ("distribu tion_lists ");
  486                    $lis ts = $this ->public_d istributio n_list_mod el->find(a rray());
  487                    $dat a['list_co unt'] = co unt($lists );
  488                    $dat a['page']  = $page;
  489                    $dat a['lists']  = array_s lice($list s,(($page- 1)*ADMINPA NEL_DISPLA Y_PER_PAGE ),ADMINPAN EL_DISPLAY _PER_PAGE) ;
  490                    //so rt array b y keys, us ing natura l order (i .e. test1,  test2, .. . , test10  vs. test1 , test10,  test2)
  491                    ukso rt($data[' lists'], f unction($a , $b) { re turn strna tcasecmp($ a,$b); });
  492  
  493                    $dat a['title']  = PORTAL_ TITLE_PREF IX . 'Admi n Panel';  //set titl e of page
  494                    $thi s->load->v iew('admin panel/mana ge_lists/i ndex',$dat a);
  495           }
  496  
  497           pu blic funct ion distri bution_lis ts_removed () {
  498                    $thi s->paginat e_distribu tion_lists _removed(1 );
  499           }
  500  
  501           pu blic funct ion pagina te_distrib ution_list s_removed( $page) {
  502                    $thi s->verify_ permission ("distribu tion_lists ");
  503                    $lis ts = $this ->public_d istributio n_list_mod el->find_d eleted(arr ay());
  504                    $dat a['list_co unt'] = co unt($lists );
  505                    $dat a['page']  = $page;
  506                    $dat a['lists']  = array_s lice($list s,(($page- 1)*ADMINPA NEL_DISPLA Y_PER_PAGE ),ADMINPAN EL_DISPLAY _PER_PAGE) ;
  507                    $dat a['title']  = PORTAL_ TITLE_PREF IX . 'Admi n Panel';  //set titl e of page
  508                    $thi s->load->v iew('admin panel/mana ge_lists/r emoved',$d ata);
  509           }
  510  
  511           // displays t he edit fo rm - for s ave, see e dit_distri bution_lis ts()
  512           pu blic funct ion distri bution_lis ts_edit($i d) {
  513                    $thi s->verify_ permission ("distribu tion_lists ");
  514                    $act ive_tab =  '/adminpan el/distrib ution_list s/' ;
  515                    $for m = 'admin panel/edit _distribut ion_list';
  516                    $thi s->_distri bution_lis ts_edit($i d, 'public _distribut ion_list_m odel', com pact('acti ve_tab', ' form'));
  517           }
  518  
  519           // displays t he edit fo rm - for s ave, see d istributio n_lists_ed it_removed ()
  520           pu blic funct ion distri bution_lis ts_edit_re moved($id)  {
  521                    $thi s->verify_ permission ("distribu tion_lists ");
  522                    $act ive_tab =  '/adminpan el/distrib ution_list s/removed'  ;
  523                    $for m = 'admin panel/edit _removed_d istributio n_list';
  524                    $thi s->_distri bution_lis ts_edit($i d, 'delete d_public_d istributio n_list_mod el', compa ct('active _tab', 'fo rm'));
  525           }
  526  
  527           /* *
  528           *  Displays &  submits f orm to cre ate public  distribut ion lists.
  529           */
  530           pu blic funct ion create _distribut ion_list()  {
  531                    $thi s->verify_ permission ("distribu tion_lists _create");
  532                    $thi s->load->l ibrary('au dit');
  533                    $tit le = PORTA L_TITLE_PR EFIX . 'Ad min Panel' ;
  534                    $for m_data = a rray();
  535                    $val idation_er rors = arr ay();
  536                    $err or = '';
  537  
  538                    if(! empty($_PO ST)){
  539                             $list_ display_na me = $this ->input->p ost('list_ display_na me',TRUE);
  540                             $list_ descriptio n = $this- >input->po st('list_d escription ',TRUE);
  541  
  542                             //set  valdiation  rules
  543                             if($th is->form_v alidation- >run('dist ribution_l ist') ===  TRUE) {
  544                                      $attribu tes = arra y(
  545                                               'name' =>  $list_disp lay_name,
  546                                               'cn' => $l ist_displa y_name,
  547                                               'descripti on' => $li st_descrip tion,
  548                                      );
  549                                      $id = $t his->publi c_distribu tion_list_ model->cre ate($attri butes);
  550                                      if($this ->public_d istributio n_list_mod el->format ted_like_a n_id($id)) {
  551                                               $list = $t his->publi c_distribu tion_list_ model->fin d_one(arra y('cn'=> $ list_displ ay_name));
  552                                               $this->aud it->log_ev ent('edit' ,array(0,$ this->user ->id,'Crea ted list:  ' . $list_ display_na me. ' ('.$ list['id'] .')',date( 'U')));
  553                                               redirect(' adminpanel /distribut ion_lists/ list/'.$id );
  554                                      }else{
  555                                               $error = ' Something  went wrong  and your  distributi on list wa s not crea ted.  Plea se try aga in in a mo ment. '.
  556                                                                 'If  you conti nue to see  this erro r, please  contact a  site admin istrator.' ;
  557                                      }
  558                             }
  559                             else {
  560                                      //valida tion fails
  561                                      $form_da ta = $this ->input->p ost(NULL,T RUE);
  562                                      $form_da ta['list_d isplay_nam e']=html_e ntity_deco de($form_d ata['list_ display_na me'],ENT_Q UOTES);
  563                                      $form_da ta['list_d escription ']=html_en tity_decod e($form_da ta['list_d escription '],ENT_QUO TES);
  564                                      if(is_ar ray($form_ data)) {
  565                                               foreach($f orm_data a s $key =>  $input) {
  566                                                       if (strlen(fo rm_error($ key)) > 0)  { $valida tion_error s[$key] =  form_error ($key); }
  567                                               }
  568                                               $this->ses sion->set_ flashdata( 'validatio n_errors', $validatio n_errors);
  569                                      }
  570                             }
  571                    }
  572                    $thi s->load->v iew('admin panel/mana ge_lists/c reate',com pact('erro r', 'form_ data', 'ti tle', 'val idation_er rors'));
  573           }
  574  
  575           //  saves the  edit form  - for the  form setu p, see dis tribution_ lists_edit ()
  576           pu blic funct ion edit_d istributio n_list() {
  577                    retu rn $this-> _edit_dist ribution_l ist('publi c_distribu tion_list_ model');
  578           }
  579  
  580           //  saves the  edit form  - for the  form setu p, see dis tribution_ lists_edit _removed()
  581           pu blic funct ion edit_r emoved_dis tribution_ list() {
  582                    retu rn $this-> _edit_dist ribution_l ist('delet ed_public_ distributi on_list_mo del');
  583           }
  584  
  585           pu blic funct ion remove _distribut ion_list($ list_id) {
  586                    $thi s->verify_ permission ("distribu tion_lists ");
  587                    if($ this->publ ic_distrib ution_list _model->ex ists($list _id)) {
  588                             $list  = $this->p ublic_dist ribution_l ist_model- >find_one( $list_id);
  589                             $this- >public_di stribution _list_mode l->delete( $list_id);
  590                             $this- >load->lib rary('audi t');
  591                             if($li st !== nul l){
  592                                      $this->a udit->log_ event('edi t',array(0 ,$this->us er->id,'Re moved list : ' . $lis t['name'].  ' ('.$lis t_id.')',d ate('U'))) ;
  593                             }
  594                    }
  595                    else  { show_40 4(); }
  596                    redi rect('admi npanel/dis tribution_ lists');
  597           }
  598  
  599           pu blic funct ion restor e_distribu tion_list( $list_id)  {
  600                    $thi s->verify_ permission ("distribu tion_lists ");
  601                    if($ this->publ ic_distrib ution_list _model->ex ists_delet ed($list_i d)) {
  602                             $this- >public_di stribution _list_mode l->restore _deleted($ list_id);
  603                             $list  = $this->p ublic_dist ribution_l ist_model- >find_one( $list_id);
  604                             $this- >load->lib rary('audi t');
  605                             if($li st !== nul l){
  606                                      $this->a udit->log_ event('edi t',array(0 ,$this->us er->id,'Re stored lis t: ' . $li st['name'] . ' ('.$li st_id.')', date('U')) );
  607                             }
  608                    }
  609                    else  { show_40 4(); }
  610                    redi rect('admi npanel/dis tribution_ lists/remo ved');
  611           }
  612  
  613           /*  This func tion displ ays the ad d user to  group form  view, mea nt for use  with a mo dal window  or pop-up  */
  614           pu blic funct ion add_us er_to_grou p_form($gr oup,$activ e) {
  615                    $thi s->verify_ permission ("manage_g roups");
  616                    $thi s->load->v iew('admin panel/mana ge_groups/ add_user_f orm',array ('group'=> $group,'ac tive'=>$ac tive));
  617           }
  618  
  619  
  620           pu blic funct ion id_req uired($str , $field)  {
  621                    swit ch($field)  {
  622                             case ' piv':
  623                                      $this->f orm_valida tion->set_ message('i d_required ', 'The %s  field is  required w hen the ED IPI field  is not pro vided.');
  624                                      return ( strlen(tri m($str)) < = 0) ? FAL SE : TRUE;
  625                                      break;
  626                             case ' edipi':
  627                                      $this->f orm_valida tion->set_ message('i d_required ', 'The %s  field is  required w hen the PI V ID field  is not pr ovided.');
  628                                      return ( strlen(tri m($str)) < = 0) ? FAL SE : TRUE;
  629                                      break;
  630                             defaul t:
  631                                      return F ALSE;
  632                                      break;
  633                    }
  634           }
  635  
  636           pu blic funct ion update _archive_s etting() {
  637                    $thi s->form_va lidation-> set_rules( "archive_a ge","Messa ge Age for  Archive", "required| is_natural _no_zero", "xss_clean ");
  638                    $thi s->form_va lidation-> set_rules( "frequency ","Frequen cy","requi red","xss_ clean");
  639                    $fre quency = $ this->inpu t->post("f requency", TRUE);
  640                    $arc hive_age =  $this->in put->post( "archive_a ge",TRUE);
  641                    $arc hive_age_u nit = $thi s->input-> post("arch ive_age_un it",TRUE);
  642                    if($ this->form _validatio n->run() = = true) {
  643                             $frequ ency = $th is->input- >post("fre quency",TR UE);
  644                             $archi ve_age = $ this->inpu t->post("a rchive_age ",TRUE);
  645                             $frequ ency_array  = array(' none', 'da ily', 'wee kly', 'biw eekly', 'm onthly', ' bimonthly' , 'six_mon ths', 'yea rly');
  646                             $archi ve_age_uni t_array =  array('day ', 'week',  'month',  'year');
  647  
  648                             if(in_ array($fre quency, $f requency_a rray) && i n_array($a rchive_age _unit, $ar chive_age_ unit_array )) {
  649                                      $message _archive_s etting_id  = $this->d b->query(" SELECT TOP  1 id FROM  dbo.archi ve_setting s")->resul t();
  650                                      $message _archive_s etting_id  = $message _archive_s etting_id[ 0]->id;
  651                                      $update  = $this->d b->query(" UPDATE dbo .archive_s ettings SE T frequenc y = " . $t his->db->e scape($fre quency) .  ", archive _age = " .  $this->db ->escape($ archive_ag e) . ", ar chive_age_ unit = " .  $this->db ->escape($ archive_ag e_unit) .  " WHERE id  = " . $th is->db->es cape($mess age_archiv e_setting_ id));
  652                             }
  653  
  654                             redire ct('/admin panel/arch ive_settin g');
  655                    }
  656                    else  {
  657                             $form_ data = $th is->input- >post(NULL ,TRUE);
  658                             $valid ation_erro rs = array ();
  659                             if(is_ array($for m_data)) {
  660                                      foreach( $form_data  as $key = > $input)  {
  661                                               if(strlen( form_error ($key)) >  0) { $vali dation_err ors[$key]  = form_err or($key);  }
  662                                      }
  663                                      $this->s ession->se t_flashdat a('validat ion_errors ',$validat ion_errors );
  664                             }
  665                             redire ct('/admin panel/arch ive_settin g');
  666                    }
  667           }
  668  
  669           pu blic funct ion ajax_g roup_membe r_search($ input = NU LL,$sizeli mit = NULL , $echo =  TRUE) {
  670                    if(! is_null($s izelimit))  { $proper ties = NUL L; }
  671                    else  {  $prope rties = ar ray('displ ayname','o bjectclass ','mail',' uid','give nname','in itials','s n','physic aldelivery officename ','o','dep artmentnum ber','mobi le','telep honenumber ','title') ;}
  672  
  673                    //on ly allow e choing of  JSON data  if request ed with AJ AX
  674                    if(I S_AJAX) {
  675                             if($ec ho) { echo  $this->js on->encode ($this->ld ap->search (rawurldec ode($input ),$sizelim it,$proper ties,'(&(u serPasswor d=*)(|(dis playName=' .$input.'* )(uid='.$i nput.'*))) ')); }
  676                    }
  677                    //if  not echoi ng, allow  return
  678                    if(! $echo) { r eturn $thi s->json->e ncode($thi s->ldap->s earch(rawu rldecode($ input),$si zelimit,$p roperties, '(&(userPa ssword=*)( |(displayN ame='.$inp ut.'*)(uid ='.$input. '*)))'));  }
  679           }
  680  
  681   ////////// ////////// ////////// ////////// ////////// ////////// ////////
  682   // PROTECT ED METHODS
  683   // Helper  methods fo r this con troller wh ich are no t web-acce ssible.
  684   ////////// ////////// ////////// ////////// ////////// ////////// ////////
  685  
  686           // helper met hod to dis play the e dit form f or active  & removed  distros
  687           pr otected fu nction _di stribution _lists_edi t($id, $mo del, $data ) {
  688                    if(! $this->is- >nonempty_ string($mo del)) retu rn $this-> error->sho uld_be_a_n onempty_st ring($mode l);
  689  
  690                    //fi rst, check  to make s ure we hav e a valid  list id
  691                    $thi s->load->m odel($mode l,'list_mo del');
  692                    if(! $this->lis t_model->f ormatted_l ike_an_id( $id)) show _404();
  693                    $lis t = $this- >list_mode l->find_on e(array('i d'=>$id));
  694                    if(e mpty($list )) show_40 4();
  695  
  696                    //lo ad data fo r form
  697                    $dat a['title']  = PORTAL_ TITLE_PREF IX . 'Admi n Panel';
  698                    $dat a['list_id '] = $id;
  699                    $dat a['list']  = $list;
  700                    $dat a['address es'] = $th is->list_m odel->addr esses_for_ list($list );
  701                    $dat a['form_da ta'] = arr ay('list_d isplay_nam e' => $lis t['name'],
  702                                                                            'li st_descrip tion' => $ list['desc ription']) ;
  703  
  704                    //se t up the o ptions for  the multi select
  705                    $use r_options  = array();
  706                    fore ach($this- >get_user_ search() a s $user){
  707                             $email  = strtolo wer(trim($ user['id'] ));
  708                             $user_ options[$e mail] =  $ user['name '] . ' ('. $email.')' ;
  709                    }
  710  
  711                    $ext ernal_addr esses = ar ray_diff($ data['addr esses'], a rray_keys( $user_opti ons));
  712                    fore ach($exter nal_addres ses as $ex ternal_add ress){
  713                             $user_ options[$e xternal_ad dress] = $ external_a ddress;
  714                    }
  715                    natc asesort($u ser_option s);
  716                    $dat a['user_op tions'] =  $user_opti ons;
  717  
  718                    $thi s->load->v iew('admin panel/mana ge_lists/e dit_list',  $data);
  719           }
  720  
  721           //  helper me thod used  by both me thods that  save edit  forms for  distros ( edit_distr ibution_li st && edit _removed_d istributio n_list)
  722           pr otected fu nction _ed it_distrib ution_list ($model) {
  723                    if(! $this->is- >nonempty_ string($mo del)) retu rn $this-> error->sho uld_be_a_n onempty_st ring($mode l);
  724                    $thi s->load->m odel($mode l,'list_mo del');
  725  
  726                    $lis t_display_ name = $th is->input- >post('lis t_display_ name',TRUE );
  727                    $lis t_descript ion = $thi s->input-> post('list _descripti on',TRUE);
  728                    $new _members =  $this->in put->post( 'list_memb ers',TRUE) ;
  729                    if(e mpty($new_ members))  $new_membe rs = array (); //when  nothing's  selected,  we don't  always get  an array  back
  730                    $new _members =  array_map ('strtolow er', $new_ members);
  731                    $lis t_id = $th is->input- >post('lis t_id',TRUE );
  732  
  733                    //se t valdiati on rules
  734                    if($ this->form _validatio n->run('di stribution _list') == = TRUE) {
  735                             //upda te display  name and  descriptio n
  736                             $attri butes = ar ray(
  737                                      'cn' =>  $list_disp lay_name,
  738                                      'descrip tion' => $ list_descr iption,
  739                             );
  740                             $this- >list_mode l->update( $list_id,$ attributes );
  741                             //upda te address es
  742                             $old_m embers = $ this->list _model->ad dresses_fo r_list($li st_id);
  743                             $addre sses_to_ad d = array_ diff($new_ members,$o ld_members );
  744                             $addre sses_to_re move = arr ay_diff($o ld_members ,$new_memb ers);
  745  
  746                             foreac h($address es_to_add  as $addres s) {
  747                                       $this-> list_model ->add_addr ess_to_lis t($list_id ,$address) ;
  748                             }
  749                             foreac h($address es_to_remo ve as $add ress) {
  750                                       $this-> list_model ->remove_a ddress_fro m_list($li st_id,$add ress);
  751                             }
  752                    }
  753                    else  {
  754                             //vali dation fai ls
  755                             $form_ data = $th is->input- >post(NULL ,TRUE);
  756                             $valid ation_erro rs = array ();
  757                             if(is_ array($for m_data)) {
  758                                      foreach( $form_data  as $key = > $input)  {
  759                                               if(strlen( form_error ($key)) >  0) { $vali dation_err ors[$key]  = form_err or($key);  }
  760                                      }
  761                                      echo $th is->json-> encode($va lidation_e rrors);
  762                             }
  763                    }
  764           }
  765  
  766           pr otected fu nction log _view($act ion = NULL , $value =  NULL) {
  767                    $dat a["title"]  = PORTAL_ TITLE_PREF IX . "Admi n Panel";
  768                    $thi s->load->l ibrary('lo cale');
  769                    $tim ezone_abbr ev = $this ->locale-> timezone_a bbr_from_n ame(date_d efault_tim ezone_get( ));
  770                    if($ action ==  "logins")  {
  771                             $this- >verify_pe rmission(" logs_login s");
  772                             $data[ "active_ta b"] = "log ins";
  773                             if(is_ null($valu e)) { $pag e_start =  0; $page =  1; }
  774                             else {  $page = $ value; $pa ge_start =  (($page-1 )*ADMINPAN EL_LOG_DIS PLAY_PER_P AGE);  }
  775                             $login s = $this- >db->query ("SELECT *  FROM (SEL ECT ROW_NU MBER() OVE R (ORDER B Y login_ti me DESC) A S RowNum,  * FROM log ins) AS ro ws WHERE R owNum > "  . ($page_s tart) . "  AND RowNum  <= " . ($ page_start  + ADMINPA NEL_LOG_DI SPLAY_PER_ PAGE) . "  ORDER BY R owNum");
  776                             $log_c ount_query  = $this-> db->query( "SELECT CO UNT(id) AS  login_cou nt FROM lo gins");
  777                             if($lo gins && $l og_count_q uery) {
  778                                      $row = $ log_count_ query->row _array();
  779                                      $log_cou nt = $row[ "login_cou nt"];
  780                                      $view_st r = "<span  style=\"f loat: righ t;\"><a hr ef=\"javas cript:expo rtCSV('log ins');\">E xport</a>< /span>";
  781                                      $view_st r .= "<h2> System Log s &#8594;  Login Logs </h2>";
  782                                      $view_st r .= $this ->generate _paginatio n($page,$l og_count,A DMINPANEL_ LOG_DISPLA Y_PER_PAGE ,'/adminpa nel/logs/l ogins/');
  783                                      $view_st r .= "<tab le class=\ "log\">";
  784                                      $view_st r .= '<cap tion class ="hidden_c ontext">Lo g of Login  Records</ caption>';
  785                                      $view_st r .= "<tr> <th>Log Da te";
  786                                      if(isset ($timezone _abbrev))  { $view_st r .= ' ('  . $timezon e_abbrev . ')'; }
  787                                      $view_st r .= "</th ><th>Usern ame</th><t h>IP Addre ss</th><th >Login Suc cess</th>< th>Error M essage</th ></tr>";
  788                                      for($i =  0; $i < $ logins->nu m_rows();  $i++) {
  789                                               $row = $lo gins->row_ array($i);
  790                                               if($row["s uccess"])  { $success  = "Succes s"; } else  { $succes s = "Failu re"; }
  791                                               $view_str  .= "<tr><t d>" . html entities(d ate("m/d/y  h:i:s A", $row["logi n_time"]))  . "</td>< td>" . htm lentities( $row["user name"]) .  "</td><td> " . htmlen tities($ro w["ip_addr ess"]) . " </td><td>"  . $succes s . "</td> <td>" . ht mlentities ($row["err or_msg"])  . "</td></ tr>";
  792                                      }
  793                                      $view_st r .= "</ta ble>";
  794                             }
  795                    }
  796                    else  if($actio n == "sent _mail") {
  797                             $this- >verify_pe rmission(" logs_sent_ mail");
  798                             $data[ "active_ta b"] = "sen t_mail";
  799                             if(is_ null($valu e)) { $pag e_start =  0; $page =  1; }
  800                             else {  $page = $ value; $pa ge_start =  (($page-1 )*ADMINPAN EL_LOG_DIS PLAY_PER_P AGE);  }
  801                             $sent_ mail = $th is->db->qu ery("SELEC T * FROM ( SELECT ROW _NUMBER()  OVER (ORDE R BY time  DESC) AS R owNum, * F ROM mail_l og WHERE i nbound_out bound=0) A S rows WHE RE inbound _outbound  = 0 AND Ro wNum > " .  ($page_st art) . " A ND RowNum  <= " . ($p age_start  + ADMINPAN EL_LOG_DIS PLAY_PER_P AGE) . " O RDER BY Ro wNum");
  802                             $log_c ount_query  = $this-> db->query( "SELECT CO UNT(id) AS  sent_coun t FROM mai l_log WHER E inbound_ outbound=0 ");
  803                             if($se nt_mail &&  $log_coun t_query) {
  804                                      $row = $ log_count_ query->row _array();
  805                                      $log_cou nt = $row[ "sent_coun t"];
  806                                      $view_st r = "<span  style=\"f loat: righ t;\"><a hr ef=\"javas cript:expo rtCSV('sen t_mail');\ ">Export</ a></span>" ;
  807                                      $view_st r .= "<h2> System Log s &#8594;  Sent Mail  Logs</h2>" ;
  808                                      $view_st r .= $this ->generate _paginatio n($page,$l og_count,A DMINPANEL_ LOG_DISPLA Y_PER_PAGE ,'/adminpa nel/logs/s ent_mail/' );
  809                                      $view_st r .= "<tab le class=\ "log\">";
  810                                      $view_st r .= '<cap tion class ="hidden_c ontext">Lo g of Sent  Mail</capt ion>';
  811                                      $view_st r .= "<tr> <th>Log Da te";
  812                                      if(isset ($timezone _abbrev))  { $view_st r .= ' ('  . $timezon e_abbrev . ')'; }
  813                                      $view_st r .="</th> <th>Sender </th><th>R ecipient(s )</th><th> Message Si ze (KB)</t h><th>Send  Success</ th></tr>";
  814                                      for($i =  0; $i < $ sent_mail- >num_rows( ); $i++) {
  815                                               $row = $se nt_mail->r ow_array($ i);
  816                                               if($row["s uccess"])  { $success  = "Succes s"; } else  { $succes s = "Failu re"; }
  817                                               $view_str  .= "<tr><t d>" . html entities(d ate("m/d/y  h:i:s A", $row["time "])) . "</ td><td>" .  htmlentit ies($row[" sender"])  . "</td><t d>" . html entities(i mplode(",  ",$this->j son->decod e($row["re cipient"]) )) . "</td ><td>" . $ row["size" ] . "</td> <td>" . $s uccess . " </td></tr> ";
  818                                      }
  819                                      $view_st r .= "</ta ble>";
  820                             }
  821                    }
  822                    else  if($actio n == "rece ived_mail" ) {
  823                             $this- >verify_pe rmission(" logs_recei ved_mail") ;
  824                             $data[ "active_ta b"] = "rec eived_mail ";
  825                             if(is_ null($valu e)) { $pag e_start =  0; $page =  1; }
  826                             else {  $page = $ value; $pa ge_start =  (($page-1 )*ADMINPAN EL_LOG_DIS PLAY_PER_P AGE);  }
  827                             $sent_ mail = $th is->db->qu ery("SELEC T * FROM ( SELECT ROW _NUMBER()  OVER (ORDE R BY time  DESC) AS R owNum, * F ROM mail_l og WHERE i nbound_out bound=1) A S rows WHE RE inbound _outbound  = 1 AND Ro wNum > " .  ($page_st art) . " A ND RowNum  <= " . ($p age_start  + ADMINPAN EL_LOG_DIS PLAY_PER_P AGE) . " O RDER BY Ro wNum");
  828                             $log_c ount_query  = $this-> db->query( "SELECT CO UNT(id) AS  sent_coun t FROM mai l_log WHER E inbound_ outbound=1 ");
  829                             if($se nt_mail &&  $log_coun t_query) {
  830                                      $row = $ log_count_ query->row _array();
  831                                      $log_cou nt = $row[ "sent_coun t"];
  832                                      $view_st r = "<span  style=\"f loat: righ t;\"><a hr ef=\"javas cript:expo rtCSV('rec eived_mail ');\">Expo rt</a></sp an>";
  833                                      $view_st r .= "<h2> System Log s &#8594;  Received M ail Logs</ h2>";
  834                                      $view_st r .= $this ->generate _paginatio n($page,$l og_count,A DMINPANEL_ LOG_DISPLA Y_PER_PAGE ,'/adminpa nel/logs/r eceived_ma il/');
  835                                      $view_st r .= "<tab le class=\ "log\">";
  836                                      $view_st r .= '<cap tion class ="hidden_c ontext">Lo g of Recei ved Mail</ caption>';
  837                                      $view_st r .= "<tr> <th>Log Da te";
  838                                      if(isset ($timezone _abbrev))  { $view_st r .= ' ('  . $timezon e_abbrev . ')'; }
  839                                      $view_st r .="</th> <th>Sender </th><th>R ecipient(s )</th><th> Message Si ze (KB)</t h><th>Rece ipt Succes s</th></tr >";
  840                                      for($i =  0; $i < $ sent_mail- >num_rows( ); $i++) {
  841                                               $row = $se nt_mail->r ow_array($ i);
  842                                               if($row["s uccess"])  { $success  = "Succes s"; } else  { $succes s = "Failu re"; }
  843                                               $view_str  .= "<tr><t d>" . html entities(d ate("m/d/y  h:i:s A", $row["time "])) . "</ td><td>" .  htmlentit ies($row[" sender"])  . "</td><t d>" . html entities(i mplode(",  ",$this->j son->decod e($row["re cipient"]) )) . "</td ><td>" . $ row["size" ] . "</td> <td>" . $s uccess . " </td></tr> ";
  844                                      }
  845                                      $view_st r .= "</ta ble>";
  846                             }
  847                    }
  848                    else  if($actio n == "edit ") {
  849                             $this- >verify_pe rmission(" logs_edit" );
  850                             $data[ "active_ta b"] = "edi t";
  851                             if(is_ null($valu e)) { $pag e_start =  0; $page =  1; }
  852                             else {  $page = $ value; $pa ge_start =  (($page-1 )*ADMINPAN EL_LOG_DIS PLAY_PER_P AGE);  }
  853                             $edits  = $this-> db->query( "SELECT *  FROM (SELE CT ROW_NUM BER() OVER  (ORDER BY  edit_date time DESC)  AS RowNum , * FROM e dit_log) A S rows WHE RE RowNum  > " . ($pa ge_start)  . " AND Ro wNum <= "  . ($page_s tart + ADM INPANEL_LO G_DISPLAY_ PER_PAGE)  . " ORDER  BY RowNum" );
  854                             $log_c ount_query  = $this-> db->query( "SELECT CO UNT(edit_i d) AS edit _count FRO M edit_log ");
  855                             if($ed its && $lo g_count_qu ery) {
  856                                      $row = $ log_count_ query->row _array();
  857                                      $log_cou nt = $row[ "edit_coun t"];
  858                                      $view_st r = "<span  style=\"f loat: righ t;\"><a hr ef=\"javas cript:expo rtCSV('edi t');\">Exp ort</a></s pan>";
  859                                      $view_st r .= "<h2> System Log s &#8594;  User Edit  Logs</h2>" ;
  860                                      $view_st r .= $this ->generate _paginatio n($page,$l og_count,A DMINPANEL_ LOG_DISPLA Y_PER_PAGE ,'/adminpa nel/logs/e dit/');
  861                                      $view_st r .= "<tab le class=\ "log\">";
  862                                      $view_st r .= '<cap tion class ="hidden_c ontext">Lo g of Edit  Records</c aption>';
  863                                      $view_st r .= "<tr> <th>Log Da te";
  864                                      if(isset ($timezone _abbrev))  { $view_st r .= ' ('  . $timezon e_abbrev . ')'; }
  865                                      $view_st r .= "</th ><th>Targe t</th><th> Actor</th> <th>Action </th></tr> ";
  866                                      for($i =  0; $i < $ edits->num _rows(); $ i++) {
  867                                               $row = $ed its->row_a rray($i);
  868                                               $target_id _query = $ this->db-> query("SEL ECT user_n ame FROM u sers WHERE  user_id="  . $this-> db->escape ($row["tar get_user_i d"]));
  869                                               $actor_id_ query = $t his->db->q uery("SELE CT user_na me FROM us ers WHERE  user_id="  . $this->d b->escape( $row["acto r_user_id" ]));
  870                                               if($target _id_query  && $actor_ id_query)  {
  871                                                       $t arget_id_r ow = $targ et_id_quer y->row_arr ay();
  872                                                       $a ctor_id_ro w = $actor _id_query- >row_array ();
  873                                                       $t arget_name  = isset($ target_id_ row ["user _name"]) ?  $target_i d_row ["us er_name"]  : "Unknown  User";
  874                                                       $a ctor_name  = isset($a ctor_id_ro w ["user_n ame"]) ? $ actor_id_r ow ["user_ name"] : " Unknown Us er";
  875                                                       $v iew_str .=  "<tr><td> " . htmlen tities(dat e("m/d/y h :i:s A",$r ow["edit_d atetime"]) ) . "</td> <td>" . ht mlentities ($target_n ame) . "</ td><td>" .  htmlentit ies($actor _name) . " </td><td>"  . htmlent ities($row ["edit_act ion"]) . " </td></tr> ";
  876                                               }
  877                                      }
  878                                      $view_st r .= "</ta ble>";
  879                             }
  880                    }
  881                    else  if($actio n == "feed back") {
  882                             $this- >verify_pe rmission(" logs_feedb ack");
  883                             $data[ "active_ta b"] = "fee dback";
  884                             if(is_ null($valu e)) { $pag e_start =  0; $page =  1; }
  885                             else {  $page = $ value; $pa ge_start =  (($page-1 )*ADMINPAN EL_LOG_DIS PLAY_PER_P AGE);  }
  886                             $feedb ack = $thi s->db->que ry("SELECT  * FROM (S ELECT ROW_ NUMBER() O VER (ORDER  BY feedba ck_id DESC ) AS RowNu m, * FROM  feedback)  AS rows WH ERE RowNum  > " . ($p age_start)  . " AND R owNum <= "  . ($page_ start + AD MINPANEL_L OG_DISPLAY _PER_PAGE)  . " ORDER  BY RowNum ");
  887                             $log_c ount_query  = $this-> db->query( "SELECT CO UNT(feedba ck_id) AS  feedback_c ount FROM  feedback") ;
  888                             if($fe edback &&  $log_count _query) {
  889                                      $row = $ log_count_ query->row _array();
  890                                      $log_cou nt = $row[ "feedback_ count"];
  891                                      $view_st r = "<span  style=\"f loat: righ t;\"><a hr ef=\"javas cript:expo rtCSV('fee dback');\" >Export</a ></span>";
  892                                      $view_st r .= "<h2> System Log s &#8594;  User Feedb ack Logs</ h2>";
  893                                      $view_st r .= $this ->generate _paginatio n($page,$l og_count,A DMINPANEL_ LOG_DISPLA Y_PER_PAGE ,'/adminpa nel/logs/f eedback/') ;
  894                                      $view_st r .= "<tab le class=\ "log\">";
  895                                      $view_st r .= '<cap tion class ="hidden_c ontext">Lo g of Feedb ack Record s</caption >';
  896                                      $view_st r .= "<tr> <th>Log Da te";
  897                                      if(isset ($timezone _abbrev))  { $view_st r .= ' ('  . $timezon e_abbrev . ')'; }
  898                                      $view_st r .= "</th ><th>Usern ame</th><t h>Feedback  Type</th> <th>Feedba ck Comment s</th></tr >";
  899                                      for($i =  0; $i < $ feedback-> num_rows() ; $i++) {
  900                                               $row = $fe edback->ro w_array($i );
  901                                               $actor_id_ query = $t his->db->q uery("SELE CT user_na me FROM us ers WHERE  user_id="  . $this->d b->escape( $row["user _id"]));
  902                                               if($actor_ id_query)  {
  903                                                       $a ctor_id_ro w = $actor _id_query- >row_array ();
  904                                                       $a ctor_name  = $actor_i d_row ["us er_name"];
  905                                                       $v iew_str .=  "<tr><td> " . htmlen tities(dat e("m/d/y h :i:s A",$r ow["feedba ck_datetim e"])) . "< /td><td>"  . htmlenti ties($acto r_name) .  "</td><td> " . htmlen tities($ro w["feedbac k_type"])  . "</td><t d>" . html entities($ row["feedb ack_commen ts"]) . "< /td></tr>" ;
  906                                               }
  907                                      }
  908                                      $view_st r .= "</ta ble>";
  909                             }
  910                    }
  911                    else  { show_40 4(); }
  912                    $dat a["log_vie w"] = $vie w_str;
  913                    retu rn $data;
  914           }
  915  
  916           /*  This func tion takes  inputs an d uses the m to creat e a table  which can  then be tr ansformed  by the jQu ery visual ization
  917            *  library.
  918            * /
  919           pr otected fu nction mar kup_for_jq uery_chart ($chartTyp e, $captio n, $data,  $id, $widt h="325px",  $height=" 100px", $c olors="['r ed']", $vi sualize=TR UE) {
  920                    $cha rt_table =  "<table c lass=\"cha rt\" id=\" " . $id .  "\" style= \"width: "  . $width  ."; height : " . $hei ght . ";\" >\n";
  921                    $cha rt_table . = "<captio n>" . $cap tion . "</ caption>\n ";
  922                    $cha rt_table . = "<tbody> \n";
  923                    if($ chartType  != "table" ) { $chart _table .=  "<thead>\n "; }
  924                    $i =  0;
  925                    fore ach($data  as $row) {
  926                             if($i  == 0 && $c hartType ! = "table")  { $chart_ table .= " <tr>\n"; }
  927                             $j = 0 ;
  928                             foreac h($row as  $col) {
  929                                      if($j ==  0 && $cha rtType !=  "table") {  $chart_ta ble .= "<t h scope=\" col\">" .   $col . "< /th>\n"; }
  930                                      $j++;
  931                             }
  932                             if($i+ 1 == count ($data) &&  $chartTyp e != "tabl e") { $cha rt_table . = "</tr>\n "; }
  933                             $i++;
  934                    }
  935                    if($ chartType  != "table" ) { $chart _table .=  "</thead>\ n"; }
  936                    $i =  0;
  937                    fore ach($data  as $row) {
  938                             if($i  == 0 || $c hartType = = "pie" ||  $chartTyp e == "tabl e") { $cha rt_table . = "<tr>\n" ; }
  939                             $j = 0 ;
  940                             foreac h($row as  $col) {
  941                                      if($j !=  0) { $cha rt_table . = "<td>" .   $col . " </td>\n";  }
  942                                      else if( ($chartTyp e == "pie"  || $chart Type == "t able") &&  $j == 0) {  $chart_ta ble .= "<t h scope=\" row\">" .   $col . "< /th>\n";}
  943                                      $j++;
  944                             }
  945                             if($i+ 1 == count ($data) ||  $chartTyp e == "pie"  || $chart Type == "t able") { $ chart_tabl e .= "</tr >\n"; }
  946                             $i++;
  947                    }
  948                    $cha rt_table . = "</tbody >\n";
  949                    $cha rt_table . = "</table >\n";
  950                    if($ visualize  == TRUE) {
  951                             $chart _table .=  "<script>
  952                             $(docu ment).read y(
  953                                      function () { $('#"  . $id . " ').css('di splay','no ne');
  954                                      $('#" .  $id . "'). visualize( {type: '"  .$chartTyp e . "', wi dth: '" .  $width . " ', height:  '" .$heig ht. "', co lors: ". $ colors ."} ); }
  955                             );
  956                             </scri pt>\n";
  957                    }
  958                    retu rn $chart_ table;
  959           }
  960  
  961           pr otected fu nction gen erate_pagi nation($pa ge,$items, $items_per _page,$lin k) {
  962                    $vie w_str = '< h3 class=" hidden_con text">Pagi nation</h3 >';
  963                    if($ items > $i tems_per_p age) {
  964                             $view_ str .= "<d iv id=\"pa gination\" >\n";
  965                             if($it ems%$items _per_page  > 0) { $pa ge_count =  (int)($it ems/$items _per_page) +1; }
  966                             else {  $page_cou nt = (int) ($items/$i tems_per_p age); }
  967                             //styl e paginati on
  968                             $befor e_span = 5 ;
  969                             $after _span = 5;
  970                             if($pa ge - 5 <=  0) { $afte r_span +=  abs($page  - $before_ span); }
  971                             else i f($page +  5 > $page_ count) { $ before_spa n += abs($ page_count  - ($page  + $after_s pan)); }
  972                             for($i  = ($page  - $before_ span); $i  <= ($page+ $after_spa n); $i++)  {
  973                                      if($i >  0 && $i <=  $page_cou nt) {
  974                                               if($i == ( $page - $b efore_span ) && ($pag e - $befor e_span > 1 )) { $view _str .= '< a style="m argin-righ t: 3px;" h ref="' . $ link . ($p age - 1).  '"><img sr c="/images /lt.png" a lt="Previo us Page">< /a>'; }
  975                                               if(($i) !=  $page) {  $view_str  .= '<a hre f="' . $li nk . ($i)  . '">' . ( $i) . '</a > '; }
  976                                               else {  $v iew_str .=  "<span st yle=\"padd ing: 2px;  font-weigh t: bold;\" >" . ($i)  . '</span> '; }
  977                                               if($i == ( $page+$aft er_span) & & ($page+$ after_span  < $page_c ount)) { $ view_str . = '<a href ="' . $lin k . ($page  + 1). '"> <img src=" /images/gt .png" alt= "Next Page "></a>'; }
  978                                      }
  979                             }
  980                             $view_ str .= "</ div>\n";
  981                    }
  982                    retu rn $view_s tr;
  983           }
  984  
  985           pr otected fu nction san itize_expo rt($input) {
  986                    retu rn str_rep lace("\"", "\"\"",str _replace(a rray("\r", "\n"),"",$ input));
  987           }
  988  
  989           pu blic funct ion valid_ formatted_ address($s tr)
  990           {
  991                    $val id_format  = (!preg_m atch("/^([ a-z0-9\'\+ _\-]+)(\.[ a-z0-9\'\+ _\-]+)*@([ a-z0-9\-]+ \.)+[a-z]{ 2,6}$/ix",  $str)) ?  FALSE : TR UE;
  992                    retu rn $valid_ format;
  993           }
  994  
  995           pr otected fu nction _ca lcMessageP ercentage( $data, $wh ich) {
  996                    $suc cessCount  = empty($d ata['succe ss']['val' ]) ? 0 : $ data['succ ess']['val '];
  997                    $fai lCount = e mpty($data ['fail'][' val']) ? 0  : $data[' fail']['va l'];
  998                    $tot alCount =  $successCo unt + $fai lCount;
  999  
  1000                    if ( $totalCoun t === 0) {
  1001                             return  'N/A';
  1002                    }
  1003  
  1004                    retu rn round($ data[$whic h]['val']/ $totalCoun t, 2) * 10 0 . '%';
  1005           }
  1006  
  1007   ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////
  1008   // USER HE LPER FUNCT IONS
  1009   // These f unctions a re not web -accessibl e and at s ome point  we should  evaluate w hether or  not they w ould more  appropriat ely belong  in models /libraries .
  1010   ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////
  1011  
  1012           pr otected fu nction can _edit_user ($username ){
  1013                    if($ this->has_ permission ("manage_u sers_all") ){
  1014                             return  true;
  1015                    }els e if($this ->has_perm ission("ma nage_users _facilitie s")){
  1016                             $resou rce = '/di rect/accou nt/in_faci lity/mailb ox/'.$this ->session- >userdata( 'username' );
  1017                             $resou rce .= '/f ormat/json ';
  1018                             $respo nse = @$th is->api_mo del->webse rvice_call ($resource ,'GET');
  1019                             if($re sponse->ht tp_status  === 200){
  1020                                      $users =  $response ->response ->accounts ;
  1021                                      if( in_a rray($user name, $use rs)){
  1022                                               return tru e;
  1023                                      }
  1024                             }
  1025                    }
  1026                    show _404();
  1027           }
  1028  
  1029           /*  This sear ches the a ddress boo k and retu rns a list  of users  for use wi th the sea rch in edi t distribu tion list  view */
  1030           pr otected fu nction get _user_sear ch($input  = null){
  1031           $i nput = url decode($in put);
  1032                    $res ult_arr =  array();
  1033                    $ent ries = ($t his->ldap- >search($i nput));
  1034           $i  = 0;
  1035                    fore ach($entri es as $key  => $val)  {
  1036                             if($th is->valid_ formatted_ address($v al['mail'] )) {
  1037                                      $contact _arr = arr ay('name'= >(isset($v al['displa yname'])?$ val['displ ayname']:" Undefined" ),'id'=>$v al['mail'] );
  1038                                      array_pu sh($result _arr,$cont act_arr);
  1039                                      $i++;
  1040                             }
  1041                    }
  1042  
  1043                    //so rt combine d result a rray (natu ral order,  case inse nsitive)
  1044                    usor t($result_ arr, funct ion( $el1,  $el2) { r eturn strn atcasecmp(  $el1['nam e'], $el2[ 'name']);  });
  1045  
  1046                    //ad d whatever  the user  is current ly typing  so that it  is allowe d as well
  1047                    if($ this->vali d_formatte d_address( $input)) {
  1048                             $conta ct_arr = a rray('name ' => $inpu t, 'id' =>  $input);
  1049                             array_ push($resu lt_arr,$co ntact_arr) ;
  1050                    }
  1051                    arra y_walk_rec ursive($re sult_arr,  function ( &$value) {
  1052                             $value  = htmlent ities($val ue);
  1053                    });
  1054                    retu rn $result _arr;
  1055           }
  1056  
  1057   ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// /////
  1058   // FORM VA LIDATION C ALLBACKS
  1059   // These a re current ly public  - iddeally , these sh ould be pr otected or  just adde d to the f orm valida tion libra ry so that  they can  be used th roughout t he applica tion
  1060   ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// ////////// //////
  1061  
  1062           pu blic funct ion allowe d_mailbox_ characters ($name) {
  1063                    $val id = (preg _match('/[ ^A-Za-z0-9 \'._-]/',  $name) ===  1) ? FALS E : TRUE;
  1064                    if($ valid) { r eturn TRUE ; }
  1065                    $thi s->form_va lidation-> set_messag e('allowed _mailbox_c haracters' , 'The %s  field may  only conta in alpha-n umeric cha racters (A -Z, a-z, 0 -9), under scores, pe riods, apo strophes,  and dashes .');
  1066                    retu rn FALSE;
  1067           }
  1068  
  1069           pu blic funct ion check_ password_s trength($p assword) {
  1070                    $val id = TRUE;
  1071                    $msg  = 'Passwo rd strengt h requirem ents not m et.<br />' ;
  1072                    if(s trlen($pas sword) < 1 5) {
  1073                             $msg . = 'Must be  at least  15 charact ers long.< br />';
  1074                             $valid  = FALSE;
  1075                    }
  1076                    if(! preg_match ("/[a-z]+/ ", $passwo rd)) {
  1077                             $msg . = 'Must co ntain at l east one l owercase c haracter.< br />';
  1078                             $valid  = FALSE;
  1079                    }
  1080                    if(! preg_match ("/[A-Z]+/ ", $passwo rd)) {
  1081                             $msg . = 'Must co ntain at l east one u ppercase c haracter.< br />';
  1082                             $valid  = FALSE;
  1083                    }
  1084                    if(! preg_match ("/[0-9]+/ ", $passwo rd)) {
  1085                             $msg . = 'Must co ntain at l east one n umeric cha racter.<br  />';
  1086                             $valid  = FALSE;
  1087                    }
  1088                    if(! preg_match ("/[!@#$%& *()_+|~=`{ }[:;'<>?,. \-\^\]\\\\ ]+/", $pas sword)) {  //four bac kslashes t o escape t he backsla sh once fo r PHP and  once for t he regex
  1089                             $msg . = 'Must co ntain at l east one s pecial cha racter.<br  />';
  1090                             $valid  = FALSE;
  1091                    }
  1092                    if(! $valid) {  $this->for m_validati on->set_me ssage('che ck_passwor d_strength ', $msg);  }
  1093                    retu rn $valid;
  1094           }
  1095  
  1096           /*  Form vali dation cal lback */
  1097           pu blic funct ion list_i s_unique($ name) {
  1098                    //if  we're edi ting, we c ould be us ing the pu blic list  model or t he deleted  list mode l.  otherw ise, it wi ll
  1099                    if(! isset($thi s->list_mo del))
  1100                             $this- >load->mod el('public _distribut ion_list_m odel', 'li st_model') ;
  1101  
  1102                    $thi s->form_va lidation-> set_messag e('list_is _unique',  'The %s fi eld must n ot match a ny existin g lists or  removed l ists.');
  1103  
  1104                    $nam e_is_avail able = $th is->list_m odel->name _is_availa ble($name) ;
  1105                    if($ name_is_av ailable) r eturn true ;
  1106  
  1107                    //if  we're edi ting (edit _distribut ion_list o r edit_rem oved_distr ibution_li st), check  to see if  the name  is being u sed by the  list we'r e editing
  1108                    if(s tring_begi ns_with('e dit', $thi s->router- >method) & & string_e nds_with(' distributi on_list',  $this->rou ter->metho d)){
  1109                             $list  = $this->l ist_model- >find_one( compact('n ame'));
  1110                             return  $list['id '] == $thi s->input-> post('list _id',TRUE) ;
  1111                    }
  1112  
  1113                    retu rn $name_i s_availabl e;
  1114           }
  1115  
  1116           pu blic funct ion va_ema il($email)  {
  1117                    $val id = (preg _match("/^ ([a-z0-9\' \+_\-]+)(\ .[a-z0-9\' \+_\-]+)*@ +((.*(\.va \.gov))|va \.gov)$/ix ", $email) ) ? TRUE :  FALSE;
  1118  
  1119                    if($ valid) { r eturn TRUE ; }
  1120                     $this->for m_validati on->set_me ssage('va_ email', 'T he %s fiel d must con tain a val id  DNS       email addr ess.');
  1121                    retu rn FALSE;
  1122           }
  1123  
  1124           pu blic funct ion valid_ trusted_ad dress($str ) {
  1125                    //ha ve to urle ncode / ba se64 encod e the addr ess to sen d to the w eb service
  1126                    $str  = rawurle ncode(base 64_encode( $str));
  1127                    $res ource = '/ direct/val idate/addr ess/'.$str .'/format/ json';
  1128                    $url  = WEBSERV ICE_URL .  $resource;
  1129  
  1130                    $hea ders = arr ay(
  1131                             'Autho rization:  DPII ' . W EBSERVICE_ PUBLIC_KEY  . ':'. ba se64_encod e(hash_hma c('sha256' ,"GET\n" .  date('U') . "\n" . $ resource,  WEBSERVICE _PRIVATE_K EY)),
  1132                             'Date:  ' . date( 'U'),
  1133                             );
  1134                    $ch  = curl_ini t();
  1135                    curl _setopt($c h,CURLOPT_ URL, $url) ;
  1136                    curl _setopt($c h, CURLOPT _RETURNTRA NSFER, tru e);
  1137                    curl _setopt($c h, CURLOPT _SSL_VERIF YPEER, fal se);
  1138                    curl _setopt($c h, CURLOPT _HTTPHEADE R,$headers );
  1139                    $ser ver_output  = curl_ex ec($ch);
  1140                    if($ server_out put === fa lse)
  1141                             trigge r_error( c url_error( $ch), E_US ER_WARNING );
  1142                    $htt p_status =  curl_geti nfo($ch, C URLINFO_HT TP_CODE);
  1143                    $res ponse = $t his->json- >decode($s erver_outp ut);
  1144                    if(i sset($resp onse->vali d)) {
  1145                             $valid  = $respon se->valid;
  1146                             if(!$v alid) { $t his->form_ validation ->set_mess age('valid _trusted_a ddress', ' The %s fie ld must be  a trusted  Direct Ad dress'); }
  1147                             return  $valid;
  1148                    }
  1149                    else  { $this-> form_valid ation->set _message(' valid_trus ted_addres s', 'The % s field mu st be a tr usted Dire ct Address '); return  FALSE; }
  1150           }
  1151  
  1152  
  1153   }
  1154   /* End of  file admin panel.php  */
  1155   /* Locatio n: ./appli cation/con trollers/a dminpanel. php */