187. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 5/25/2018 9:22:48 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.

187.1 Files compared

# Location File Last Modified
1 C:\AraxisMergeCompare\Pri_un\ZIP\DSM-cif\Direct_API\application\controllers Install.php Tue May 22 12:03:32 2018 UTC
2 C:\AraxisMergeCompare\Pri_re\ZIP\DSM-cif\Direct_API\application\controllers Install.php Tue May 22 22:09:38 2018 UTC

187.2 Comparison summary

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

187.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

187.4 Active regular expressions

No regular expressions were active.

187.5 Comparison detail

  1   <?php defi ned('BASEP ATH') OR e xit('No di rect scrip t access a llowed');
  2   /**
  3   * @package  direct-as -a-service
  4   * @subpack age contro llers
  5   *//** */
  6  
  7   /**
  8   * @package  direct-as -a-service
  9   * @subpack age contro llers
  10   */
  11   class Inst all extend s CI_Contr oller {
  12           va r $title =  'Configur ation Scri pt';
  13           
  14           // these are  set in the  construct or
  15           va r $databas es = array ();
  16           va r $databas e_schema =  array();
  17           va r $mail_da tabase_sch ema = arra y();
  18           va r $nhindco nfig_datab ase_schema  = array() ;
  19           va r $databas e_queries  = array();
  20           va r $databas e_table_qu eries = ar ray();
  21           va r $ldap_sc hema = arr ay();
  22           va r $ldap_ba se_domain  = '';
  23           
  24           // we pull ou r database  configura tion from  constants  and use it  like CI w ould,
  25           // but we don 't use the  CI Databa se class i n this ins tall scrip t due to t he difficu lty
  26           // in getting  useful er ror messag es when ru nning mult iple queri es, which  is necessa ry for cre ating the  tables
  27           va r $db_requ ired_permi ssions = a rray('db_d atareader'  => FALSE,  'db_dataw riter' =>  FALSE);
  28           va r $databas e_serverna me = DATAB ASE_HOSTNA ME;
  29           va r $databas e_config =  array (
  30                                                                                  'UID'                              => DAT ABASE_USER NAME,
  31                                                                                  'PWD'                              => DAT ABASE_PASS WORD,
  32                                                                                  'Databas e'                        => 'ma ster',
  33                                                                                  'Connect ionPooling ' => 0,
  34                                                                                  'ReturnD atesAsStri ngs' => 1,
  35                                                                                  'LoginTi meout' =>  5,
  36                                                                           );
  37                                                                           
  38           pu blic funct ion __cons truct(){
  39                    glob al $instal ler;
  40                    $ins taller = T RUE;
  41                    pare nt::__cons truct();
  42                    
  43                    requ ire_models ('mailbox' );
  44           
  45                    $thi s->config- >set_item( 'sess_use_ database',  FALSE);
  46                    $thi s->config- >set_item( 'sess_encr ypt_cookie ', FALSE);
  47                    $thi s->load->l ibrary(arr ay('sessio n','encryp t'));
  48                    $thi s->load->h elper('url ');
  49                    
  50                    //fo r now the  tables wil l be creat ed in the  order they  are put i n this arr ay,
  51                    //ke ep that in  mind when  setting u p foreign  key relati ons, etc.
  52                    //TO -DO: Inclu de array s orting fun ction for  preferred  creation o rder
  53                    $thi s->databas e_schema =   array( 
  54                                                                                  'users'  =>      ar ray(
  55                                                                                                                     'user_ id' => 'bi gint',
  56                                                                                                                     'usern ame' => 'n varchar(50 )',
  57                                                                                                                     'user_ org_id' =>  'bigint',
  58                                                                                                                     'user_ created_ti me' => 'bi gint',
  59                                                                                                                     'user_ ext_mail'  => 'nvarch ar(max)',
  60                                                                                                                     'user_ ep' => 'nv archar(max )',
  61                                                                                                            ),
  62                                                                                  'account _request'  => array(
  63                                                                                                                     'id' = > 'bigint' ,
  64                                                                                                                     'usern ame' => 'n varchar(10 0)',
  65                                                                                                                     'user_ org_id' =>  'bigint',
  66                                                                                                                     'first _name' =>  'nvarchar( 100)',
  67                                                                                                                     'middl e_name' =>  'nvarchar (100)',
  68                                                                                                                     'last_ name' => ' nvarchar(1 00)',
  69                                                                                                                     'ext_m ail' => 'n varchar(20 0)',
  70                                                                                                                     'title ' => 'nvar char(300)' ,
  71                                                                                                                     'depar tment' =>  'nvarchar( 300)',
  72                                                                                                                     'organ ization' = > 'nvarcha r(300)',
  73                                                                                                                     'locat ion' => 'n varchar(50 0)',
  74                                                                                                                     'facil ity_id' =>  'bigint',
  75                                                                                                                     'telep hone' => ' nvarchar(1 00)',
  76                                                                                                                     'mobil e' => 'nva rchar(100) ',
  77                                                                                                                     'reque st_date' = > 'bigint' ,
  78                                                                                                                     'appro ved_date'  => 'bigint ',
  79                                                                                                                     'justi fication'  => 'nvarch ar(4000)',
  80                                                                                                                     'denie d' => 'tin yint',
  81                                                                                                                     'domai n' => 'nva rchar(253) ',
  82                                                                                                                              
  83                                                                                                            ),
  84                                                                                  'applica tion' =>         arra y(
  85                                                                                                                                       'id' => 'b igint',
  86                                                                                                                                       'name' =>  'nvarchar( 100)',
  87                                                                                                                                       'public_ke y' => 'nva rchar(100) ',
  88                                                                                                                                       'private_k ey' => 'nv archar(100 )',
  89                                                                                                                                       'url' => ' nvarchar(1 000)',
  90                                                                                                                                       'descripti on' => 'nv archar(400 0)',
  91                                                                                                                                       'poc_name'  => 'nvarc har(500)',
  92                                                                                                                                       'poc_email ' => 'nvar char(100)' ,
  93                                                                                                                                       'poc_phone ' => 'nvar char(20)',
  94                                                                                                                                       'app_reque st_id' =>  'bigint'
  95                                                                                                                              ),
  96                                                                                  'applica tion_accou nt_link'       =>       array(
  97                                                                                                                                                                 'id' = > 'bigint' ,
  98                                                                                                                                                                 'app_i d' => 'big int',
  99                                                                                                                                                                 'uniqu e_id' => ' nvarchar(6 4)',
  100                                                                                                                                                                 'creat ed_at' =>  'bigint',
  101                                                                                                                                                                 'org_i d' => 'big int',
  102                                                                                                                                                                 'syste m_permissi ons' => 'n varchar(10 0)'
  103                                                                                                                                                        ),
  104                                                                                  'applica tion_reque st' =>         array(
  105                                                                                                                                                        'id'  => 'bigin t',
  106                                                                                                                                                        'nam e' => 'nva rchar(100) ',
  107                                                                                                                                                        'req uestor' =>  'bigint',
  108                                                                                                                                                        'url ' => 'nvar char(1000) ',
  109                                                                                                                                                        'des cription'  => 'nvarch ar(4000)',
  110                                                                                                                                                        'poc _name' =>  'nvarchar( 500)',
  111                                                                                                                                                        'poc _email' =>  'nvarchar (100)',
  112                                                                                                                                                        'poc _phone' =>  'nvarchar (20)',
  113                                                                                                                                                        'req uested_dat e' => 'big int',
  114                                                                                                                                                        'app roved_date ' => 'bigi nt',
  115                                                                                                                                                        'jus tification ' => 'nvar char(4000) ',
  116                                                                                                                                                        'den ial_reason ' => 'nvar char(4000) ',
  117                                                                                                                                                        'den ied' => 't inyint',
  118                                                                                                                                               ),
  119                                                                                  'event_l og'     =>       arra y(
  120                                                                                                                              'id' =>  'bigint',
  121                                                                                                                              'target_ type' => ' int',
  122                                                                                                                              'target_ id' => 'bi gint',
  123                                                                                                                              'actor_t ype' => 'i nt',
  124                                                                                                                              'actor_i d' => 'big int',
  125                                                                                                                              'action'  => 'nvarc har(max)',
  126                                                                                                                              'event_d ate' => 'b igint',
  127                                                                                                                              'success ' => 'tiny int',
  128                                                                                                                     ),
  129                                                                                  'facilit y' =>   ar ray(
  130                                                                                                                              'id' =>  'bigint',
  131                                                                                                                              'name' = > 'nvarcha r(400)',
  132                                                                                                                              'active'  => 'tinyi nt',
  133                                                                                                                     ),
  134                                                                                  'logins'  =>     ar ray(
  135                                                                                                                     'id' = > 'bigint' ,
  136                                                                                                                     'sessi on_id' =>  'nvarchar( 50)',
  137                                                                                                                     'ip_ad dress' =>  'nvarchar( 50)',
  138                                                                                                                     'login _time' =>  'bigint',
  139                                                                                                                     'succe ss' => 'ti nyint',
  140                                                                                                                     'error _msg' => ' nvarchar(m ax)',
  141                                                                                                                     'org_i d' => 'big int',
  142                                                                                                            ),
  143                                                                                  'mail_lo g' =>   ar ray(
  144                                                                                                                              'id' =>  'bigint',
  145                                                                                                                              'time' = > 'bigint' ,
  146                                                                                                                              'size' = > 'bigint' ,
  147                                                                                                                              'sender'  => 'nvarc har(max)',
  148                                                                                                                              'recipie nt' => 'nv archar(max )',
  149                                                                                                                              'attachm ent_types'  => 'nvarc har(max)',
  150                                                                                                                              'success ' => 'tiny int',
  151                                                                                                                              'inbound _outbound'  => 'tinyi nt',
  152                                                                                                                              'mdn' =>  'tinyint' ,
  153                                                                                                                              'protect ed_data' = > 'tinyint ',
  154                                                                                                                              'storage _id' => 'b igint',
  155                                                                                                                     ),
  156                                                                                  'mailbox _settings'  =>   arra y(
  157                                                                                                                                               'i d' => 'big int',
  158                                                                                                                                               'm ailbox_id'  => 'bigin t',
  159                                                                                                                                               'a pplication _id' => 'b igint',
  160                                                                                                                                               'w eb_service _id' => 'b igint',
  161                                                                                                                                               'a uthorized'  => 'tinyi nt',
  162                                                                                                                                       ),
  163                                                                                  'request ' =>    ar ray(
  164                                                                                                                              'id' =>  'bigint',
  165                                                                                                                              'applica tion_id' = > 'bigint' ,
  166                                                                                                                              'call' = > 'nvarcha r(max)',
  167                                                                                                                              'call_da te' => 'bi gint',
  168                                                                                                                              'respons e_code' =>  'int',
  169                                                                                                                              'respons e' => 'nva rchar(max) ',
  170                                                                                                                     ),
  171                                                                                  'ticket_ category'  =>    arra y(
  172                                                                                                                                               'i d' => 'big int',
  173                                                                                                                                               'c ategory' = > 'nvarcha r(200)',
  174                                                                                                                                       ),
  175                                                                                  'tickets ' =>    ar ray(
  176                                                                                                                              'id' =>  'bigint',
  177                                                                                                                              'parent_ id' => 'bi gint',
  178                                                                                                                              'user_id ' => 'bigi nt',
  179                                                                                                                              'message ' => 'nvar char(4000) ',
  180                                                                                                                              'open_da te' => 'bi gint',
  181                                                                                                                              'close_d ate' => 'b igint',
  182                                                                                                                              'categor y_id' => ' bigint',
  183                                                                                                                     ),
  184                                                                                  'web_ser vices' =>        arra y(
  185                                                                                                                                       'id' => 'b igint',
  186                                                                                                                                       'name' =>  'nvarchar( 200)',
  187                                                                                                                                       'descripti on' => 'nv archar(400 0)',
  188                                                                                                                              ),
  189                                                                                  'role_pe rmissions'  =>   arra y(
  190                                                                                                                                               'i d' => 'big int',
  191                                                                                                                                               'r ole_name'  => 'nvarch ar(150)',
  192                                                                                                                                               'p ermission_ id' => 'bi gint',
  193                                                                                                                              ),
  194                                                                                  'permiss ions' =>         arra y(
  195                                                                                                                                               'i d' => 'big int',
  196                                                                                                                                               'n ame' => 'n varchar(10 0)',
  197                                                                                                                                               'p arent_id'  => 'bigint ',
  198                                                                                                                              ),
  199                                                                                  'adhoc_r eports' =>       arra y(
  200                                                                                                                                       'report_id ' => 'bigi nt',
  201                                                                                                                                       'report_ty pe' => 'nv archar(100 )',
  202                                                                                                                                       'report_na me' => 'nv archar(50) ',
  203                                                                                                                                       'report_de scription'  => 'nvarc har(max)',
  204                                                                                                                                       'report_cr eated_by'  => 'nvarch ar(max)',
  205                                                                                                                                       'report_ac cess_type'  => 'nvarc har(50)',
  206                                                                                                                                       'report_cr eated_time ' => 'bigi nt',
  207                                                                                                                                       'report_qu ery_genera tor' => 'n varchar(ma x)',
  208                                                                                                                                       'report_or der_by' =>  'nvarchar (max)',
  209                                                                                                                                       'report_or der_by_dir ection' =>  'nvarchar (100)',
  210                                                                                                                                       'report_ti me_period'  => 'nvarc har(200)',
  211                                                                                                                                       'report_st atus' => ' nvarchar(m ax)',
  212                                                                                                                                       'report_en d_date' =>  'nvarchar (max)',
  213                                                                                                                                       'report_st art_date'  => 'nvarch ar(max)',
  214                                                                                                                                       'report_se lector' =>  'nvarchar (max)',
  215                                                                                                                                       'report_ti me_field'  => 'nvarch ar(200)',
  216                                                                                                                              ),
  217                                                                                  'adhoc_r eports_acc ess' =>        array(
  218                                                                                                                                                        'rep ort_access _id' => 'b igint',
  219                                                                                                                                                        'rep ort_id' =>  'bigint',
  220                                                                                                                                                        'use r_id' => ' bigint',
  221                                                                                                                                                        'tim e' => 'big int',
  222                                                                                                                                               ),
  223                                                                                  'das_log _entries'  =>    arra y(
  224                                                                                                                                       'id' => 'b igint',
  225                                                                                                                                       'saved_dat e' => 'big int',
  226                                                                                                                                       'result_st atus' => ' nchar(10)' ,
  227                                                                                                                                       'attachmen t_name' =>  'nvarchar (max)',
  228                                                                                                                                       'hash_atta chment_nam e' => 'nva rchar(512) ',
  229                                                                                                                                       'das_docum ent_id' =>  'nvarchar (max)',
  230                                                                                                                                       'message_i d' => 'big int',
  231                                                                                                                              ),
  232                                                                                  );
  233                    $thi s->mail_da tabase_sch ema =  arr ay(
  234                                                                                                   'm ailboxes'  => array(
  235                                                                                                            'id'  => 'bigin t',
  236                                                                                                            'nam e' => 'nva rchar(100) ',
  237                                                                                                            'is_ group' =>  'tinyint',
  238                                                                                                            'is_ active' =>  'tinyint' ,
  239                                                                                                            'fac ility_id'  => 'bigint ',
  240                                                                                                            'dom ain' => 'n varchar(25 3)',
  241                                                                                                   ),
  242                                                                                                   'f olders' =>  array(
  243                                                                                                            'id'  => 'bigin t',
  244                                                                                                            'nam e' => 'nva rchar(200) ',
  245                                                                                                            'mai lbox_id' = > 'bigint' ,
  246                                                                                                            'par ent_id' =>  'bigint',
  247                                                                                                   ),
  248                                                                                                   'm essages' = > array(
  249                                                                                                            'id'  => 'bigin t',
  250                                                                                                            'rec ipients' = > 'nvarcha r(max)',
  251                                                                                                            'sen der' => 'n varchar(ma x)',
  252                                                                                                            'ori ginal_send er_id' =>  'bigint',
  253                                                                                                            'to'  => 'nvarc har(max)',
  254                                                                                                            'cc'  => 'nvarc har(max)',
  255                                                                                                            'bcc ' => 'nvar char(max)' ,
  256                                                                                                            'att achments'  => 'nvarch ar(max)',
  257                                                                                                            'sub ject' => ' nvarchar(m ax)',
  258                                                                                                            'pla in' => 'nv archar(max )',
  259                                                                                                            'htm l' => 'nva rchar(max) ',
  260                                                                                                            'tim estamp' =>  'bigint',
  261                                                                                                            'fol der_id' =>  'bigint',
  262                                                                                                            'siz e' => 'big int',
  263                                                                                                            'fla gs' => 'nv archar(max )',
  264                                                                                                            'hea ders' => ' nvarchar(m ax)',
  265                                                                                                            'raw _mime' =>  'nvarchar( max)',
  266                                                                                                            'see n' => 'tin yint',
  267                                                                                                            'sen t' => 'tin yint',
  268                                                                                                            'arc hived' =>  'tinyint',
  269                                                                                                            'mes sage_id' = > 'nvarcha r(max)',
  270                                                                                                            'mai lbox_id' = > 'bigint' ,
  271                                                                                                            'mai ltype' =>  'nvarchar( 4)',
  272                                                                                                            'pri ority' =>  'tinyint',
  273                                                                                                            'pro tected_dat a' => 'tin yint',
  274                                                                                                            'is_ automated'  => 'bit',
  275                                                                                                            'non _va_referr al' => 'ti nyint' 
  276                                                                                                   ),
  277                                                                                                   'm essage_sta tus' => ar ray(
  278                                                                                                            'id'  => 'bigin t',
  279                                                                                                            'mes sage_id' = > 'nvarcha r(max)',
  280                                                                                                            'sta tus_code'  => 'tinyin t',
  281                                                                                                            'rec ipient' =>  'nvarchar (max)',
  282                                                                                                            'tim estamp' =>  'bigint',
  283                                                                                                   ),
  284                                                                                                   'p atients' = > array(
  285                                                                                                            'id'  => 'bigin t',
  286                                                                                                            'mes sage_id' = > 'bigint' ,
  287                                                                                                            'giv en_name' = > 'nvarcha r(max)',
  288                                                                                                            'fam ily_name'  => 'nvarch ar(max)',
  289                                                                                                            'dat e_of_birth ' => 'bigi nt',
  290                                                                                                            'tit le' => 'nv archar(max )',
  291                                                                                                            'org anization'  => 'nvarc har(max)',
  292                                                                                                            'fil e_hash' =>  'nvarchar (60)',
  293                                                                                                            'doc ument_name ' => 'nvar char(255)'                                                                                                        
  294                                                                                                   ),
  295                                                                                                   'a ccounting_ disclosure ' => array (
  296                                                                                                                     'id' = > 'bigint' ,
  297                                                                                                                     'messa ges_table_ id' => 'bi gint',
  298                                                                                                                     'messa ge_id' =>  'nvarchar( max)',
  299                                                                                                                     'recip ient' => ' nvarchar(m ax)',
  300                                                                                                                     'first ' => 'nvar char(max)' ,
  301                                                                                                                     'last'  => 'nvarc har(max)',
  302                                                                                                                     'discl osed' => ' bigint',
  303                                                                                                                     'recei ved' => 'b igint',
  304                                                                                                                     'title ' => 'nvar char(max)' ,
  305                                                                                                                     'sent_ to' => 'nv archar(max )',
  306                                                                                                                     'recei ved_from'  => 'nvarch ar(max)',
  307                                                                                                                     'usern ame' => 'n varchar(10 0)',
  308                                                                                                                     'facil ity' => 'n varchar(ma x)',
  309                                                                                                                     'purpo se' => 'nv archar(max )',
  310                                                                                                                     'ssn'  => 'bigint ',
  311                                                                                                                     'hash'  => 'nchar (40)',
  312                                                                                                                     'patie nt_id' =>  'nvarchar( 50)',
  313                                                                                                   ),
  314                                                                                                   'a utomatic_r eplies' =>  array(
  315                                                                                                                     'id' = > 'bigint' ,
  316                                                                                                                     'mailb ox_id' =>  'bigint',
  317                                                                                                                     'start _at' => 'b igint',
  318                                                                                                                     'end_a t' => 'big int',
  319                                                                                                                     'conte nt' => 'nv archar(max )',
  320                                                                                                                     'updat ed_at' =>  'bigint'
  321                                                                                                   ),
  322                                                                                                   'a utomatic_r eply_log'  => array(
  323                                                                                                                     'id' = > 'bigint' ,
  324                                                                                                                     'autom atic_reply _id' => 'b igint',
  325                                                                                                                     'email _address'  => 'nvarch ar(max)',
  326                                                                                                                     'sent_ at' => 'bi gint'
  327                                                                                                   ),
  328                                                                                                   'f ile_transf ers' => ar ray(
  329                                                                                                            'id'  => 'bigin t',
  330                                                                                                            'nam e' => 'nva rchar(260) ',
  331                                                                                                            'typ e' => 'nva rchar(255) ', 
  332                                                                                                            'siz e' => 'big int',
  333                                                                                                            'has h' => 'nch ar(40)',
  334                                                                                                            'con tent' => ' varbinary( max)',
  335                                                                                                            'pas scode' =>  'nvarchar( 15)', 
  336                                                                                                            'rec ipient' =>  'nvarchar (255)',
  337                                                                                                            'mes sage_id' = > 'bigint' ,
  338                                                                                                            'not e' => 'nva rchar',
  339                                                                                                            'not ify_on_dow nload' =>  'bit',
  340                                                                                                            'upl oad_progre ss' => 'ti nyint',
  341                                                                                                            'dow nloaded_by ' => 'bigi nt',
  342                                                                                                            'dow nloaded_by _ip' => 'n varchar(39 )',
  343                                                                                                            'dow nloaded_at ' => 'bigi nt',
  344                                                                                                            'cre ated_by' = > 'bigint' ,
  345                                                                                                            'cre ated_at' = > 'bigint' ,
  346                                                                                                            'mod ified_by'  => 'bigint ',
  347                                                                                                            'mod ified_at'  => 'bigint ',
  348                                                                                                   ),
  349                                                                                           );
  350                    $thi s->nhindco nfig_datab ase_schema  = array (
  351                                                                                                            'mai let_proper ties' => a rray(
  352                                                                                                                                                                          'name' = > 'varchar (50)',
  353                                                                                                                                                                          'value'  => 'varcha r(max)',
  354                                                                                                                                                                 ),
  355                                                                                                   );
  356                    $thi s->databas e_queries  = array(
  357                                                                                  'create_ ' . DATABA SE_NAME =>     "
  358                                                                                                                                                        USE  [master];
  359                                                                                                                                                        IF N OT EXISTS( SELECT nam e FROM mas ter.sys.da tabases WH ERE name =  N'api')
  360                                                                                                                                                        BEGI N
  361                                                                                                                                                        CREA TE DATABAS E [api]
  362                                                                                                                                                        ALTE R DATABASE  [api] SET  COMPATIBI LITY_LEVEL  = 100
  363  
  364                                                                                                                                                        IF ( 1 = FULLTE XTSERVICEP ROPERTY('I sFullTextI nstalled') )
  365                                                                                                                                                        BEGI N
  366                                                                                                                                                        EXEC  [api].[db o].[sp_ful ltext_data base] @act ion = 'ena ble'
  367                                                                                                                                                        END
  368                                                                                                                                                        ALTE R DATABASE  [api] SET  ANSI_NULL _DEFAULT O FF 
  369                                                                                                                                                        ALTE R DATABASE  [api] SET  ANSI_NULL S OFF 
  370                                                                                                                                                        ALTE R DATABASE  [api] SET  ANSI_PADD ING OFF 
  371                                                                                                                                                        ALTE R DATABASE  [api] SET  ANSI_WARN INGS OFF 
  372                                                                                                                                                        ALTE R DATABASE  [api] SET  ARITHABOR T OFF 
  373                                                                                                                                                        ALTE R DATABASE  [api] SET  AUTO_CLOS E OFF 
  374                                                                                                                                                        ALTE R DATABASE  [api] SET  AUTO_CREA TE_STATIST ICS ON 
  375                                                                                                                                                        ALTE R DATABASE  [api] SET  AUTO_SHRI NK OFF 
  376                                                                                                                                                        ALTE R DATABASE  [api] SET  AUTO_UPDA TE_STATIST ICS ON 
  377                                                                                                                                                        ALTE R DATABASE  [api] SET  CURSOR_CL OSE_ON_COM MIT OFF 
  378                                                                                                                                                        ALTE R DATABASE  [api] SET  CURSOR_DE FAULT  GLO BAL 
  379                                                                                                                                                        ALTE R DATABASE  [api] SET  CONCAT_NU LL_YIELDS_ NULL OFF 
  380                                                                                                                                                        ALTE R DATABASE  [api] SET  NUMERIC_R OUNDABORT  OFF 
  381                                                                                                                                                        ALTE R DATABASE  [api] SET  QUOTED_ID ENTIFIER O FF 
  382                                                                                                                                                        ALTE R DATABASE  [api] SET  RECURSIVE _TRIGGERS  OFF 
  383                                                                                                                                                        ALTE R DATABASE  [api] SET   DISABLE_ BROKER 
  384                                                                                                                                                        ALTE R DATABASE  [api] SET  AUTO_UPDA TE_STATIST ICS_ASYNC  OFF 
  385                                                                                                                                                        ALTE R DATABASE  [api] SET  DATE_CORR ELATION_OP TIMIZATION  OFF 
  386                                                                                                                                                        ALTE R DATABASE  [api] SET  TRUSTWORT HY OFF 
  387                                                                                                                                                        ALTE R DATABASE  [api] SET  ALLOW_SNA PSHOT_ISOL ATION OFF 
  388                                                                                                                                                        ALTE R DATABASE  [api] SET  PARAMETER IZATION SI MPLE 
  389                                                                                                                                                        ALTE R DATABASE  [api] SET  READ_COMM ITTED_SNAP SHOT OFF 
  390                                                                                                                                                        ALTE R DATABASE  [api] SET  HONOR_BRO KER_PRIORI TY OFF 
  391                                                                                                                                                        ALTE R DATABASE  [api] SET   READ_WRI TE 
  392                                                                                                                                                        ALTE R DATABASE  [api] SET  RECOVERY  FULL 
  393                                                                                                                                                        ALTE R DATABASE  [api] SET   MULTI_US ER
  394                                                                                                                                                        ALTE R DATABASE  [api] SET  PAGE_VERI FY CHECKSU M  
  395                                                                                                                                                        ALTE R DATABASE  [api] SET  DB_CHAINI NG OFF
  396                                                                                                                                                        END
  397                                                                                                                                                        ",
  398                                                                                  'create_ ' . MAIL_D ATABASE_NA ME => "
  399                                                                                                                                                        USE  [master];
  400                                                                                                                                                        IF N OT EXISTS( SELECT nam e FROM mas ter.sys.da tabases WH ERE name =  N'mail')
  401                                                                                                                                                        BEGI N
  402                                                                                                                                                        CREA TE DATABAS E [mail]
  403                                                                                                                                                        ALTE R DATABASE  [mail] SE T COMPATIB ILITY_LEVE L = 100
  404  
  405                                                                                                                                                        IF ( 1 = FULLTE XTSERVICEP ROPERTY('I sFullTextI nstalled') )
  406                                                                                                                                                        BEGI N
  407                                                                                                                                                        EXEC  [mail].[d bo].[sp_fu lltext_dat abase] @ac tion = 'en able'
  408                                                                                                                                                        END
  409                                                                                                                                                        ALTE R DATABASE  [mail] SE T ANSI_NUL L_DEFAULT  OFF 
  410                                                                                                                                                        ALTE R DATABASE  [mail] SE T ANSI_NUL LS OFF 
  411                                                                                                                                                        ALTE R DATABASE  [mail] SE T ANSI_PAD DING OFF 
  412                                                                                                                                                        ALTE R DATABASE  [mail] SE T ANSI_WAR NINGS OFF 
  413                                                                                                                                                        ALTE R DATABASE  [mail] SE T ARITHABO RT OFF 
  414                                                                                                                                                        ALTE R DATABASE  [mail] SE T AUTO_CLO SE OFF 
  415                                                                                                                                                        ALTE R DATABASE  [mail] SE T AUTO_CRE ATE_STATIS TICS ON 
  416                                                                                                                                                        ALTE R DATABASE  [mail] SE T AUTO_SHR INK OFF 
  417                                                                                                                                                        ALTE R DATABASE  [mail] SE T AUTO_UPD ATE_STATIS TICS ON 
  418                                                                                                                                                        ALTE R DATABASE  [mail] SE T CURSOR_C LOSE_ON_CO MMIT OFF 
  419                                                                                                                                                        ALTE R DATABASE  [mail] SE T CURSOR_D EFAULT  GL OBAL 
  420                                                                                                                                                        ALTE R DATABASE  [mail] SE T CONCAT_N ULL_YIELDS _NULL OFF 
  421                                                                                                                                                        ALTE R DATABASE  [mail] SE T NUMERIC_ ROUNDABORT  OFF 
  422                                                                                                                                                        ALTE R DATABASE  [mail] SE T QUOTED_I DENTIFIER  OFF 
  423                                                                                                                                                        ALTE R DATABASE  [mail] SE T RECURSIV E_TRIGGERS  OFF 
  424                                                                                                                                                        ALTE R DATABASE  [mail] SE T  DISABLE _BROKER 
  425                                                                                                                                                        ALTE R DATABASE  [mail] SE T AUTO_UPD ATE_STATIS TICS_ASYNC  OFF 
  426                                                                                                                                                        ALTE R DATABASE  [mail] SE T DATE_COR RELATION_O PTIMIZATIO N OFF 
  427                                                                                                                                                        ALTE R DATABASE  [mail] SE T TRUSTWOR THY OFF 
  428                                                                                                                                                        ALTE R DATABASE  [mail] SE T ALLOW_SN APSHOT_ISO LATION OFF  
  429                                                                                                                                                        ALTE R DATABASE  [mail] SE T PARAMETE RIZATION S IMPLE 
  430                                                                                                                                                        ALTE R DATABASE  [mail] SE T READ_COM MITTED_SNA PSHOT OFF 
  431                                                                                                                                                        ALTE R DATABASE  [mail] SE T HONOR_BR OKER_PRIOR ITY OFF 
  432                                                                                                                                                        ALTE R DATABASE  [mail] SE T  READ_WR ITE 
  433                                                                                                                                                        ALTE R DATABASE  [mail] SE T RECOVERY  FULL 
  434                                                                                                                                                        ALTE R DATABASE  [mail] SE T  MULTI_U SER
  435                                                                                                                                                        ALTE R DATABASE  [mail] SE T PAGE_VER IFY CHECKS UM  
  436                                                                                                                                                        ALTE R DATABASE  [mail] SE T DB_CHAIN ING OFF
  437                                                                                                                                                        END
  438                                                                                                                                                        ",
  439                                                                                  'encrypt _'.MAIL_DA TABASE_NAM E =>         "
  440                                                                                                                                                                 USE [m aster]
  441                                                                                                                                                                 IF (se lect Count (*) from s ys.symmetr ic_keys wh ere name l ike '%Data baseMaster Key%') = 0
  442                                                                                                                                                                 BEGIN
  443                                                                                                                                                                 create  master ke y encrypti on by pass word = '". $this->con fig->item( 'encryptio n_key')."' ;
  444                                                                                                                                                                 END
  445  
  446                                                                                                                                                                 IF (se lect Count (*) from s ys.certifi cates wher e name = ' TDE_Certif icate') =  0
  447                                                                                                                                                                 BEGIN
  448                                                                                                                                                                 create  certifica te TDE_Cer tificate w ith subjec t = 'Datab ase TDE ce rtificate' ;
  449                                                                                                                                                                 END
  450  
  451                                                                                                                                                                 IF (se lect Count (*) from s ys.certifi cates wher e name = ' TDE_Certif icate') >  0
  452                                                                                                                                                                 BEGIN
  453                                                                                                                                                                 USE [m ail]
  454                                                                                                                                                                 CREATE  DATABASE  ENCRYPTION  KEY
  455                                                                                                                                                                 WITH A LGORITHM =  AES_256
  456                                                                                                                                                                 ENCRYP TION BY SE RVER CERTI FICATE TDE _Certifica te
  457                                                                                                                                                                 ALTER  DATABASE m ail SET EN CRYPTION O N
  458                                                                                                                                                                 END
  459                                                                                                                                                                 ",
  460                                                                                  'create_ nhindconfi g' =>          "
  461                                                                                                                                                        USE  [master];
  462                                                                                                                                                        IF N OT EXISTS( SELECT nam e FROM mas ter.sys.da tabases WH ERE name =  N'nhindco nfig')
  463                                                                                                                                                        BEGI N
  464                                                                                                                                                        CREA TE DATABAS E [nhindco nfig]
  465                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET C OMPATIBILI TY_LEVEL =  100
  466  
  467                                                                                                                                                        IF ( 1 = FULLTE XTSERVICEP ROPERTY('I sFullTextI nstalled') )
  468                                                                                                                                                        BEGI N
  469                                                                                                                                                        EXEC  [nhindcon fig].[dbo] .[sp_fullt ext_databa se] @actio n = 'enabl e'
  470                                                                                                                                                        END
  471                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET A NSI_NULL_D EFAULT OFF  
  472                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET A NSI_NULLS  OFF 
  473                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET A NSI_PADDIN G OFF 
  474                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET A NSI_WARNIN GS OFF 
  475                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET A RITHABORT  OFF 
  476                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET A UTO_CLOSE  OFF 
  477                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET A UTO_CREATE _STATISTIC S ON 
  478                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET A UTO_SHRINK  OFF 
  479                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET A UTO_UPDATE _STATISTIC S ON 
  480                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET C URSOR_CLOS E_ON_COMMI T OFF 
  481                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET C URSOR_DEFA ULT  GLOBA
  482                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET C ONCAT_NULL _YIELDS_NU LL OFF 
  483                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET N UMERIC_ROU NDABORT OF
  484                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET Q UOTED_IDEN TIFIER OFF  
  485                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET R ECURSIVE_T RIGGERS OF
  486                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET   DISABLE_BR OKER 
  487                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET A UTO_UPDATE _STATISTIC S_ASYNC OF
  488                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET D ATE_CORREL ATION_OPTI MIZATION O FF 
  489                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET T RUSTWORTHY  OFF 
  490                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET A LLOW_SNAPS HOT_ISOLAT ION OFF 
  491                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET P ARAMETERIZ ATION SIMP LE 
  492                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET R EAD_COMMIT TED_SNAPSH OT OFF 
  493                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET H ONOR_BROKE R_PRIORITY  OFF 
  494                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET   READ_WRITE  
  495                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET R ECOVERY FU LL 
  496                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET   MULTI_USER
  497                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET P AGE_VERIFY  CHECKSUM   
  498                                                                                                                                                        ALTE R DATABASE  [nhindcon fig] SET D B_CHAINING  OFF
  499                                                                                                                                                        END
  500                                                                                                                                                        ",
  501                                                                          );
  502                    $thi s->databas e_table_qu eries = ar ray(
  503                                                                                  DATABASE _NAME => a rray(
  504                                                                                           'create_us ers' =>        "
  505                                                                                                                                       USE [".DAT ABASE_NAME ."]
  506                                                                                                                                       IF NOT EXI STS (SELEC T * FROM s ys.objects  WHERE obj ect_id = O BJECT_ID(N '[dbo].[us ers]') AND  type in ( N'U'))
  507                                                                                                                                       BEGIN
  508                                                                                                                                       CREATE TAB LE [dbo].[ users](
  509                                                                                                                                               [u ser_id] [b igint] IDE NTITY(1,1)  NOT NULL,
  510                                                                                                                                               [u sername] [ varchar](5 0) NOT NUL L,
  511                                                                                                                                               [u ser_org_id ] [bigint]  NOT NULL,
  512                                                                                                                                               [u ser_create d_time] [b igint] NOT  NULL,
  513                                                                                                                                               [u ser_ext_ma il] [nvarc har](max)  NULL,
  514                                                                                                                                               [u ser_ep] [n varchar](m ax) NOT NU LL,
  515                                                                                                                                       PRIMARY KE Y CLUSTERE D ([user_i d] ASC)
  516                                                                                                                                       WITH (PAD_ INDEX  = O FF, STATIS TICS_NOREC OMPUTE  =  OFF, IGNOR E_DUP_KEY  = OFF, ALL OW_ROW_LOC KS  = ON,  ALLOW_PAGE _LOCKS  =  ON) ON [PR IMARY]) ON  [PRIMARY]                    
  517                                                                                                                                       ALTER TABL E [dbo].[u sers] ADD  CONSTRAINT  [unique_u ser_org_id ] UNIQUE N ONCLUSTERE D ([user_o rg_id])
  518                                                                                                                                       END
  519                                                                                                                                       ",
  520                                                                                           'create_ap plication_ request' = >          "
  521                                                                                                                                                                 USE [" .DATABASE_ NAME."]
  522                                                                                                                                                                 IF NOT  EXISTS (S ELECT * FR OM sys.obj ects WHERE  object_id  = OBJECT_ ID(N'[dbo] .[applicat ion_reques t]') AND t ype in (N' U'))
  523                                                                                                                                                                 CREATE  TABLE [db o].[applic ation_requ est](
  524                                                                                                                                                                          [id] [bi gint] IDEN TITY(1,1)  NOT NULL,
  525                                                                                                                                                                          [name] [ varchar](1 00) NULL,
  526                                                                                                                                                                          [request or] [bigin t] NOT NUL L,
  527                                                                                                                                                                          [url] [v archar](10 00) NULL,
  528                                                                                                                                                                          [descrip tion] [var char](4000 ) NULL,
  529                                                                                                                                                                          [poc_nam e] [varcha r](500) NU LL,
  530                                                                                                                                                                          [poc_ema il] [varch ar](100) N ULL,
  531                                                                                                                                                                          [poc_pho ne] [varch ar](20) NU LL,
  532                                                                                                                                                                          [request ed_date] [ bigint] NU LL,
  533                                                                                                                                                                          [approve d_date] [b igint] NUL L,
  534                                                                                                                                                                          [justifi cation] [v archar](40 00) NULL,
  535                                                                                                                                                                          [denial_ reason] [v archar](40 00) NULL,
  536                                                                                                                                                                          [denied]  [tinyint]  NULL,
  537                                                                                                                                                                 PRIMAR Y KEY CLUS TERED ([id ] ASC)
  538                                                                                                                                                                 WITH ( PAD_INDEX   = OFF, ST ATISTICS_N ORECOMPUTE   = OFF, I GNORE_DUP_ KEY = OFF,  ALLOW_ROW _LOCKS  =  ON, ALLOW_ PAGE_LOCKS   = ON) ON  [PRIMARY] ) ON [PRIM ARY]
  539  
  540                                                                                                                                                                 IF  NO T EXISTS ( SELECT * F ROM sys.fo reign_keys  WHERE obj ect_id = O BJECT_ID(N '[dbo].[FK _applicati on_request _users]')  AND parent _object_id  = OBJECT_ ID(N'[dbo] .[applicat ion_reques t]'))
  541                                                                                                                                                                 BEGIN
  542                                                                                                                                                                 ALTER  TABLE [dbo ].[applica tion_reque st]  WITH  CHECK ADD  CONSTRAINT  [FK_appli cation_req uest_users ] FOREIGN  KEY([reque stor])
  543                                                                                                                                                                 REFERE NCES [dbo] .[users] ( [user_id])
  544                                                                                                                                                                 END
  545                                                                                                                                                                 ",
  546                                                                                           'create_ap plication'  => "
  547                                                                                                                                               US E [".DATAB ASE_NAME." ]
  548                                                                                                                                               IF  NOT EXIST S (SELECT  * FROM sys .objects W HERE objec t_id = OBJ ECT_ID(N'[ dbo].[appl ication]')  AND type  in (N'U'))
  549                                                                                                                                               CR EATE TABLE  [dbo].[ap plication] (
  550                                                                                                                                                        [id]  [bigint]  IDENTITY(1 ,1) NOT NU LL,
  551                                                                                                                                                        [nam e] [varcha r](100) NU LL,
  552                                                                                                                                                        [pub lic_key] [ varchar](1 00) NULL,
  553                                                                                                                                                        [pri vate_key]  [varchar]( 100) NULL,
  554                                                                                                                                                        [url ] [varchar ](1000) NU LL,
  555                                                                                                                                                        [des cription]  [varchar]( 4000) NULL ,
  556                                                                                                                                                        [poc _name] [va rchar](500 ) NULL,
  557                                                                                                                                                        [poc _email] [v archar](10 0) NULL,
  558                                                                                                                                                        [poc _phone] [v archar](20 ) NULL,
  559                                                                                                                                                        [app _request_i d] [bigint ] NULL,
  560                                                                                                                                               PR IMARY KEY  CLUSTERED  ([id] ASC)
  561                                                                                                                                               WI TH (PAD_IN DEX  = OFF , STATISTI CS_NORECOM PUTE  = OF F, IGNORE_ DUP_KEY =  OFF, ALLOW _ROW_LOCKS   = ON, AL LOW_PAGE_L OCKS  = ON ) ON [PRIM ARY]) ON [ PRIMARY]
  562  
  563                                                                                                                                               IF   NOT EXIS TS (SELECT  * FROM sy s.foreign_ keys WHERE  object_id  = OBJECT_ ID(N'[dbo] .[FK_appli cation_app lication_r eques]') A ND parent_ object_id  = OBJECT_I D(N'[dbo]. [applicati on]'))
  564                                                                                                                                               BE GIN
  565                                                                                                                                               AL TER TABLE  [dbo].[app lication]   WITH CHEC K ADD CONS TRAINT [FK _applicati on_applica tion_reque st] FOREIG N KEY([app _request_i d])
  566                                                                                                                                               RE FERENCES [ dbo].[appl ication_re quest] ([i d])
  567                                                                                                                                               EN D
  568                                                                                                                                               ",
  569                                                                                           'create_ap plication_ account_li nk' =>     "
  570                                                                                                                                                                                   USE [".DAT ABASE_NAME ."]
  571                                                                                                                                                                                   SET ANSI_N ULLS ON
  572                                                                                                                                                                                   SET QUOTED _IDENTIFIE R ON
  573                                                                                                                                                                                   SET ANSI_P ADDING ON
  574  
  575                                                                                                                                                                                   IF NOT EXI STS (SELEC T * FROM s ys.objects  WHERE obj ect_id = O BJECT_ID(N '[dbo].[ap plication_ account_li nk]') AND  type in (N 'U'))
  576                                                                                                                                                                                   BEGIN
  577                                                                                                                                                                                   CREATE TAB LE [dbo].[ applicatio n_account_ link](
  578                                                                                                                                                                                           [i d] [bigint ] IDENTITY (1,1) NOT  NULL,
  579                                                                                                                                                                                           [a pp_id] [bi gint] NOT  NULL,
  580                                                                                                                                                                                           [u nique_id]  [nvarchar] (64) NOT N ULL,
  581                                                                                                                                                                                           [c reated_at]  [bigint]  NOT NULL,
  582                                                                                                                                                                                           [o rg_id] [bi gint] NULL ,
  583                                                                                                                                                                                           [s ystem_perm issions] [ nvarchar]( 100) NULL,
  584                                                                                                                                                                                    CONSTRAIN T [PK_appl ication_ac count_link ] PRIMARY  KEY CLUSTE RED ([id]  ASC)
  585                                                                                                                                                                                   WITH (PAD_ INDEX  = O FF, STATIS TICS_NOREC OMPUTE  =  OFF, IGNOR E_DUP_KEY  = OFF, ALL OW_ROW_LOC KS  = ON,  ALLOW_PAGE _LOCKS  =  ON) ON [PR IMARY]) ON  [PRIMARY]
  586                                                                                                                                                                                   END
  587                                                                                                                                                                                   SET ANSI_P ADDING OFF
  588  
  589                                                                                                                                                                                   IF  NOT EX ISTS (SELE CT * FROM  sys.foreig n_keys WHE RE object_ id = OBJEC T_ID(N'[db o].[FK_app lication_a ccount_lin k_applicat ion]') AND  parent_ob ject_id =  OBJECT_ID( N'[dbo].[a pplication _account_l ink]'))
  590                                                                                                                                                                                   BEGIN
  591                                                                                                                                                                                   ALTER TABL E [dbo].[a pplication _account_l ink]  WITH  CHECK ADD  CONSTRAIN T [FK_appl ication_ac count_link _applicati on] FOREIG N KEY([app _id])
  592                                                                                                                                                                                   REFERENCES  [dbo].[ap plication]  ([id])
  593                                                                                                                                                                                   END
  594                                                                                                                                                                                   ",
  595                                                                                           'create_ac count_requ est' =>      "
  596                                                                                                                                                        USE  [".DATABAS E_NAME."]
  597                                                                                                                                                        IF N OT EXISTS  (SELECT *  FROM sys.o bjects WHE RE object_ id = OBJEC T_ID(N'[db o].[accoun t_request] ') AND typ e in (N'U' ))
  598                                                                                                                                                        BEGI N
  599                                                                                                                                                        CREA TE TABLE [ dbo].[acco unt_reques t](
  600                                                                                                                                                                 [id] [ bigint] ID ENTITY(1,1 ) NOT NULL ,
  601                                                                                                                                                                 [usern ame] [varc har](100)  NULL,
  602                                                                                                                                                                 [user_ org_id] [b igint] NOT  NULL,
  603                                                                                                                                                                 [first _name] [nv archar](10 0) NOT NUL L,
  604                                                                                                                                                                 [middl e_name] [n varchar](1 00) NULL,
  605                                                                                                                                                                 [last_ name] [nva rchar](100 ) NOT NULL ,
  606                                                                                                                                                                 [ext_m ail] [nvar char](200)  NULL,
  607                                                                                                                                                                 [title ] [nvarcha r](300) NU LL,
  608                                                                                                                                                                 [depar tment] [nv archar](30 0) NULL,
  609                                                                                                                                                                 [organ ization] [ nvarchar]( 300) NULL,
  610                                                                                                                                                                 [locat ion] [nvar char](500)  NULL,
  611                                                                                                                                                                 [facil ity_id] [b igint] NUL L,
  612                                                                                                                                                                 [telep hone] [nva rchar](100 ) NULL,
  613                                                                                                                                                                 [mobil e] [nvarch ar](100) N ULL,
  614                                                                                                                                                                 [reque st_date] [ bigint] NO T NULL,
  615                                                                                                                                                                 [appro ved_date]  [bigint] N ULL,
  616                                                                                                                                                                 [justi fication]  [varchar]( 4000) NULL ,
  617                                                                                                                                                                 [denie d] [tinyin t] NOT NUL L DEFAULT  0,
  618                                                                                                                                                                 [domai n] [nvarch ar](253) N OT NULL DE FAULT '".C LINICAL_DO MAIN."',
  619                                                                                                                                                        PRIM ARY KEY CL USTERED ([ id] ASC)
  620                                                                                                                                                        WITH  (PAD_INDE X  = OFF,  STATISTICS _NORECOMPU TE  = OFF,  IGNORE_DU P_KEY = OF F, ALLOW_R OW_LOCKS   = ON, ALLO W_PAGE_LOC KS  = ON)  ON [PRIMAR Y]) ON [PR IMARY]
  621                                                                                                                                                        END
  622                                                                                                                                                        ",
  623                                                                                           'create_ev ent_log' = >   "
  624                                                                                                                                               US E [".DATAB ASE_NAME." ]
  625                                                                                                                                               SE T ANSI_NUL LS ON
  626                                                                                                                                               SE T QUOTED_I DENTIFIER  ON
  627                                                                                                                                               SE T ANSI_PAD DING ON
  628                                                                                                                                               IF  NOT EXIST S (SELECT  * FROM sys .objects W HERE objec t_id = OBJ ECT_ID(N'[ dbo].[even t_log]') A ND type in  (N'U'))
  629                                                                                                                                               BE GIN
  630                                                                                                                                               CR EATE TABLE  [dbo].[ev ent_log](
  631                                                                                                                                                        [id]  [bigint]  IDENTITY(1 ,1) NOT NU LL,
  632                                                                                                                                                        [tar get_type]  [int] NOT  NULL,
  633                                                                                                                                                        [tar get_id] [b igint] NOT  NULL,
  634                                                                                                                                                        [act or_type] [ int] NOT N ULL,
  635                                                                                                                                                        [act or_id] [bi gint] NOT  NULL,
  636                                                                                                                                                        [act ion] [nvar char](max)  NOT NULL,
  637                                                                                                                                                        [eve nt_date] [ bigint] NO T NULL,
  638                                                                                                                                                        [suc cess] [tin yint] NOT  NULL,
  639                                                                                                                                                C ONSTRAINT  [PK_event_ log] PRIMA RY KEY CLU STERED ([i d] ASC)
  640                                                                                                                                                W ITH (PAD_I NDEX  = OF F, STATIST ICS_NORECO MPUTE  = O FF, IGNORE _DUP_KEY =  OFF, ALLO W_ROW_LOCK S  = ON, A LLOW_PAGE_ LOCKS  = O N) ON [PRI MARY]) ON  [PRIMARY]
  641                                                                                                                                               EN D
  642                                                                                                                                               ",
  643                                                                                           'create_fa cility' =>     "
  644                                                                                                                                               US E [".DATAB ASE_NAME." ]
  645                                                                                                                                               SE T ANSI_NUL LS ON
  646                                                                                                                                               SE T QUOTED_I DENTIFIER  ON
  647                                                                                                                                               SE T ANSI_PAD DING ON
  648                                                                                                                                               IF  NOT EXIST S (SELECT  * FROM sys .objects W HERE objec t_id = OBJ ECT_ID(N'[ dbo].[faci lity]') AN D type in  (N'U'))
  649                                                                                                                                               BE GIN
  650                                                                                                                                               CR EATE TABLE  [dbo].[fa cility](
  651                                                                                                                                                        [id]  [bigint]  IDENTITY(1 ,1) NOT NU LL,
  652                                                                                                                                                        [nam e] [varcha r](400) NO T NULL,
  653                                                                                                                                                        [act ive] [tiny int] NOT N ULL,
  654                                                                                                                                               PR IMARY KEY  CLUSTERED  ([id] ASC)
  655                                                                                                                                               WI TH (PAD_IN DEX  = OFF , STATISTI CS_NORECOM PUTE  = OF F, IGNORE_ DUP_KEY =  OFF, ALLOW _ROW_LOCKS   = ON, AL LOW_PAGE_L OCKS  = ON ) ON [PRIM ARY]) ON [ PRIMARY]
  656                                                                                                                                               SE T ANSI_PAD DING OFF
  657                                                                                                                                               EN D
  658                                                                                                                                               ",
  659                                                                                           'create_lo gins' =>       "
  660                                                                                                                                       USE [".DAT ABASE_NAME ."]
  661                                                                                                                                       SET ANSI_N ULLS ON
  662                                                                                                                                       SET QUOTED _IDENTIFIE R ON
  663                                                                                                                                       IF NOT EXI STS (SELEC T * FROM s ys.objects  WHERE obj ect_id = O BJECT_ID(N '[dbo].[lo gins]') AN D type in  (N'U'))
  664                                                                                                                                       BEGIN
  665                                                                                                                                       CREATE TAB LE [dbo].[ logins](
  666                                                                                                                                               [i d] [bigint ] IDENTITY (1,1) NOT  NULL,
  667                                                                                                                                               [s ession_id]  [nvarchar ](50) NOT  NULL,
  668                                                                                                                                               [i p_address]  [nvarchar ](50) NOT  NULL,
  669                                                                                                                                               [l ogin_time]  [bigint]  NOT NULL,
  670                                                                                                                                               [s uccess] [t inyint] NO T NULL,
  671                                                                                                                                               [e rror_msg]  [nvarchar] (max) NOT  NULL,
  672                                                                                                                                               [o rg_id] [bi gint] NOT  NULL,
  673                                                                                                                                        CONSTRAIN T [PK_logi ns] PRIMAR Y KEY CLUS TERED ([id ] ASC)
  674                                                                                                                                       WITH (PAD_ INDEX  = O FF, STATIS TICS_NOREC OMPUTE  =  OFF, IGNOR E_DUP_KEY  = OFF, ALL OW_ROW_LOC KS  = ON,  ALLOW_PAGE _LOCKS  =  ON) ON [PR IMARY]) ON  [PRIMARY]
  675                                                                                                                                       END
  676                                                                                                                                       ",
  677                                                                                           'create_ma il_log' =>     "
  678                                                                                                                                               US E [".DATAB ASE_NAME." ]
  679                                                                                                                                               SE T ANSI_NUL LS ON
  680                                                                                                                                               SE T QUOTED_I DENTIFIER  ON
  681                                                                                                                                               SE T ANSI_PAD DING ON
  682                                                                                                                                               IF  NOT EXIST S (SELECT  * FROM sys .objects W HERE objec t_id = OBJ ECT_ID(N'[ dbo].[mail _log]') AN D type in  (N'U'))
  683                                                                                                                                               BE GIN
  684                                                                                                                                               CR EATE TABLE  [dbo].[ma il_log](
  685                                                                                                                                                        [id]  [bigint]  IDENTITY(1 ,1) NOT NU LL,
  686                                                                                                                                                        [tim e] [bigint ] NOT NULL ,
  687                                                                                                                                                        [siz e] [bigint ] NOT NULL ,
  688                                                                                                                                                        [sen der] [varc har](max)  NOT NULL,
  689                                                                                                                                                        [rec ipient] [v archar](ma x) NOT NUL L,
  690                                                                                                                                                        [att achment_ty pes] [nvar char](max)  NOT NULL,
  691                                                                                                                                                        [suc cess] [tin yint] NOT  NULL,
  692                                                                                                                                                        [inb ound_outbo und] [tiny int] NOT N ULL,
  693                                                                                                                                                        [mdn ] [tinyint ] NULL,
  694                                                                                                                                                        [pro tected_dat a] [tinyin t] NULL,
  695                                                                                                                                                        [sto rage_id] [ bigint] NU LL,
  696                                                                                                                                                C ONSTRAINT  [PK_mail_l og] PRIMAR Y KEY CLUS TERED ([id ] ASC)
  697                                                                                                                                               WI TH (PAD_IN DEX  = OFF , STATISTI CS_NORECOM PUTE  = OF F, IGNORE_ DUP_KEY =  OFF, ALLOW _ROW_LOCKS   = ON, AL LOW_PAGE_L OCKS  = ON ) ON [PRIM ARY]) ON [ PRIMARY]
  698                                                                                                                                               EN D
  699                                                                                                                                               SE T ANSI_PAD DING OFF
  700                                                                                                                                               ",
  701                                                                                           'create_ma ilbox_sett ings' =>     "
  702                                                                                                                                                                 USE [" .DATABASE_ NAME."]
  703                                                                                                                                                                 IF NOT  EXISTS (S ELECT * FR OM sys.obj ects WHERE  object_id  = OBJECT_ ID(N'[dbo] .[mailbox_ settings]' ) AND type  in (N'U') )
  704                                                                                                                                                                 BEGIN
  705                                                                                                                                                                 CREATE  TABLE [db o].[mailbo x_settings ](
  706                                                                                                                                                                          [id] [bi gint] IDEN TITY(1,1)  NOT NULL,
  707                                                                                                                                                                          [mailbox _id] [bigi nt] NOT NU LL,
  708                                                                                                                                                                          [applica tion_id] [ bigint] NO T NULL,
  709                                                                                                                                                                          [web_ser vice_id] [ bigint] NO T NULL,
  710                                                                                                                                                                          [authori zed] [tiny int] NOT N ULL,
  711                                                                                                                                                                 PRIMAR Y KEY CLUS TERED([id]  ASC)
  712                                                                                                                                                                 WITH ( PAD_INDEX   = OFF, ST ATISTICS_N ORECOMPUTE   = OFF, I GNORE_DUP_ KEY = OFF,  ALLOW_ROW _LOCKS  =  ON, ALLOW_ PAGE_LOCKS   = ON) ON  [PRIMARY] ) ON [PRIM ARY]
  713                                                                                                                                                                 END
  714  
  715                                                                                                                                                                 IF  NO T EXISTS ( SELECT * F ROM sys.fo reign_keys  WHERE obj ect_id = O BJECT_ID(N '[dbo].[FK _mailbox_s ettings_ap plication] ') AND par ent_object _id = OBJE CT_ID(N'[d bo].[mailb ox_setting s]'))
  716                                                                                                                                                                 BEGIN
  717                                                                                                                                                                 ALTER  TABLE [dbo ].[mailbox _settings]   WITH CHE CK ADD CON STRAINT [F K_mailbox_ settings_a pplication ] FOREIGN  KEY([appli cation_id] )
  718                                                                                                                                                                 REFERE NCES [dbo] .[applicat ion] ([id] )
  719                                                                                                                                                                 END
  720  
  721                                                                                                                                                                 IF  NO T EXISTS ( SELECT * F ROM sys.fo reign_keys  WHERE obj ect_id = O BJECT_ID(N '[dbo].[FK _mailbox_s ettings_we b_services ]') AND pa rent_objec t_id = OBJ ECT_ID(N'[ dbo].[mail box_settin gs]'))
  722                                                                                                                                                                 BEGIN
  723                                                                                                                                                                 ALTER  TABLE [dbo ].[mailbox _settings]   WITH CHE CK ADD CON STRAINT [F K_mailbox_ settings_w eb_service s] FOREIGN  KEY([web_ service_id ])
  724                                                                                                                                                                 REFERE NCES [dbo] .[web_serv ices] ([id ])
  725                                                                                                                                                                 END
  726                                                                                                                                                                 ",
  727                                                                                           'create_re quest' =>      "
  728                                                                                                                                       USE [".DAT ABASE_NAME ."]
  729                                                                                                                                       IF NOT EXI STS (SELEC T * FROM s ys.objects  WHERE obj ect_id = O BJECT_ID(N '[dbo].[re quest]') A ND type in  (N'U'))
  730                                                                                                                                       BEGIN
  731                                                                                                                                       CREATE TAB LE [dbo].[ request](
  732                                                                                                                                               [i d] [bigint ] IDENTITY (1,1) NOT  NULL,
  733                                                                                                                                               [a pplication _id] [bigi nt] NULL,
  734                                                                                                                                               [c all] [varc har](max)  NULL,
  735                                                                                                                                               [c all_date]  [bigint] N ULL,
  736                                                                                                                                               [r esponse_co de] [int]  NULL,
  737                                                                                                                                               [r esponse] [ varchar](m ax) NULL,
  738                                                                                                                                       PRIMARY KE Y CLUSTERE D ([id] AS C)
  739                                                                                                                                       WITH (PAD_ INDEX  = O FF, STATIS TICS_NOREC OMPUTE  =  OFF, IGNOR E_DUP_KEY  = OFF, ALL OW_ROW_LOC KS  = ON,  ALLOW_PAGE _LOCKS  =  ON) ON [PR IMARY]) ON  [PRIMARY]
  740                                                                                                                                       END
  741  
  742                                                                                                                                       IF  NOT EX ISTS (SELE CT * FROM  sys.foreig n_keys WHE RE object_ id = OBJEC T_ID(N'[db o].[FK_req uest_appli cation]')  AND parent _object_id  = OBJECT_ ID(N'[dbo] .[request] '))
  743                                                                                                                                       BEGIN
  744                                                                                                                                       ALTER TABL E [dbo].[r equest]  W ITH CHECK  ADD CONSTR AINT [FK_r equest_app lication]  FOREIGN KE Y([applica tion_id])
  745                                                                                                                                       REFERENCES  [dbo].[ap plication]  ([id])
  746                                                                                                                                       END
  747                                                                                                                                       ",
  748                                                                                           'create_ti cket_categ ory' => "
  749                                                                                                                                                        USE  [".DATABAS E_NAME."]
  750                                                                                                                                                        IF N OT EXISTS  (SELECT *  FROM sys.o bjects WHE RE object_ id = OBJEC T_ID(N'[db o].[ticket _category] ') AND typ e in (N'U' ))
  751                                                                                                                                                        BEGI N
  752                                                                                                                                                        CREA TE TABLE [ dbo].[tick et_categor y](
  753                                                                                                                                                        [id]  [bigint]  IDENTITY(1 ,1) NOT NU LL,
  754                                                                                                                                                        [cat egory] [va rchar](200 ) NULL,
  755                                                                                                                                                        PRIM ARY KEY CL USTERED
  756                                                                                                                                                        ([id ] ASC)
  757                                                                                                                                                        WITH  (PAD_INDE X  = OFF,  STATISTICS _NORECOMPU TE  = OFF,  IGNORE_DU P_KEY = OF F, ALLOW_R OW_LOCKS   = ON, ALLO W_PAGE_LOC KS  = ON)  ON [PRIMAR Y]) ON [PR IMARY]
  758                                                                                                                                                        END
  759                                                                                                                                                        
  760                                                                                                                                                        IF E XISTS (SEL ECT * FROM  sys.objec ts WHERE o bject_id =  OBJECT_ID (N'[dbo].[ ticket_cat egory]') A ND type in  (N'U'))
  761                                                                                                                                                        BEGI N
  762                                                                                                                                                        SET  IDENTITY_I NSERT [dbo ].[web_ser vices] ON
  763                                                                                                                                                        INSE RT [dbo].[ ticket_cat egory] ([i d], [categ ory]) VALU ES (1, N'C ontact')
  764                                                                                                                                                        SET  IDENTITY_I NSERT [dbo ].[web_ser vices] OFF
  765                                                                                                                                                        END
  766                                                                                                                                                        ",
  767                                                                                           'create_ti ckets' =>      "
  768                                                                                                                                       USE [".DAT ABASE_NAME ."]
  769                                                                                                                                       IF NOT EXI STS (SELEC T * FROM s ys.objects  WHERE obj ect_id = O BJECT_ID(N '[dbo].[ti ckets]') A ND type in  (N'U'))
  770                                                                                                                                       BEGIN
  771                                                                                                                                       CREATE TAB LE [dbo].[ tickets](
  772                                                                                                                                               [i d] [bigint ] IDENTITY (1,1) NOT  NULL,
  773                                                                                                                                               [p arent_id]  [bigint] N ULL,
  774                                                                                                                                               [u ser_id] [b igint] NUL L,
  775                                                                                                                                               [m essage] [v archar](40 00) NULL,
  776                                                                                                                                               [o pen_date]  [bigint] N ULL,
  777                                                                                                                                               [c lose_date]  [bigint]  NULL,
  778                                                                                                                                               [c ategory_id ] [bigint]  NULL,
  779                                                                                                                                       PRIMARY KE Y CLUSTERE D ([id] AS C)
  780                                                                                                                                       WITH (PAD_ INDEX  = O FF, STATIS TICS_NOREC OMPUTE  =  OFF, IGNOR E_DUP_KEY  = OFF, ALL OW_ROW_LOC KS  = ON,  ALLOW_PAGE _LOCKS  =  ON) ON [PR IMARY]) ON  [PRIMARY]
  781                                                                                                                                       END
  782  
  783                                                                                                                                       IF  NOT EX ISTS (SELE CT * FROM  sys.foreig n_keys WHE RE object_ id = OBJEC T_ID(N'[db o].[FK_tic kets_users ]') AND pa rent_objec t_id = OBJ ECT_ID(N'[ dbo].[tick ets]'))
  784                                                                                                                                       BEGIN
  785                                                                                                                                       ALTER TABL E [dbo].[t ickets]  W ITH CHECK  ADD CONSTR AINT [FK_t ickets_use rs] FOREIG N KEY([use r_id])
  786                                                                                                                                       REFERENCES  [dbo].[us ers] ([use r_id])
  787                                                                                                                                       END
  788  
  789                                                                                                                                       IF  NOT EX ISTS (SELE CT * FROM  sys.foreig n_keys WHE RE object_ id = OBJEC T_ID(N'[db o].[FK_tic kets_ticke ts]') AND  parent_obj ect_id = O BJECT_ID(N '[dbo].[ti ckets]'))
  790                                                                                                                                       BEGIN
  791                                                                                                                                       ALTER TABL E [dbo].[t ickets]  W ITH CHECK  ADD CONSTR AINT [FK_t ickets_tic kets] FORE IGN KEY([p arent_id])
  792                                                                                                                                       REFERENCES  [dbo].[ti ckets] ([i d])
  793                                                                                                                                       END
  794  
  795                                                                                                                                       IF  NOT EX ISTS (SELE CT * FROM  sys.foreig n_keys WHE RE object_ id = OBJEC T_ID(N'[db o].[FK_tic kets_ticke t_category ]') AND pa rent_objec t_id = OBJ ECT_ID(N'[ dbo].[tick ets]'))
  796                                                                                                                                       BEGIN
  797                                                                                                                                       ALTER TABL E [dbo].[t ickets]  W ITH CHECK  ADD CONSTR AINT [FK_t ickets_tic ket_catego ry] FOREIG N KEY([cat egory_id])
  798                                                                                                                                       REFERENCES  [dbo].[ti cket_categ ory] ([id] )
  799                                                                                                                                       END
  800                                                                                                                                       ",
  801                                                                                           'create_we b_services ' =>         "
  802                                                                                                                                                        USE  [".DATABAS E_NAME."]
  803                                                                                                                                                        SET  ANSI_NULLS  ON
  804                                                                                                                                                        SET  QUOTED_IDE NTIFIER ON
  805                                                                                                                                                        SET  ANSI_PADDI NG ON
  806                                                                                                                                                        IF N OT EXISTS  (SELECT *  FROM sys.o bjects WHE RE object_ id = OBJEC T_ID(N'[db o].[web_se rvices]')  AND type i n (N'U'))
  807                                                                                                                                                        BEGI N
  808                                                                                                                                                        CREA TE TABLE [ dbo].[web_ services](
  809                                                                                                                                                                 [id] [ bigint] ID ENTITY(1,1 ) NOT NULL ,
  810                                                                                                                                                                 [name]  [varchar] (200) NOT  NULL,
  811                                                                                                                                                                 [descr iption] [v archar](40 00) NULL,
  812                                                                                                                                                         CON STRAINT [P K_web_serv ices] PRIM ARY KEY NO NCLUSTERED  ([id] ASC )
  813                                                                                                                                                        WITH  (PAD_INDE X  = OFF,  STATISTICS _NORECOMPU TE  = OFF,  IGNORE_DU P_KEY = OF F, ALLOW_R OW_LOCKS   = ON, ALLO W_PAGE_LOC KS  = ON)  ON [PRIMAR Y]) ON [PR IMARY]
  814                                                                                                                                                        END
  815                                                                                                                                                        SET  ANSI_PADDI NG OFF
  816  
  817                                                                                                                                                        IF E XISTS (SEL ECT * FROM  sys.objec ts WHERE o bject_id =  OBJECT_ID (N'[dbo].[ web_servic es]') AND  type in (N 'U'))
  818                                                                                                                                                        BEGI N
  819                                                                                                                                                        SET  IDENTITY_I NSERT [dbo ].[web_ser vices] ON
  820                                                                                                                                                        INSE RT [dbo].[ web_servic es] ([id],  [name], [ descriptio n]) VALUES  (1, N'sen d', N'Allo ws applica tion to se nd a direc t message  on your be half')
  821                                                                                                                                                        INSE RT [dbo].[ web_servic es] ([id],  [name], [ descriptio n]) VALUES  (2, N'ret rieve', N' Allows app lication t o retrieve  your mess ages')
  822                                                                                                                                                        INSE RT [dbo].[ web_servic es] ([id],  [name], [ descriptio n]) VALUES  (3, N'man age', N'Al lows appli cation to  manage mes sages and  folders')
  823                                                                                                                                                        SET  IDENTITY_I NSERT [dbo ].[web_ser vices] OFF
  824                                                                                                                                                        END
  825                                                                                                                                                        ",
  826                                                                                                   'c reate_perm issions' = > "
  827                                                                                                                                                        USE  [".DATABAS E_NAME."]
  828                                                                                                                                                        SET  ANSI_NULLS  ON
  829                                                                                                                                                        SET  QUOTED_IDE NTIFIER ON
  830                                                                                                                                                        SET  ANSI_PADDI NG ON
  831                                                                                                                                                        IF N OT EXISTS  (SELECT *  FROM sys.o bjects WHE RE object_ id = OBJEC T_ID(N'[db o].[permis sions]') A ND type in  (N'U'))
  832                                                                                                                                                        BEGI N
  833                                                                                                                                                        CREA TE TABLE [ dbo].[perm issions](
  834                                                                                                                                                                 [id] [ bigint] ID ENTITY(1,1 ) NOT NULL ,
  835                                                                                                                                                                 [name]  [nvarchar ](100) NOT  NULL,
  836                                                                                                                                                                 [paren t_id] bigi nt NULL,
  837                                                                                                                                                         CON STRAINT [P K_permissi ons] PRIMA RY KEY NON CLUSTERED  ([id] ASC)
  838                                                                                                                                                        WITH  (PAD_INDE X  = OFF,  STATISTICS _NORECOMPU TE  = OFF,  IGNORE_DU P_KEY = OF F, ALLOW_R OW_LOCKS   = ON, ALLO W_PAGE_LOC KS  = ON)  ON [PRIMAR Y]) ON [PR IMARY]
  839                                                                                                                                                        END
  840                                                                                                                                                        SET  ANSI_PADDI NG OFF
  841                                                                                                   
  842                                                                                                                                                        IF E XISTS (SEL ECT * FROM  sys.objec ts WHERE o bject_id =  OBJECT_ID (N'[dbo].[ permission s]') AND t ype in (N' U'))
  843                                                                                                                                                        BEGI N
  844                                                                                                                                                        SET  IDENTITY_I NSERT [dbo ].[permiss ions] ON
  845                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (1 , N'report s', NULL)
  846                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (2 , N'user_s ummary_rep ort_contro ller', 1)
  847                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (3 , N'facili ty_report_ controller ', 1)
  848                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (4 , N'admini stration',  NULL)
  849                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (5 , N'manage _groups',  4)
  850                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (6 , N'manage _groups_le ads', 5)
  851                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (7 , N'enable _group', 5 )
  852                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (8 , N'disabl e_group',  5)
  853                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (9 , N'group_ permission s', 5)
  854                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (1 0, N'discl osure', 1)
  855                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (1 1, N'reque st_report_ controller ', 1)
  856                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (1 2, N'event _report_co ntroller',  1)
  857                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (1 3, N'login _report_co ntroller',  1)
  858                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (1 4, N'mail_ report_con troller',  1)
  859                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (1 5, N'group _summary_r eport_cont roller', 1 )
  860                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (1 6, N'hisp_ report_con troller',  1)
  861                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (1 7, N'point s_of_origi n_report_c ontroller' , 1)
  862                                                                                                                                                        INSE RT [dbo].[ permission s] ([id],  [name], [p arent_id])  VALUES (1 8, N'adhoc _report_co ntroller',  1)
  863                                                                                                   
  864                                                                                                   
  865                                                                                                                                                        SET  IDENTITY_I NSERT [dbo ].[permiss ions] OFF
  866                                                                                                                                                        END
  867                                                                                                                                                        ",
  868                                                                                                   'c reate_role _permissio ns' =>     "
  869                                                                                                                                                        USE  [".DATABAS E_NAME."]
  870                                                                                                                                                        SET  ANSI_NULLS  ON
  871                                                                                                                                                        SET  QUOTED_IDE NTIFIER ON
  872                                                                                                                                                        SET  ANSI_PADDI NG ON
  873                                                                                                                                                        IF N OT EXISTS  (SELECT *  FROM sys.o bjects WHE RE object_ id = OBJEC T_ID(N'[db o].[role_p ermissions ]') AND ty pe in (N'U '))
  874                                                                                                                                                        BEGI N
  875                                                                                                                                                        CREA TE TABLE [ dbo].[role _permissio ns](
  876                                                                                                                                                                 [id] [ bigint] ID ENTITY(1,1 ) NOT NULL ,
  877                                                                                                                                                                 [role_ name] [nva rchar](150 ) NOT NULL ,
  878                                                                                                                                                                 [permi ssion_id]  bigint NOT  NULL,
  879                                                                                                                                                         CON STRAINT [P K_role_per missions]  PRIMARY KE Y NONCLUST ERED ([id]  ASC)
  880                                                                                                                                                        WITH  (PAD_INDE X  = OFF,  STATISTICS _NORECOMPU TE  = OFF,  IGNORE_DU P_KEY = OF F, ALLOW_R OW_LOCKS   = ON, ALLO W_PAGE_LOC KS  = ON)  ON [PRIMAR Y]) ON [PR IMARY]
  881                                                                                                                                                        END
  882                                                                                                                                                        SET  ANSI_PADDI NG OFF
  883                                                       
  884                                                                                                                                                        IF E XISTS (SEL ECT * FROM  sys.objec ts WHERE o bject_id =  OBJECT_ID (N'[dbo].[ role_permi ssions]')  AND type i n (N'U'))
  885                                                                                                                                                        BEGI N
  886                                                                                                                                                        SET  IDENTITY_I NSERT [dbo ].[role_pe rmissions]  ON
  887                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (1, N'fa cilitylead er', 1)
  888                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (2, N'fa cilitylead er', 2)
  889                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (3, N'fa cilitylead er', 3)
  890                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (5, N'gr oupleader' , 4)
  891                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (6, N'gr oupleader' , 5)
  892                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (7, N'gr oupleader' , 6)
  893                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (8, N'gr oupleader' , 7)
  894                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (9, N'gr oupleader' , 8)
  895                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (10, N'g roupleader ', 9)
  896                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (11, N'r eports', 1 )
  897                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (12, N'r eports', 2 )
  898                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (13, N'r eports', 3 )
  899                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (14, N'r eports', 1 1)
  900                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (15, N'r eports', 1 2)
  901                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (16, N'r eports', 1 3)
  902                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (17, N'r eports', 1 4)
  903                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (18, N'r eports', 1 5)
  904                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (19, N'r eports', 1 6)
  905                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (20, N'r eports', 1 7)
  906                                                                                                                                                        INSE RT [dbo].[ role_permi ssions] ([ id], [role _name], [p ermission_ id]) VALUE S (21, N'r eports', 1 8)
  907                                                                                                                                                        
  908                                                                                                                                                        SET  IDENTITY_I NSERT [dbo ].[role_pe rmissions]  OFF
  909                                                                                                                                                        END
  910                                                                                                                                                        ",
  911                                                                                           'create_ad hoc_report s' =>        "
  912                                                                                                                                                        USE  [".DATABAS E_NAME."]
  913                                                                                                                                                        SET  ANSI_NULLS  ON
  914                                                                                                                                                        SET  QUOTED_IDE NTIFIER ON
  915                                                                                                                                                        CREA TE TABLE [ dbo].[adho c_reports] (
  916                                                                                                                                                                 [repor t_id] [big int] IDENT ITY(1,1) N OT NULL,
  917                                                                                                                                                                 [repor t_type] [n varchar](1 00) NULL,
  918                                                                                                                                                                 [repor t_name] [n varchar](5 0) NULL,
  919                                                                                                                                                                 [repor t_descript ion] [nvar char](max)  NULL,
  920                                                                                                                                                                 [repor t_created_ by] [nvarc har](max)  NULL,
  921                                                                                                                                                                 [repor t_access_t ype] [nvar char](50)  NULL,
  922                                                                                                                                                                 [repor t_created_ time] [big int] NOT N ULL,
  923                                                                                                                                                                 [repor t_query_ge nerator] [ nvarchar]( max) NULL,
  924                                                                                                                                                                 [repor t_order_by ] [nvarcha r](max) NU LL,
  925                                                                                                                                                                 [repor t_order_by _direction ] [nvarcha r](100) NU LL,
  926                                                                                                                                                                 [repor t_time_per iod] [nvar char](200)  NULL,
  927                                                                                                                                                                 [repor t_status]  [nvarchar] (max) NULL ,
  928                                                                                                                                                                 [repor t_end_date ] [nvarcha r](max) NU LL,
  929                                                                                                                                                                 [repor t_start_da te] [nvarc har](max)  NULL,
  930                                                                                                                                                                 [repor t_selector ] [nvarcha r](max) NU LL,
  931                                                                                                                                                                 [repor t_time_fie ld] [nvarc har](200)  NULL
  932                                                                                                                                                        ) ON  [PRIMARY]
  933                                                                                                                                                        ",
  934                                                                                           'create_ad hoc_report s_access'  =>         "
  935                                                                                                                                                                          USE [".D ATABASE_NA ME."]
  936                                                                                                                                                                          SET ANSI _NULLS ON
  937                                                                                                                                                                          SET QUOT ED_IDENTIF IER ON
  938                                                                                                                                                                          CREATE T ABLE [dbo] .[adhoc_re ports_acce ss](
  939                                                                                                                                                                                   [report_ac cess_id] [ bigint] ID ENTITY(1,1 ) NOT NULL ,
  940                                                                                                                                                                                   [report_id ] [bigint]  NOT NULL,
  941                                                                                                                                                                                   [user_id]  [bigint] N OT NULL,
  942                                                                                                                                                                                   [time] [bi gint] NOT  NULL
  943                                                                                                                                                                          ) ON [PR IMARY]
  944                                                                                                                                                                          ",
  945                                                                                  'create_ das_log_en tries' =>      "
  946                                                                                                                                       USE [".DAT ABASE_NAME ."]
  947                                                                                                                                       SET ANSI_N ULLS ON
  948                                                                                                                                       SET QUOTED _IDENTIFIE R ON
  949                                                                                                                                       CREATE TAB LE [dbo].[ das_log_en tries](
  950                                                                                                                                               [i d] [bigint ] IDENTITY (1,1) NOT  NULL,
  951                                                                                                                                               [s aved_date]  [bigint]  NULL,
  952                                                                                                                                               [r esult_stat us] [nchar ](10) NULL ,
  953                                                                                                                                               [a ttachment_ name] [nva rchar](max ) NULL,
  954                                                                                                                                               [h ash_attach ment_name]  [nvarchar ](512) NUL L,
  955                                                                                                                                               [d as_documen t_id] [nva rchar](max ) NULL,
  956                                                                                                                                               [m essage_id]  [bigint]  NULL,
  957                                                                                                                                               CO NSTRAINT [ PK_das_log _entries]  PRIMARY KE Y CLUSTERE D ([id] AS C) WITH (P AD_INDEX   = OFF, STA TISTICS_NO RECOMPUTE   = OFF, IG NORE_DUP_K EY = OFF,  ALLOW_ROW_ LOCKS  = O N, ALLOW_P AGE_LOCKS   = ON) ON  [PRIMARY])  ON [PRIMA RY]
  958                                                                                                                                       ",                                                                             
  959                                                                                  ),
  960                                                                                  MAIL_DAT ABASE_NAME  => array(
  961                                                                                           'create_fo lders' =>      "
  962                                                                                                                                       USE [".MAI L_DATABASE _NAME."]
  963                                                                                                                                       SET ANSI_N ULLS ON
  964                                                                                                                                       SET QUOTED _IDENTIFIE R ON
  965                                                                                                                                       SET ANSI_P ADDING ON
  966                                                                                                                                       IF NOT EXI STS (SELEC T * FROM s ys.objects  WHERE obj ect_id = O BJECT_ID(N '[dbo].[fo lders]') A ND type in  (N'U'))
  967                                                                                                                                       BEGIN
  968                                                                                                                                       CREATE TAB LE [dbo].[ folders](
  969                                                                                                                                               [i d] [bigint ] IDENTITY (1,1) NOT  NULL,
  970                                                                                                                                               [n ame] [varc har](200)  NOT NULL,
  971                                                                                                                                               [m ailbox_id]  [bigint]  NOT NULL,
  972                                                                                                                                               [p arent_id]  [bigint] N ULL,
  973                                                                                                                                        CONSTRAIN T [PK_fold ers] PRIMA RY KEY NON CLUSTERED  ([id] ASC)
  974                                                                                                                                        WITH (PAD _INDEX  =  OFF, STATI STICS_NORE COMPUTE  =  OFF, IGNO RE_DUP_KEY  = OFF, AL LOW_ROW_LO CKS  = ON,  ALLOW_PAG E_LOCKS  =  ON) ON [P RIMARY]) O N [PRIMARY ]
  975                                                                                                                                       SET ANSI_P ADDING OFF
  976                                                                                                                                       END
  977                                                                                                                                       IF EXISTS  (SELECT *  FROM sys.o bjects WHE RE object_ id = OBJEC T_ID(N'[db o].[folder s]') AND t ype in (N' U'))
  978                                                                                                                                       BEGIN
  979                                                                                                                                       ALTER TABL E [dbo].[f olders]  W ITH CHECK  ADD  CONST RAINT [FK_ folder_mai lbox2] FOR EIGN KEY([ mailbox_id ])
  980                                                                                                                                       REFERENCES  [dbo].[ma ilboxes] ( [id])
  981                                                                                                                                       ON DELETE  CASCADE
  982                                                                                                                                       ALTER TABL E [dbo].[f olders] CH ECK CONSTR AINT [FK_f older_mail box2]
  983                                                                                                                                       END
  984                                                                                                                                       ",
  985                                                                                           'create_me ssages' =>     "
  986                                                                                                                                               US E [".MAIL_ DATABASE_N AME."]
  987                                                                                                                                               SE T ANSI_NUL LS ON
  988                                                                                                                                               SE T QUOTED_I DENTIFIER  ON
  989                                                                                                                                               SE T ANSI_PAD DING ON
  990                                                                                                                                               IF  NOT EXIST S (SELECT  * FROM sys .objects W HERE objec t_id = OBJ ECT_ID(N'[ dbo].[mess ages]') AN D type in  (N'U'))
  991                                                                                                                                               BE GIN
  992                                                                                                                                               CR EATE TABLE  [dbo].[me ssages](
  993                                                                                                                                                        [id]  [bigint]  IDENTITY(1 ,1) NOT NU LL,
  994                                                                                                                                                        [rec ipients] [ varchar](m ax) NULL,
  995                                                                                                                                                        [sen der] [varc har](max)  NOT NULL,
  996                                                                                                                                                        [ori ginal_send er_id] [bi gint] NULL ,
  997                                                                                                                                                        [to]  [varchar] (max) NULL ,
  998                                                                                                                                                        [cc]  [varchar] (max) NULL ,
  999                                                                                                                                                        [bcc ] [varchar ](max) NUL L,
  1000                                                                                                                                                        [att achments]  [varchar]( max) NULL,
  1001                                                                                                                                                        [sub ject] [var char](max)  NULL,
  1002                                                                                                                                                        [pla in] [varch ar](max) N ULL,
  1003                                                                                                                                                        [htm l] [varcha r](max) NU LL,
  1004                                                                                                                                                        [tim estamp] [b igint] NOT  NULL,
  1005                                                                                                                                                        [fol der_id] [b igint] NUL L,
  1006                                                                                                                                                        [siz e] [bigint ] NULL,
  1007                                                                                                                                                        [fla gs] [varch ar](max) N ULL,
  1008                                                                                                                                                        [hea ders] [var char](max)  NOT NULL,
  1009                                                                                                                                                        [raw _mime] [va rchar](max ) NULL,
  1010                                                                                                                                                        [see n] [tinyin t] NULL,
  1011                                                                                                                                                        [dra ft] [tinyi nt] NULL,
  1012                                                                                                                                                        [sen t] [tinyin t] NULL,
  1013                                                                                                                                                        [arc hived] [ti nyint] NUL L,
  1014                                                                                                                                                        [mes sage_id] [ varchar](m ax) NULL,
  1015                                                                                                                                                        [mai lbox_id] [ bigint] NO T NULL,
  1016                                                                                                                                                        [mai ltype] [va rchar](4)  NOT NULL,
  1017                                                                                                                                                        [pri ority] [ti nyint] NOT  NULL,
  1018                                                                                                                                                        [pro tected_dat a] [tinyin t] NULL,
  1019                                                                                                                                                        [is_ automated]  [bit] NOT  NULL DEFA ULT 0,
  1020                                                                                                                                                        [non _va_referr al] [tinyi nt] NULL,
  1021                                                                                                                                               CO NSTRAINT [ PK_mailbox _username]  PRIMARY K EY NONCLUS TERED ([id ] ASC)
  1022                                                                                                                                               WI TH (PAD_IN DEX  = OFF , STATISTI CS_NORECOM PUTE  = OF F, IGNORE_ DUP_KEY =  OFF, ALLOW _ROW_LOCKS   = ON, AL LOW_PAGE_L OCKS  = ON ) ON [PRIM ARY]) ON [ PRIMARY]
  1023                                                                                                                                               EN D
  1024                                                                                                                                               SE T ANSI_PAD DING OFF
  1025                                                                                                                                               IF  EXISTS (S ELECT * FR OM sys.obj ects WHERE  object_id  = OBJECT_ ID(N'[dbo] .[messages ]') AND ty pe in (N'U '))
  1026                                                                                                                                               BE GIN
  1027                                                                                                                                               AL TER TABLE  [dbo].[mes sages] ADD   DEFAULT  ((0)) FOR  [seen]
  1028                                                                                                                                               AL TER TABLE  [dbo].[mes sages] ADD   DEFAULT  ((0)) FOR  [draft]
  1029                                                                                                                                               AL TER TABLE  [dbo].[mes sages] ADD   DEFAULT  ((0)) FOR  [sent]
  1030                                                                                                                                               AL TER TABLE  [dbo].[mes sages] ADD   DEFAULT  ((0)) FOR  [archived]
  1031                                                                                                                                               AL TER TABLE  [dbo].[mes sages] ADD   DEFAULT  ('html') F OR [mailty pe]
  1032                                                                                                                                               AL TER TABLE  [dbo].[mes sages]  WI TH CHECK A DD  CONSTR AINT [FK_m essage_mai lbox] FORE IGN KEY([m ailbox_id] )
  1033                                                                                                                                               RE FERENCES [ dbo].[mail boxes] ([i d])
  1034                                                                                                                                               AL TER TABLE  [dbo].[mes sages] CHE CK CONSTRA INT [FK_me ssage_mail box]
  1035                                                                                                                                               AL TER TABLE  [dbo].[mes sages]  WI TH CHECK A DD  CONSTR AINT [FK_m essages_fo lder] FORE IGN KEY([f older_id])
  1036                                                                                                                                               RE FERENCES [ dbo].[fold ers] ([id] )
  1037                                                                                                                                               ON  DELETE SE T NULL
  1038                                                                                                                                               AL TER TABLE  [dbo].[mes sages] CHE CK CONSTRA INT [FK_me ssages_fol der]
  1039                                                                                                                                               EN D
  1040                                                                                                                                               ",
  1041                                                                                           'create_ma ilboxes' = >   "
  1042                                                                                                                                               US E [".MAIL_ DATABASE_N AME."]
  1043                                                                                                                                               SE T ANSI_NUL LS ON
  1044                                                                                                                                               SE T QUOTED_I DENTIFIER  ON
  1045                                                                                                                                               SE T ANSI_PAD DING ON
  1046                                                                                                                                               IF  NOT EXIST S (SELECT  * FROM sys .objects W HERE objec t_id = OBJ ECT_ID(N'[ dbo].[mail boxes]') A ND type in  (N'U'))
  1047                                                                                                                                               BE GIN
  1048                                                                                                                                               CR EATE TABLE  [dbo].[ma ilboxes](
  1049                                                                                                                                                        [id]  [bigint]  IDENTITY(1 ,1) NOT NU LL,
  1050                                                                                                                                                        [nam e] [nvarch ar](100) N OT NULL,
  1051                                                                                                                                                        [dom ain] [nvar char](253)  NOT NULL  DEFAULT '" .CLINICAL_ DOMAIN."',
  1052                                                                                                                                                        [is_ group] [ti nyint] NUL L,
  1053                                                                                                                                                        [is_ active] [t inyint] NU LL,
  1054                                                                                                                                                        [fac ility_id]  [bigint] N ULL,
  1055                                                                                                                                                C ONSTRAINT  [PK_mailbo xes] PRIMA RY KEY NON CLUSTERED  ([id] ASC)
  1056                                                                                                                                               WI TH (PAD_IN DEX  = OFF , STATISTI CS_NORECOM PUTE  = OF F, IGNORE_ DUP_KEY =  OFF, ALLOW _ROW_LOCKS   = ON, AL LOW_PAGE_L OCKS  = ON ) ON [PRIM ARY],
  1057                                                                                                                                               UN IQUE NONCL USTERED ([ name] ASC)
  1058                                                                                                                                               WI TH (PAD_IN DEX  = OFF , STATISTI CS_NORECOM PUTE  = OF F, IGNORE_ DUP_KEY =  OFF, ALLOW _ROW_LOCKS   = ON, AL LOW_PAGE_L OCKS  = ON ) ON [PRIM ARY]) ON [ PRIMARY]
  1059                                                                                                                                               EN D
  1060                                                                                                                                               SE T ANSI_PAD DING OFF
  1061                                                                                                                                               IF  EXISTS (S ELECT * FR OM sys.obj ects WHERE  object_id  = OBJECT_ ID(N'[dbo] .[mailboxe s]') AND t ype in (N' U'))
  1062                                                                                                                                               BE GIN
  1063                                                                                                                                               AL TER TABLE  [dbo].[mai lboxes] AD D  DEFAULT  ((0)) FOR  [is_group ]
  1064                                                                                                                                               AL TER TABLE  [dbo].[mai lboxes] AD D  DEFAULT  ((0)) FOR  [is_activ e]
  1065                                                                                                                                               EN D
  1066                                                                                                                                               ",
  1067                                                                                           'create_me ssage_stat us' =>       "
  1068                                                                                                                                                        USE  [".MAIL_DA TABASE_NAM E."]
  1069                                                                                                                                                        SET  ANSI_NULLS  ON
  1070                                                                                                                                                        SET  QUOTED_IDE NTIFIER ON
  1071                                                                                                                                                        SET  ANSI_PADDI NG ON
  1072                                                                                                                                                        CREA TE TABLE [ dbo].[mess age_status ](
  1073                                                                                                                                                                 [id] [ bigint] ID ENTITY(1,1 ) NOT NULL ,
  1074                                                                                                                                                                 [messa ge_id] [va rchar](max ) NOT NULL ,
  1075                                                                                                                                                                 [statu s_code] [t inyint] NO T NULL,
  1076                                                                                                                                                                 [recip ient] [var char](max)  NOT NULL,
  1077                                                                                                                                                                 [times tamp] [big int] NOT N ULL,
  1078                                                                                                                                                         CON STRAINT [P K_message_ status] PR IMARY KEY  CLUSTERED  ([id] ASC)
  1079                                                                                                                                                        WITH  (PAD_INDE X  = OFF,  STATISTICS _NORECOMPU TE  = OFF,  IGNORE_DU P_KEY = OF F, ALLOW_R OW_LOCKS   = ON, ALLO W_PAGE_LOC KS  = ON)  ON [PRIMAR Y]) ON [PR IMARY]
  1080                                                                                                                                                        SET  ANSI_PADDI NG OFF
  1081                                                                                                                                                        ",
  1082                                                                                                   'c reate_pati ents'=>
  1083                                                                                                   "U SE [".MAIL _DATABASE_ NAME."]
  1084                                                                                                   GO
  1085                                                                                                   
  1086                                                                                                   /* ***** Obje ct:  Table  [dbo].[pa tients]     Script Da te: 11/03/ 2014 13:03 :39 ****** /
  1087                                                                                                   SE T ANSI_NUL LS ON
  1088                                                                                                   GO
  1089                                                                                                   
  1090                                                                                                   SE T QUOTED_I DENTIFIER  ON
  1091                                                                                                   GO
  1092                                                                                                   
  1093                                                                                                   CR EATE TABLE  [dbo].[pa tients](
  1094                                                                                                                     [id] [ bigint] ID ENTITY(1,1 ) NOT NULL ,
  1095                                                                                                                     [messa ge_id] [bi gint] NOT  NULL,
  1096                                                                                                                     [given _name] [nv archar](ma x) NULL,
  1097                                                                                                                     [famil y_name] [n varchar](m ax) NULL,
  1098                                                                                                                     [date_ of_birth]  [bigint] N ULL,
  1099                                                                                                                     [title ] [nvarcha r](max) NU LL,
  1100                                                                                                                     [organ ization] [ nvarchar]( max) NULL,
  1101                                                                                                                     [file_ hash] [nva rchar](60)  NULL,
  1102                                                                                                                     [docum ent_name]  [nvarchar] (255) NULL ,
  1103                                                                                                                     CONSTR AINT [PK_p atients] P RIMARY KEY  NONCLUSTE RED
  1104                                                                                                                     (
  1105                                                                                                                                       [id] ASC
  1106                                                                                                                     )WITH  (PAD_INDEX   = OFF, S TATISTICS_ NORECOMPUT E  = OFF,  IGNORE_DUP _KEY = OFF , ALLOW_RO W_LOCKS  =  ON, ALLOW _PAGE_LOCK S  = ON) O N [PRIMARY ]
  1107                                                                                                   )  ON [PRIMAR Y]
  1108                                                                                                   
  1109                                                                                                   GO
  1110                                                                                                   
  1111                                                                                                   AL TER TABLE  [dbo].[pat ients]  WI TH CHECK A DD  CONSTR AINT [FK_p atients_me ssages] FO REIGN KEY( [message_i d])
  1112                                                                                                   RE FERENCES [ dbo].[mess ages] ([id ])
  1113                                                                                                   GO
  1114                                                                                                   
  1115                                                                                                   AL TER TABLE  [dbo].[pat ients] CHE CK CONSTRA INT [FK_pa tients_mes sages]
  1116                                                                                                   GO
  1117                                                                                                   ",
  1118                                                                                                            
  1119                                                                                           'create_ac counting_d isclosure'  =>
  1120                                                                                                                                                                 "
  1121                                                                                                                                                                 USE [" .MAIL_DATA BASE_NAME. "]
  1122                                                                                                                                                                 SET AN SI_NULLS O N       
  1123                                                                                                                                                                 SET QU OTED_IDENT IFIER ON         
  1124                                                                                                                                                                 SET AN SI_PADDING  ON
  1125                                                                                                                                                                 CREATE  TABLE [db o].[accoun ting_discl osure](
  1126                                                                                                                                                                          [id] [bi gint] IDEN TITY(1,1)  NOT NULL,
  1127                                                                                                                                                                          [message s_table_id ] [bigint]  NOT NULL,
  1128                                                                                                                                                                          [message _id] [nvar char](max)  NULL,
  1129                                                                                                                                                                          [recipie nt] [nvarc har](max)  NULL,
  1130                                                                                                                                                                          [first]  [nvarchar] (max) NULL ,
  1131                                                                                                                                                                          [last] [ nvarchar]( max) NULL,
  1132                                                                                                                                                                          [disclos ed] [bigin t] NOT NUL L,
  1133                                                                                                                                                                          [receive d] [bigint ] NULL,
  1134                                                                                                                                                                          [title]  [nvarchar] (max) NULL ,
  1135                                                                                                                                                                          [sent_to ] [nvarcha r](max) NU LL,
  1136                                                                                                                                                                          [receive d_from] [n varchar](m ax) NULL,
  1137                                                                                                                                                                          [usernam e] [nvarch ar](100) N OT NULL,
  1138                                                                                                                                                                          [facilit y] [nvarch ar](max) N ULL,
  1139                                                                                                                                                                          [purpose ] [nvarcha r](max) NU LL,
  1140                                                                                                                                                                          [ssn] [b igint] NUL L,
  1141                                                                                                                                                                          [hash] [ nchar](40)  NOT NULL,
  1142                                                                                                                                                                          [patient _id] [nvar char](50)  NULL,
  1143                                                                                                                                                                  CONST RAINT [PK_ accounting _disclosur es] PRIMAR Y KEY CLUS TERED ([id ] ASC)
  1144                                                                                                                                                                 WITH ( PAD_INDEX   = OFF, ST ATISTICS_N ORECOMPUTE   = OFF, I GNORE_DUP_ KEY = OFF,  ALLOW_ROW _LOCKS  =  ON, ALLOW_ PAGE_LOCKS   = ON) ON  [PRIMARY] ) ON [PRIM ARY]
  1145                                                                                                                                                                 SET AN SI_PADDING  OFF
  1146                                                                                                                                                                 ALTER  TABLE [dbo ].[account ing_disclo sure]  WIT H CHECK AD D  CONSTRA INT [FK_ac counting_d isclosures _mailboxes ] FOREIGN  KEY([usern ame]) REFE RENCES [db o].[mailbo xes] ([nam e])
  1147                                                                                                                                                                 ALTER  TABLE [dbo ].[account ing_disclo sure] CHEC K CONSTRAI NT [FK_acc ounting_di sclosures_ mailboxes]
  1148                                                                                                                                                                 ALTER  TABLE [dbo ].[account ing_disclo sure]  WIT H CHECK AD D  CONSTRA INT [FK_ac counting_d isclosures _messages]  FOREIGN K EY([messag es_table_i d]) REFERE NCES [dbo] .[messages ] ([id])
  1149                                                                                                                                                                 ALTER  TABLE [dbo ].[account ing_disclo sure] CHEC K CONSTRAI NT [FK_acc ounting_di sclosures_ messages]                                                                        
  1150                                                                                                                                                                 ",
  1151                                                                                                                                                                 'creat e_automati c_replies'  => "SET A NSI_NULLS  ON
  1152                                                                                                                              SET QUOT ED_IDENTIF IER ON
  1153                                                                                                                              SET ANSI _PADDING O N
  1154                                                                                                                              IF NOT E XISTS (SEL ECT * FROM  sys.objec ts WHERE o bject_id =  OBJECT_ID (N'[dbo].[ mailboxes] ') AND typ e in (N'U' ))
  1155                                                                                                                              BEGIN
  1156                                                                                                                              CREATE T ABLE mail. dbo.automa tic_replie s(
  1157                                                                                                                                       [id] [bigi nt] IDENTI TY(1,1) NO T NULL,
  1158                                                                                                                                       [mailbox_i d] [bigint ] NOT NULL ,
  1159                                                                                                                                       [start_at]  [bigint]  NULL,
  1160                                                                                                                                       [end_at] [ bigint] NU LL,
  1161                                                                                                                                       [content]  [nvarchar] (max) NOT  NULL,
  1162                                                                                                                                       [updated_a t] [bigint ] NULL,
  1163                                                                                                                                       CONSTRAINT  [PK_autom atic_repli es] PRIMAR Y KEY NONC LUSTERED ( [id] ASC)
  1164                                                                                                                                       WITH (PAD_ INDEX  = O FF, STATIS TICS_NOREC OMPUTE  =  OFF, IGNOR E_DUP_KEY  = OFF, ALL OW_ROW_LOC KS  = ON,  ALLOW_PAGE _LOCKS  =  ON) ON [PR IMARY],
  1165                                                                                                                                       UNIQUE([ma ilbox_id]) ,
  1166                                                                                                                                       CONSTRAINT  [FK_autom atic_repli es_mailbox ] FOREIGN  KEY([mailb ox_id])
  1167                                                                                                                                               RE FERENCES m ail.dbo.ma ilboxes(id ) ON DELET E CASCADE)
  1168                                                                                                                              END",
  1169                                                                                                                              'create_ automatic_ reply_log'  => "USE [ ".MAIL_DAT ABASE_NAME ."]
  1170                                                                                                                                       SET ANSI_N ULLS ON
  1171                                                                                                                                       SET QUOTED _IDENTIFIE R ON
  1172                                                                                                                                       CREATE TAB LE [dbo].[ automatic_ reply_log] (
  1173                                                                                                                                               [i d] [bigint ] IDENTITY (1,1) NOT  NULL,
  1174                                                                                                                                               [a utomatic_r eply_id] [ bigint] NO T NULL,
  1175                                                                                                                                               [e mail_addre ss] [nvarc har](max)  NOT NULL,
  1176                                                                                                                                               [s ent_at] [b igint] NUL L,
  1177                                                                                                                                        CONSTRAIN T [PK_auto matic_repl y_tracker]  PRIMARY K EY CLUSTER ED 
  1178                                                                                                                                       (
  1179                                                                                                                                               [i d] ASC
  1180                                                                                                                                       )WITH (PAD _INDEX  =  OFF, STATI STICS_NORE COMPUTE  =  OFF, IGNO RE_DUP_KEY  = OFF, AL LOW_ROW_LO CKS  = ON,  ALLOW_PAG E_LOCKS  =  ON) ON [P RIMARY]
  1181                                                                                                                                       ) ON [PRIM ARY]
  1182                                                                                                                                       ALTER TABL E [dbo].[a utomatic_r eply_log]   WITH CHEC K ADD  CON STRAINT [F K_automati c_reply_tr acker_auto matic_repl ies] FOREI GN KEY([au tomatic_re ply_id])
  1183                                                                                                                                       REFERENCES  [dbo].[au tomatic_re plies] ([i d])
  1184                                                                                                                                       ON DELETE  CASCADE
  1185                                                                                                                                       ALTER TABL E [dbo].[a utomatic_r eply_log]  CHECK CONS TRAINT [FK _automatic _reply_tra cker_autom atic_repli es]
  1186                                                                                                                                       ",
  1187                                                                                                                              'create_ file_trans fers' => " CREATE TAB LE [mail]. [dbo].[fil e_transfer s](
  1188                                                                                                                                       [id] [bigi nt] IDENTI TY(1,1) NO T NULL CON STRAINT PK _file_tran sfer PRIMA RY KEY,
  1189                                                                                                                                       [name] [nv archar](26 0) NOT NUL L,
  1190                                                                                                                                       [type] [nv archar](25 5) NOT NUL L,
  1191                                                                                                                                       [size] [bi gint] NOT  NULL,
  1192                                                                                                                                       [hash] [nc har](40) N OT NULL,
  1193                                                                                                                                       [passcode]  [nvarchar ](15) NOT  NULL,
  1194                                                                                                                                       [content]  [varbinary ](max) NOT  NULL,
  1195                                                                                                                                       [recipient ] [nvarcha r](255) NU LL,
  1196                                                                                                                                       [message_i d] [bigint ] NOT NULL  CONSTRAIN T FK_file_ transfer_t o_messages  FOREIGN K EY referen ces dbo.me ssages (id ),        
  1197                                                                                                                                       [note][nva rchar](max ) NULL,
  1198                                                                                                                                       [notify_on _download]  [bit] NOT  NULL DEFA ULT 0,
  1199                                                                                                                                       [upload_pr ogress] ti nyint DEFA ULT 0, 
  1200                                                                                                                                       [downloade d_by] [big int] NULL,
  1201                                                                                                                                       [downloade d_by_ip] [ nvarchar]( 39) NULL,
  1202                                                                                                                                       [downloade d_at] [big int] NULL,
  1203                                                                                                                                       [created_b y] [bigint ] NOT NULL ,
  1204                                                                                                                                       [created_a t] [bigint ] NOT NULL  DEFAULT D ATEDIFF(s,  '19700101 ', GETUTCD ATE()), 
  1205                                                                                                                                       [modified_ by] [bigin t] NOT NUL L,
  1206                                                                                                                                       [modified_ at] [bigin t] NOT NUL L DEFAULT  DATEDIFF(s , '1970010 1', GETUTC DATE()),
  1207                                                                                                                              );",
  1208                                                                                  ),
  1209                                                                                  
  1210                                                                                  'nhindco nfig' => a rray(
  1211                                                                                           'create_ma ilet_prope rties' =>    "
  1212                                                                                                                                                                 USE [n hindconfig ]
  1213                                                                                                                                                                 SET AN SI_NULLS O N
  1214                                                                                                                                                                 SET QU OTED_IDENT IFIER ON
  1215                                                                                                                                                                 SET AN SI_PADDING  ON
  1216                                                                                                                                                                 IF NOT  EXISTS (S ELECT * FR OM sys.obj ects WHERE  object_id  = OBJECT_ ID(N'[dbo] .[mailet_p roperties] ') AND typ e in (N'U' ))
  1217                                                                                                                                                                 BEGIN
  1218                                                                                                                                                                 CREATE  TABLE [db o].[mailet _propertie s](
  1219                                                                                                                                                                          [name] [ varchar](5 0) NOT NUL L,
  1220                                                                                                                                                                          [value]  [varchar]( max) NULL,
  1221                                                                                                                                                                  CONST RAINT [PK_ mailet_pro perties] P RIMARY KEY  CLUSTERED  ([name] A SC)
  1222                                                                                                                                                                 WITH ( PAD_INDEX   = OFF, ST ATISTICS_N ORECOMPUTE   = OFF, I GNORE_DUP_ KEY = OFF,  ALLOW_ROW _LOCKS  =  ON, ALLOW_ PAGE_LOCKS   = ON) ON  [PRIMARY] ) ON [PRIM ARY]
  1223                                                                                                                                                                 END
  1224                                                                                                                                                                 SET AN SI_PADDING  OFF
  1225                                                                                                                                                                 IF EXI STS (SELEC T * FROM s ys.objects  WHERE obj ect_id = O BJECT_ID(N '[dbo].[ma ilet_prope rties]') A ND type in  (N'U'))
  1226                                                                                                                                                                 BEGIN
  1227                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'mail. smtp.host' , N'localh ost')
  1228                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'mail. smtp.port' , N'587')
  1229                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'mail. transport. protocol',  N'smtp')
  1230                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.apina me', N'".D ATABASE_NA ME."')
  1231                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.apipa ssword', N '".DATABAS E_USERNAME ."')
  1232                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.apius ername', N '".DATABAS E_PASSWORD ."')
  1233                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.encry pt', N'tru e')
  1234                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.hostn ame', N'". first_elem ent(explod e('\\',DAT ABASE_HOST NAME))."')
  1235                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.insta nce', N'". first_elem ent(explod e(',',last _element(e xplode('\\ ',DATABASE _HOSTNAME) )))."')
  1236                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.mailn ame', N'". MAIL_DATAB ASE_NAME." ')
  1237                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.mailp assword',  N'".DATABA SE_USERNAM E."')
  1238                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.mailu sername',  N'".DATABA SE_PASSWOR D."')
  1239                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.port' , N'1433')
  1240                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.webna me', N'dir ect')
  1241                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.webpa ssword', N '')
  1242                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.db.webus ername', N '')
  1243                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.domain',  N'".CLINI CAL_DOMAIN ."')
  1244                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.error.fo lder', N'/ u01/app/ja mes-2.3.2/ store/')
  1245                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.error.ke ypass', N' ')
  1246                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.error.ke ystore', N '')
  1247                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.error.pr ivate', N' 1')
  1248                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.error.pu blic', N'' )
  1249                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.error.re fresh', N' 5')
  1250                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.error.st orepass',  N'')
  1251                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.ldap.api ', N'dc=ap i')
  1252                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.ldap.dom ain', N'". str_replac e('dc=api' ,'',LDAP_B ASE_RDN)." ')
  1253                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.ldap.hos t', N'".LD AP_HOSTNAM E."')
  1254                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.ldap.pas sword', N' ".LDAP_ANO N_ADMIN_PA SSWORD."')
  1255                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.ldap.por t', N'".LD AP_PORT."' )
  1256                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.ldap.pro tocol', N' ".((LDAP_P ORT === '6 36') ? 'ld aps' : 'ld ap')."')
  1257                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.ldap.use r_dn', N'" .LDAP_ANON _ADMIN_USE RNAME."')
  1258                                                                                                                                                                 INSERT  [dbo].[ma ilet_prope rties] ([n ame], [val ue]) VALUE S (N'maile t.notifica tion.sende r', N'noti fications@ ".CLINICAL _DOMAIN."' )
  1259                                                                                                                                                                  INSERT [db o].[mailet _propertie s] ([name] , [value])  VALUES (N 'mailet.su pportEmail ',  PII                       ')
  1260                                                                                                                                                                 END
  1261                                                                                                                                                                 ",
  1262                                                                                  ),
  1263                                                                         );
  1264                    $thi s->databas es = array (DATABASE_ NAME => $t his->datab ase_schema , MAIL_DAT ABASE_NAME  => $this- >mail_data base_schem a, 'nhindc onfig' =>  $this->nhi ndconfig_d atabase_sc hema);
  1265                    $api _dn = ldap _explode_d n(LDAP_BAS E_RDN, 0);
  1266                    unse t($api_dn[ 'count']);
  1267                    unse t($api_dn[ 0]);
  1268                    $thi s->ldap_ba se_domain  = implode( ',',$api_d n);
  1269                    $thi s->ldap_sc hema = arr ay(
  1270                                                                         LDAP_B ASE_RDN =>  array('ob jectClass'  => array( 'dcObject' ,'organiza tion','top '),'dc'=>' api','o'=> 'nodomain' ),
  1271                                                                         'ou=ad min_api_ap ps,'.LDAP_ BASE_RDN = > array('o bjectClass ' => 'grou pOfNames',  'cn' => ' Admin API  Enabled Ap plications ', 'member ' => 'cn=a dmin,'.$th is->ldap_b ase_domain , 'ou' =>  'admin_api _apps'),
  1272                                                                         'ou=ap i_admins,' .LDAP_BASE _RDN => ar ray('objec tClass' =>  'groupOfN ames', 'cn ' => 'API  Admins', ' member' =>  'cn=admin ,'.$this-> ldap_base_ domain, 'o u' => 'api _admins'),
  1273                                                                         'ou=di rect_api_a pps,'.LDAP _BASE_RDN  => array(' objectClas s' => 'gro upOfNames' , 'cn' =>  'Direct AP I Enabled  Applicatio ns', 'memb er' => 'cn =admin,'.$ this->ldap _base_doma in, 'ou' = > 'direct_ api_apps') ,
  1274                                                                         'ou=di sclosure_a pi_apps,'. LDAP_BASE_ RDN => arr ay('object Class' =>  'groupOfNa mes', 'cn'  => 'Discl osure API  Enabled Ap plications ', 'member ' => 'cn=a dmin,'.$th is->ldap_b ase_domain , 'ou' =>  'disclosur e_api_apps '),
  1275                                                                         'ou=di sabled_acc ounts,'.LD AP_BASE_RD N => array ('objectCl ass' => ar ray('organ izationalU nit','top' ), 'ou' =>  'disabled _accounts' ),
  1276                                                                         'ou=di sabled_app lications, '.LDAP_BAS E_RDN => a rray('obje ctClass' = > array('o rganizatio nalUnit',' top'), 'ou ' => 'disa bled_appli cations'),
  1277                                                                         'ou=di sabled_gro ups,'.LDAP _BASE_RDN  => array(' objectClas s' => arra y('organiz ationalUni t','top'),  'ou' => ' disabled_g roups'),
  1278                                                                         'ou=ac counts,'.L DAP_BASE_R DN => arra y('objectC lass' => a rray('orga nizational Unit','top '), 'ou' = > 'account s'),
  1279                                                                         'ou=ap plications ,'.LDAP_BA SE_RDN =>  array('obj ectClass'  => array(' organizati onalUnit', 'top'), 'o u' => 'app lications' ),
  1280                                                                         'ou=gr oups,'.LDA P_BASE_RDN  => array( 'objectCla ss' => arr ay('organi zationalUn it','top') , 'ou' =>  'groups'),
  1281                                                                         'ou=ro les,'.LDAP _BASE_RDN  => array(' objectClas s' => arra y('organiz ationalUni t','top'),  'ou' => ' roles'),
  1282                                                                         'ou=fa cilitylead er,ou=role s,'.LDAP_B ASE_RDN =>   array('o bjectClass ' => 'grou pOfNames', 'cn' => 'F acility Le ader', 'me mber' => ' cn=admin,' .$this->ld ap_base_do main, 'ou'  => 'facil ityleader' ),
  1283                                                                         'ou=gr oupleader, ou=roles,' .LDAP_BASE _RDN => ar ray('objec tClass' =>  'groupOfN ames','cn'  => 'Group  Leader',  'member' = > 'cn=admi n,'.$this- >ldap_base _domain, ' ou' => 'gr oupleader' ),
  1284                                                                );
  1285           }
  1286           
  1287           pu blic funct ion index( ) {
  1288                    $thi s->load_in stall_view ();
  1289           }
  1290           pu blic funct ion ldap()  {
  1291                    $thi s->load_in stall_view ('ldap');
  1292           }
  1293           pu blic funct ion databa se() {
  1294                    $thi s->load_in stall_view ('database ');
  1295           }
  1296           pu blic funct ion create _user() {
  1297                    $thi s->load_in stall_view ('create_u ser');
  1298           }
  1299           pu blic funct ion create _applicati on() {
  1300                    $thi s->load_in stall_view ('create_a pplication ');
  1301           }
  1302           
  1303           pu blic funct ion create _db($datab ase = DATA BASE_NAME)  {
  1304                    if($ this->inpu t->post('s a_name') & & $this->i nput->post ('sa_pwd') ) {
  1305                             $sa_na me = $this ->input->p ost('sa_na me',TRUE);
  1306                             $sa_pw d = $this- >input->po st('sa_pwd ',TRUE);
  1307                             $this- >database_ config['UI D'] = $sa_ name;
  1308                             $this- >database_ config['PW D'] = $sa_ pwd;
  1309                    }
  1310                    $con n = sqlsrv _connect($ this->data base_serve rname, $th is->databa se_config) ;
  1311                    if($ conn) {
  1312                             $query  = $this-> database_q ueries['cr eate_'.$da tabase];
  1313                             $stmt  = sqlsrv_q uery($conn , $query);
  1314                             $error s = array( );
  1315                             if($st mt) {
  1316                                      //check  the entire  query for  errors, s ince it ha s multiple  parts
  1317                                      while(!i s_null(sql srv_next_r esult($stm t))) {
  1318                                               $sql_error s = sqlsrv _errors(SQ LSRV_ERR_E RRORS);
  1319                                               if(is_arra y($sql_err ors)) {
  1320                                                       fo reach($sql _errors as  $error) {
  1321                                                                arra y_push($er rors, $err or);
  1322                                                       }
  1323                                               }
  1324                                      }
  1325                             }
  1326                             else {  $errors =  sqlsrv_er rors(SQLSR V_ERR_ERRO RS); }
  1327                             $this- >session-> set_flashd ata('creat e_db_error s', $error s);
  1328                    }
  1329                    if($ conn && $s tmt && emp ty($errors )) {
  1330                             foreac h($this->d atabases[$ database]  as $table  => $column s) {
  1331                                      $this->_ create_db_ table($tab le, $datab ase);
  1332                             }
  1333                    }
  1334                    redi rect('inst all/databa se');
  1335           }
  1336           
  1337           pu blic funct ion create _db_table( $table, $d atabase =  DATABASE_N AME) {
  1338                    $thi s->_create _db_table( $table, $d atabase);
  1339                    redi rect('inst all/databa se');
  1340           }
  1341           
  1342           pu blic funct ion encryp t_db($data base = MAI L_DATABASE _NAME) {
  1343                    if($ this->inpu t->post('s a_name') & & $this->i nput->post ('sa_pwd') ) {
  1344                             $sa_na me = $this ->input->p ost('sa_na me',TRUE);
  1345                             $sa_pw d = $this- >input->po st('sa_pwd ',TRUE);
  1346                             $this- >database_ config['UI D'] = $sa_ name;
  1347                             $this- >database_ config['PW D'] = $sa_ pwd;
  1348                    }
  1349                    $key  = $this-> input->pos t('en_key' );
  1350                    $con n = sqlsrv _connect($ this->data base_serve rname, $th is->databa se_config) ;
  1351                    if($ conn) {
  1352                             $query  = $this-> database_q ueries['en crypt_'.$d atabase];
  1353                             $query  = str_rep lace($this ->config-> item('encr yption_key '), $key,  $query);
  1354                             $stmt  = sqlsrv_q uery($conn , $query);
  1355                             $error s = array( );
  1356                             if($st mt) {
  1357                                      //check  the entire  query for  errors, s ince it ha s multiple  parts
  1358                                      while(!i s_null(sql srv_next_r esult($stm t))) {
  1359                                               $sql_error s = sqlsrv _errors(SQ LSRV_ERR_E RRORS);
  1360                                               if(is_arra y($sql_err ors)) {
  1361                                                       fo reach($sql _errors as  $error) {
  1362                                                                arra y_push($er rors, $err or);
  1363                                                       }
  1364                                               }
  1365                                      }
  1366                             }
  1367                             else {  $errors =  sqlsrv_er rors(SQLSR V_ERR_ERRO RS); }
  1368                             $this- >session-> set_flashd ata('encry pt_db_erro rs', $erro rs);
  1369                    }
  1370                    redi rect('inst all/databa se');
  1371           }
  1372           
  1373           pu blic funct ion regene rate_passw ords(){
  1374                    $thi s->load->d atabase();
  1375                    $que ry = $this ->db->get( 'users');
  1376                    if($ query){
  1377                             $users  = $query- >result();
  1378                             echo " <h3>Regene rate Passw ords</h3>" ;
  1379                             foreac h ($users  as $user){
  1380           
  1381                                      $uid = $ user->user name;
  1382                                      $ep = $t his->rando m_password ();
  1383           
  1384                                      echo "$u id: ";
  1385                                      if($this ->is_ascii ($ep)){
  1386                                               echo "Upda ting Datab ase";
  1387                                               $query = $ this->db-> query("UPD ATE users  SET user_e p=".$this- >db->escap e($this->e ncrypt->en code($ep)) ." WHERE u sername="  . $this->d b->escape( $uid));
  1388                                               echo "..." ;
  1389                                               if($query)  {
  1390                                                       ec ho '<span  style="col or:green"> OK</span>' ;
  1391                                                       ec ho '...Upd ating LDAP ...';
  1392                                                       $l dap_conn =  $this->pr epare_ldap _conn();
  1393                                                       $l dap_bind =  @ldap_bin d($ldap_co nn, LDAP_A NON_ADMIN_ USERNAME,  LDAP_ANON_ ADMIN_PASS WORD);
  1394                                                       if ($ldap_bin d) {
  1395                                                                $dn  = 'uid='.$ uid.','.LD AP_ACCOUNT _GROUP;
  1396                                                                if($ this->ldap _entry_exi sts($ldap_ conn, $dn) ) {
  1397                                                                         $succe ss = ldap_ modify($ld ap_conn, $ dn, array( 'userPassw ord' => $t his->encry pt->ssha25 6_encode($ ep)));
  1398                                                                         if($su ccess) {
  1399                                                                                  echo '<s pan style= "color:gre en">OK</sp an>';
  1400                                                                         }
  1401                                                                         else {
  1402                                                                                  echo '<s pan style= "color:red ">Error: U nable to m odify LDAP  account</ span>';
  1403                                                                         }
  1404                                                                }
  1405                                                                else  {
  1406                                                                         echo ' <span styl e="color:r ed">Error:  Unable to  locate LD AP account </span>';
  1407                                                                }
  1408                                                       }
  1409                                                       el se {
  1410                                                                echo  '<span st yle="color :red">Erro r: Unable  to bind to  LDAP</spa n>';
  1411                                                       }
  1412                                               }
  1413                                               else {
  1414                                                       ec ho '<span  style="col or:red">Er ror: Unabl e to find  user in da tabase</sp an>';
  1415                                               }       
  1416                                      }
  1417                                      echo "<b r/>";
  1418                             }
  1419                    }
  1420                    else {
  1421                             echo " Could not  get users" ;
  1422                    }
  1423                    echo  '<br/><a  href="/ins tall/regen erate_pass words">Ref resh</a>';
  1424                    echo  '<br/><a  href="/ins tall">Back </a>';
  1425           }
  1426           
  1427           pr ivate func tion _crea te_db_tabl e($table,  $database)  {
  1428                    if($ this->inpu t->post('s a_name') & & $this->i nput->post ('sa_pwd') ) {
  1429                             $sa_na me = $this ->input->p ost('sa_na me',TRUE);
  1430                             $sa_pw d = $this- >input->po st('sa_pwd ',TRUE);
  1431                             $this- >database_ config['UI D'] = $sa_ name;
  1432                             $this- >database_ config['PW D'] = $sa_ pwd;
  1433                    }
  1434                    if(a rray_key_e xists($tab le, $this- >databases [$database ])) {
  1435                             $conn  = sqlsrv_c onnect($th is->databa se_servern ame, $this ->database _config);
  1436                             if($co nn) {
  1437                                      $query =  $this->da tabase_tab le_queries [$database ]['create_ '.$table];
  1438                                      $stmt =  sqlsrv_que ry($conn,  $query);
  1439                                      $errors  = array();
  1440                                      if($stmt ) {
  1441                                               //check th e entire q uery for e rrors, sin ce it has  multiple p arts
  1442                                               while(!is_ null(sqlsr v_next_res ult($stmt) )) {
  1443                                                       $s ql_errors  = sqlsrv_e rrors(SQLS RV_ERR_ERR ORS);
  1444                                                       if (is_array( $sql_error s)) {
  1445                                                                fore ach($sql_e rrors as $ error) {
  1446                                                                         array_ push($erro rs, $error );
  1447                                                                }
  1448                                                       }
  1449                                               }
  1450                                              
  1451                                      }
  1452                                      else {
  1453                                               $errors =  sqlsrv_err ors(SQLSRV _ERR_ERROR S);
  1454                                      }
  1455                                      //if we  found erro rs
  1456                                      if(!empt y($errors) ) {
  1457                                               $this->ses sion->set_ flashdata( $table.'_e rrors',$er rors);
  1458                                               $this->ses sion->set_ flashdata( $table.'_q uery',$que ry);
  1459                                      }
  1460                             }
  1461                             else {
  1462                                      $this->s ession->se t_flashdat a($table.' _errors',s qlsrv_erro rs());
  1463                                      $this->s ession->se t_flashdat a($table.' _query',$q uery);
  1464                             }
  1465                    }
  1466                    else  {
  1467                             $this- >session-> set_flashd ata($table .'_errors' ,'This tab le does no t exist in  the confi gured sche ma.');
  1468                             $this- >session-> set_flashd ata($table .'_query', $query);
  1469                    }
  1470           }
  1471           
  1472           pr ivate func tion load_ install_vi ew($page =  'database ') {
  1473                    $thi s->load->h elper('for m_helper') ;
  1474                    $thi s->output- >append_ou tput('
  1475                             <!doct ype html>
  1476                             <html>
  1477                                      <head>
  1478                                               <title>'.$ this->titl e.'</title >
  1479                                      </head>
  1480                                      <body>
  1481                                               <div class ="wrapper" >
  1482                                                       <d iv class=" nav">
  1483   <!--                                                         <a h ref="/inst all/databa se">Databa se</a>
  1484                                                                <a h ref="/inst all/ldap"> LDAP</a>
  1485                                                                <a h ref="/inst all/create _user">Cre ate User</ a>
  1486                                                                <a h ref="/inst all/create _applicati on">Create  Applicati on</a>
  1487                                                                <a h ref="/inst all/utf8_c onversion" >UTF8 Conv ersion</a>
  1488                                                                <a h ref="/inst all/regene rate_passw ords">Rege nerate Pas swords</a>
  1489                                                                <a h ref="/inst all/popula te_patient s_for_mess ages">Popu late Patie nts</a> -- >
  1490                                                                <a h ref="/inst all/popula te_patient _document_ names">Pop ulate Pati ents docs< /a>
  1491                                                                <a h ref="/inst all/check_ patient_do cument_nam es">check  patient do cs</a>
  1492                                                       </ div>
  1493                                                       <d iv>
  1494                    ');
  1495                    if($ page === ' database')  { 
  1496                             $this- >output->a ppend_outp ut('<h2>Da tabase</h2 >');
  1497                             foreac h($this->d atabases a s $databas e => $sche ma) {
  1498                                      $this->o utput->app end_output ($this->db _configura tion_table ($database ));
  1499                             }
  1500                    }
  1501                    else  if($page  === 'ldap' ) {
  1502                             $this- >output->a ppend_outp ut('<h2>LD AP</h2>');
  1503                             $this- >output->a ppend_outp ut($this-> ldap_confi guration_t able());
  1504                    }
  1505                    else  if($page  === 'creat e_user'){
  1506                             $this- >output->a ppend_outp ut('<h2>Cr eate User< /h2>');
  1507                             $this- >output->a ppend_outp ut($this-> create_use r_form());
  1508                    }
  1509                    else  if($page  === 'creat e_applicat ion'){
  1510                             $this- >output->a ppend_outp ut('<h2>Cr eate Appli cation</h2 >');
  1511                             $this- >output->a ppend_outp ut($this-> create_app lication_f orm());
  1512                    }
  1513                    else  if($page  === 'utf8_ conversion '){
  1514                             $this- >utf8_conv ersion();
  1515                    }
  1516                    $thi s->output- >append_ou tput('
  1517                                                       </ div>
  1518                                               </div>
  1519                                      </body>
  1520                             </html >
  1521                    ');
  1522           }
  1523           pr ivate func tion creat e_user_for m() {
  1524                    $out put = '';
  1525                    $thi s->load->h elper('for m');
  1526                    $out put .= for m_open('in stall/crea te_user_su bmit');
  1527                    $out put .= '<t able>';
  1528                    $out put .= '<t r><td>'.fo rm_label(' Username', 'username' ).'</td>';
  1529                    $out put .= '<t d>'.form_i nput(array ('id'=>'us ername','n ame'=>'use rname')).' </td>';
  1530                    $out put .= '<t d>'.form_l abel('ID', 'user_id') .'</td>';
  1531                    $out put .= '<t d>'.form_i nput(array ('id'=>'us er_id','na me'=>'user _id')).'</ td></tr>';
  1532                    $out put .= '<t r><td>'.fo rm_label(' First Name ','first_n ame').'</t d>';
  1533                    $out put .= '<t d>'.form_i nput(array ('id'=>'fi rst_name', 'name'=>'f irst_name' )).'</td>' ;
  1534                    $out put .= '<t d>'.form_l abel('Last  Name','la st_name'). '</td>';
  1535                    $out put .= '<t d>'.form_i nput(array ('id'=>'la st_name',' name'=>'la st_name')) .'</td></t r>';
  1536                    $out put .= '<t r><td>'.fo rm_label(' Middle Nam e','middle _name').'< /td>';
  1537                    $out put .= '<t d>'.form_i nput(array ('id'=>'mi ddle_name' ,'name'=>' middle_nam e')).'</td >';
  1538                    $out put .= '<t d>'.form_l abel('Emai l Address' ,'user_ema il').'</td >';
  1539                    $out put .= '<t d>'.form_i nput(array ('id'=>'us er_email', 'name'=>'u ser_email' )).'</td>< /tr>';
  1540                    $out put .= '</ table>';
  1541                    $out put .= for m_submit(' create_use r_submit', 'Create Us er');
  1542                    $out put .= for m_close();
  1543                    $thi s->change_ database(' api');
  1544                    $thi s->load->m odel('user smodel');
  1545                    $use rs = $this ->usersmod el->get_us ers();
  1546                    $out put .= '<t able borde r="1" styl e="border- collapse:c ollapse;"> ';
  1547                    $out put .= '<t r><th>Data base ID</t h><th>User name</th>< th>Org ID< /th></tr>' ;
  1548                    fore ach ($user s as $user ){
  1549                             $outpu t .= '<tr> <td>'.$use r->user_id .'</td><td >'.$user-> username.' </td><td>' .$user->us er_org_id. '</td></tr >';
  1550                    }
  1551                    retu rn $output ;
  1552           }
  1553           pr ivate func tion creat e_applicat ion_form()  {
  1554                    $out put = '';
  1555                    $thi s->load->h elper('for m');
  1556                    $out put .= for m_open('in stall/crea te_applica tion_submi t');
  1557                    $out put .= '<t able>';
  1558                    $out put .= '<t r><td>'.fo rm_label(' Name','nam e').'</td> ';
  1559                    $out put .= '<t d>'.form_i nput(array ('id'=>'na me','name' =>'name')) .'</td>';
  1560                    $out put .= '<t d>'.form_l abel('URL' ,'url').'< /td>';
  1561                    $out put .= '<t d>'.form_i nput(array ('id'=>'ur l','name'= >'url')).' </td></tr> ';
  1562                    $out put .= '<t r><td>'.fo rm_label(' Descriptio n','descri ption').'< /td>';
  1563                    $out put .= '<t d colspan= "3">'.form _input(arr ay('id'=>' descriptio n','name'= >'descript ion','styl e'=>'width :99%')).'< /td></tr>' ;
  1564                    $out put .= '<t r><td>'.fo rm_label(' Justificat ion','just ').'</td>' ;
  1565                    $out put .= '<t d colspan= "3">'.form _input(arr ay('id'=>' just','nam e'=>'just' ,'style'=> 'width:99% ')).'</td> </tr>';
  1566                    $out put .= '<t r><td>'.fo rm_label(' POC Name', 'poc_name' ).'</td>';
  1567                    $out put .= '<t d>'.form_i nput(array ('id'=>'po c_name','n ame'=>'poc _name')).' </td>';
  1568                    $out put .= '<t d>'.form_l abel('POC  Email','po c_email'). '</td>';
  1569                    $out put .= '<t d>'.form_i nput(array ('id'=>'po c_email',' name'=>'po c_email')) .'</td></t r>';
  1570                    $out put .= '<t r><td>'.fo rm_label(' POC Phone' ,'poc_phon e').'</td> ';
  1571                    $out put .= '<t d>'.form_i nput(array ('id'=>'po c_phone',' name'=>'po c_phone')) .'</td>';
  1572                    $out put .= '<t d>'.form_l abel('Admi n DB ID',' uid').'</t d>';
  1573                    $out put .= '<t d>'.form_i nput(array ('id'=>'ui d','name'= >'uid')).' </td></tr> ';
  1574                    $out put .= '</ table>';
  1575                    $out put .= for m_submit(' create_app lication_s ubmit','Cr eate Appli cation');
  1576                    $out put .= for m_close();
  1577                    $thi s->change_ database(' api');
  1578                    $thi s->load->m odel('appl icationmod el');
  1579                    $app lications  = $this->a pplication model->get _applicati ons();
  1580                    if($ applicatio ns){
  1581                             $appli cations =  $applicati ons->resul t();
  1582                             $outpu t .= '<tab le border= "1" style= "border-co llapse:col lapse;">';
  1583                             $outpu t .= '<tr> <th>ID</th ><th>Name< /th><th>Pu blic Key</ th><th>Pri vate Key</ th></tr>';
  1584                             foreac h ($applic ations as  $applicati on){
  1585                                      $output  .= '<tr st yle="white -space: no wrap;"><td >'.$applic ation->id. '</td><td> '.$applica tion->name .'</td><td >'.$applic ation->pub lic_key.'< /td><td>'. $applicati on->privat e_key.'</t d></tr>';
  1586                             }
  1587                    }
  1588                    
  1589                    retu rn $output ;
  1590           }
  1591           pu blic funct ion create _applicati on_submit( ) {
  1592                    $nam e = $this- >input->po st('name',  TRUE);
  1593                    $url  = $this-> input->pos t('url', T RUE);
  1594                    $des c = $this- >input->po st('descri ption', TR UE);
  1595                    $jus t = $this- >input->po st('just',  TRUE);
  1596                    $poc _name = $t his->input ->post('po c_name', T RUE);
  1597                    $poc _email = $ this->inpu t->post('p oc_email',  TRUE);
  1598                    $poc _phone = $ this->inpu t->post('p oc_phone',  TRUE);
  1599                    $uid  = $this-> input->pos t('uid', T RUE);
  1600                    $thi s->load->m odel('appl icationmod el');
  1601                    $pub lic = hash ('sha256',  openssl_r andom_pseu do_bytes(3 2));
  1602                    $pri vate = has h('sha256' , openssl_ random_pse udo_bytes( 32));
  1603                    
  1604                    $app lication_r equest = A pplication _request:: create(arr ay(
  1605                                      'name' = > $name,
  1606                                      'request or' => $ui d,
  1607                                      'url' =>  $url,
  1608                                      'descrip tion' => $ desc,
  1609                                      'justifi cation' =>  $just,
  1610                                      'poc_nam e' => $poc _name,
  1611                                      'poc_ema il' => $po c_email,
  1612                                      'poc_pho ne' => $po c_phone,
  1613                                      'request ed_date' = > now()
  1614                    ));               
  1615                    
  1616                    if(A pplication _request:: is_an_enti ty($applic ation_requ est)){
  1617  
  1618                             $appli cation_req uest->appr ove();
  1619                             if($th is->applic ationmodel ->create_a pplication ($public,  $private,  $name, $ui d, $url, $ desc, $poc _name, $po c_email, $ poc_phone,  $ids[0]-> id)){
  1620                                      $id = $t his->appli cationmode l->get_app lication_i d_by_name( $name);
  1621                                      if($id){
  1622                                               $ldap_conn  = $this-> prepare_ld ap_conn();
  1623                                               $ldap_bind  = ldap_bi nd($ldap_c onn, LDAP_ ANON_ADMIN _USERNAME,  LDAP_ANON _ADMIN_PAS SWORD);
  1624                                               ldap_mod_a dd($ldap_c onn,LDAP_A DMIN_API_P ERMISSIONS _GROUP,arr ay('member ' => $this ->applicat ionmodel-> get_dn_fro m_app_id($ id)));
  1625                                               $this->ses sion->set_ flashdata( 'messages' ,'Successf ully creat ed applica tion.');
  1626                                      }else{
  1627                                               $this->ses sion->set_ flashdata( 'errors',' Failed to  get applic ation id.' );
  1628                                      }
  1629                             }
  1630                             else {
  1631                                      $this->s ession->se t_flashdat a('errors' ,'Failed t o create a pplication .');
  1632                             }
  1633                    }
  1634                    else {
  1635                             $this- >session-> set_flashd ata('error s','Failed  to create  applicati on.');
  1636                    }
  1637                    redi rect('inst all/create _applicati on');
  1638           }
  1639           pu blic funct ion create _user_subm it() {
  1640                    $use rname = $t his->input ->post('us ername', T RUE);
  1641                    $id  = $this->i nput->post ('user_id' , TRUE);
  1642                    $fir st = $this ->input->p ost('first _name', TR UE);
  1643                    $las t = $this- >input->po st('last_n ame', TRUE );
  1644                    $mid dle = $thi s->input-> post('midd le_name',  TRUE);
  1645                    $mai l = $this- >input->po st('user_e mail', TRU E);
  1646                    $thi s->load->m odel('user smodel');
  1647                    $lda p_attribut es = array (
  1648                                      'givenNa me' => $fi rst,
  1649                                      'sn' =>  $last,
  1650                                      'cn' =>  $first.' ' .$last,
  1651                    );
  1652                    if(! empty($mid dle)) {
  1653                             $ldap_ attributes ['initials '] = $midd le;
  1654                             $ldap_ attributes ['displayN ame'] = $l ast.', '.$ first.' '. $middle;
  1655                    }
  1656                    $def ault_ldap_ attributes  = array(  'objectCla ss' => arr ay('posixA ccount', ' top', 'per son', 'org anizationa lPerson',  'inetOrgPe rson'),
  1657                                      'gidNumb er' => '50 00',
  1658                                      'uidNumb er' => '50 00',
  1659                                      'cn' =>  $ldap_attr ibutes['gi venName']. ' '.$ldap_ attributes ['sn']); / /uid, home idrectory,  & mail wi ll be adde d once we' ve success fully save d the user
  1660                    $lda p_attribut es = array _merge($ld ap_attribu tes, $defa ult_ldap_a ttributes) ;
  1661                    if(! array_key_ exists('di splayName' , $ldap_at tributes))
  1662                             $ldap_ attributes ['displayN ame'] = $l dap_attrib utes['sn'] .', '.$lda p_attribut es['givenN ame'];
  1663                    $lda p_conn = $ this->prep are_ldap_c onn();
  1664                    $lda p_bind = l dap_bind($ ldap_conn,  LDAP_ANON _ADMIN_USE RNAME, LDA P_ANON_ADM IN_PASSWOR D);
  1665                    if(! $ldap_bind ) return $ this->erro r->warning ("I couldn 't create  user ".$th is->error- >describe( $username) ." because  I couldn' t connect  to LDAP; p lease chec k your con fig file") ;
  1666                    
  1667                    //cr eate the u ser, now t hat we kno w we have  the right  set-up
  1668                    $thi s->load->l ibrary('en crypt');
  1669                    $pas sword = $t his->rando m_password ();
  1670                    $lda p_attribut es['userPa ssword'] =  $this->ss ha256_enco de($passwo rd);
  1671                    $thi s->change_ database(' api');
  1672                    $use r = User:: create( ar ray('usern ame' => $u sername,
  1673                                      'user_or g_id' => $ id,
  1674                                      'user_ex t_mail' =>  $mail,
  1675                                      'user_ep ' => $this ->encrypt- >encode($p assword))) ;
  1676                    
  1677                    if(! User::is_a n_entity($ user)){ // the User c lass will  trigger an  error as  needed.  M ailbox cre ation/clea nup will b e handled  by the Use r class as  needed.
  1678                             $this- >session-> set_flashd ata('error s', 'Could  not creat e user');
  1679                             return  false;
  1680                    }
  1681                    //se t up the r emainder o f our ldap _attribute s
  1682                    $lda p_attribut es['uid']  = $user->u sername;
  1683                    $lda p_attribut es['homeDi rectory']  = '/var/ma ilboxes/'. $user->use rname;
  1684                    $lda p_attribut es['mail']  = $user-> mailbox->e mail_addre ss();
  1685                    
  1686                    $suc cess = lda p_add($lda p_conn, $t his->users model->get _dn_from_u sername($u sername),$ ldap_attri butes);
  1687                    if(! $success){
  1688                             $this- >session-> set_flashd ata('error s', 'Could  not creat e LDAP ent ry for '.$ user->desc ribe());
  1689                             if(!Us er::delete ($user->id )) $this-> error->war ning('Coul d not remo ve '.$user ->describe ().' from  the databa se; please  manually  remove the  user and  mailbox en tries from  the datab ase as nee ded.');
  1690                    }
  1691                    else {
  1692                             $this- >load->mod el('accoun trequestmo del');
  1693                             $this- >accountre questmodel ->create_r equest($fi rst, $midd le, $last,  $mail, nu ll, null,  null, null , null, nu ll , null,  $id);
  1694                             $r_id= $this->acc ountreques tmodel->ge t_ids($id) ;
  1695                             if($r_ id){
  1696                                      $r_id =  $r_id->res ult();
  1697                                      $this->a ccountrequ estmodel-> approve_re quest($r_i d[0]->id);
  1698                             }
  1699                             $this- >usersmode l->change_ group_memb ership('ad d',$user-> id,"API Ad mins");
  1700                             $this- >session-> set_flashd ata('messa ges','Succ essfully c reated use r with id  $user->id( ).');
  1701                    }
  1702                    
  1703                    
  1704                    
  1705                    redi rect('inst all/create _user');
  1706           }
  1707           
  1708           pr ivate func tion ldap_ configurat ion_table( ) {
  1709                    $thi s->load->h elper('for m');
  1710                    $out put = '';
  1711                    $lda p_dns = ar ray();
  1712                    $lda p_conn = $ this->prep are_ldap_c onn();
  1713                    $lda p_bind = @ ldap_bind( $ldap_conn , LDAP_ANO N_SEARCH_U SERNAME, L DAP_ANON_S EARCH_PASS WORD);
  1714                    if($ ldap_bind)  {
  1715                             $searc h = @ldap_ list($ldap _conn, $ba se_dn, '(o bjectClass =*)');
  1716                             $resul t = @ldap_ get_entrie s($ldap_co nn, $searc h);
  1717                             $outpu t .= '<tab le style=" border: so lid black  1px;">';
  1718                             $outpu t .= '<tr> <th>Requir ed LDAP Sc hema</th>< th>Status< /th></tr>' ;
  1719                             foreac h($this->l dap_schema  as $dn =>  $values)  {
  1720                                      if($this ->ldap_ent ry_exists( $ldap_conn , $dn)) {
  1721                                               $output .=  '<tr><td  style="col or: green; ">'.$dn.'< td><td sty le="color:  green;">& #x2714;</t d></tr>';
  1722                                      }
  1723                                      else { $ output .=  '<tr><td s tyle="colo r: red;">' .$dn.'<td> <td style= "color: re d;">&#x271 7;</td><td >'.form_op en('/insta ll/create_ ldap_entry /'.rawurle ncode(base 64_encode( $dn))).for m_submit(' create','C reate').fo rm_close() .'</td></t r>'; }
  1724                             }
  1725                             $outpu t .= '</ta ble>';
  1726                    }
  1727                    else  { $output  .= '<div  style="max -width: 10 00px; back ground: #f ef1ec; bor der: solid  1px #900;  border-ra dius: 5px;  padding:  5px; margi n-bottom:  5px;">'.ld ap_error($ ldap_conn) .'</div>';  }
  1728                    retu rn $output ;
  1729           }
  1730           
  1731           pr ivate func tion load_ ldap_view( ) {
  1732                    $thi s->output- >append_ou tput('<div >');
  1733                    $thi s->output- >append_ou tput('<h2> LDAP</h2>' );
  1734                    $lda p_status =  $this->ch eck_ldap_c onfigurati on();
  1735                    if($ ldap_statu s['status' ] === FALS E) {
  1736                             $this- >output->a ppend_outp ut('<div>' .$ldap_sta tus['messa ge'].'</di v>');
  1737                             $this- >output->a ppend_outp ut(form_op en('/insta ll/create_ ldap'));
  1738                             $this- >output->a ppend_outp ut('<div c lass="form " style="f loat: none ;">');
  1739                             $this- >output->a ppend_outp ut('<label  for="sa_n ame">LDAP  admin pass word</labe l><input t ype="passw ord" id="l dap_pwd" n ame="ldap_ pwd" /><br  /><br />' );
  1740                             $this- >output->a ppend_outp ut('</div> ');
  1741                             $this- >output->a ppend_outp ut('<div c lass="cent er"><input  type="sub mit" value ="Create L DAP Entry" /></div>') ;
  1742                             $this- >output->a ppend_outp ut(form_cl ose());
  1743                    }
  1744                    else {
  1745                             $this- >output->a ppend_outp ut('<h2>LD AP <span s tyle="colo r: green;" >&#x2713;< /span></h2 >');
  1746                    }
  1747                    $thi s->output- >append_ou tput('</di v>');
  1748           }
  1749           
  1750           pr ivate func tion _db_c onnects()  {
  1751                    $con nects = FA LSE;
  1752                    $con n = sqlsrv _connect($ this->data base_serve rname, $th is->databa se_config) ;
  1753                    if($ conn) { 
  1754                             $conne cts = TRUE
  1755                             sqlsrv _close($co nn);
  1756                    }
  1757                    else  {
  1758                             if(sql srv_errors ()) {
  1759                                      $this->s ession->se t_flashdat a('db_conn ects_error s', sqlsrv _errors()) ;
  1760                             }
  1761                    }
  1762                    retu rn $connec ts;
  1763           }
  1764           
  1765           pr ivate func tion _db_e xists($dat abase = DA TABASE_NAM E) {
  1766                    $con n = sqlsrv _connect($ this->data base_serve rname, $th is->databa se_config) ;
  1767                    if($ conn) {
  1768                             $db_ex ist_query  = "SELECT  name FROM  master.sys .databases  WHERE nam e = N'".$d atabase."' ";
  1769                             $stmt  = sqlsrv_q uery($conn , $db_exis t_query, a rray(), ar ray('Scrol lable'=>'b uffered')) ;
  1770                             if($st mt) {
  1771                                      $num_row s = sqlsrv _num_rows( $stmt);
  1772                                      if($num_ rows && ($ num_rows >  0)) { ret urn TRUE;  }
  1773                                      //db doe s not exis t yet, or  possibly w e don't ha ve permiss ions to se e it
  1774                                      else { r eturn FALS E; }
  1775                             }
  1776                             else {
  1777                                      $errors  = array();
  1778                                      foreach( sqlsrv_err ors() as $ error) {
  1779                                               array_push ($errors,  $error);
  1780                                      }
  1781                                      $this->s ession->se t_flashdat a('db_exis ts_errors' , $errors) ;
  1782                             }
  1783                    }
  1784                    retu rn FALSE;
  1785           }
  1786           
  1787           pr ivate func tion _db_p ermissions _set($data base = DAT ABASE_NAME , $user =  DATABASE_U SERNAME, $ permission s = NULL)  {
  1788                    //if  permissio ns to chec k are not  provided b y the func tion call,  set them  from defau lts
  1789                    $req uired_perm issions =  empty($per missions)  ? $this->d b_required _permissio ns : $perm issions;
  1790                    $con n = sqlsrv _connect($ this->data base_serve rname, $th is->databa se_config) ;
  1791                    if($ conn) {
  1792                             $permi ssion_quer y = "USE [ ".$databas e."]; EXEC  sp_helpro lemember";
  1793                             $stmt  = sqlsrv_q uery($conn , $permiss ion_query) ;
  1794                             if($st mt) {
  1795                                      do {
  1796                                               while($row  = sqlsrv_ fetch_arra y($stmt))  {
  1797                                                       if ($row['Mem berName']  === $user)  {
  1798                                                                if(a rray_key_e xists($row ['DbRole'] , $require d_permissi ons)) {
  1799                                                                         $requi red_permis sions[$row ['DbRole'] ] = TRUE;
  1800                                                                }
  1801                                                       }
  1802                                               }
  1803                                      }
  1804                                      while(sq lsrv_next_ result($st mt));
  1805                             }
  1806                             else {
  1807                                      $this->s ession->se t_flashdat a('db_perm issions_se t_errors',  sqlsrv_er rors());
  1808                             }
  1809                    }
  1810                    //if  permissio ns are mis sing, set  which ones  are missi ng in flas hdata to d isplay
  1811                    if(( in_array(F ALSE, $req uired_perm issions)))  {
  1812                             $missi ng_permiss ions = arr ay();
  1813                             foreac h($require d_permissi ons as $ke y => $perm ission) {
  1814                                      if(!$per mission) {  array_pus h($missing _permissio ns, $key);  }
  1815                             }
  1816                             $this- >session-> set_flashd ata('db_pe rmissions_ missing',  $missing_p ermissions );
  1817                    }
  1818                    retu rn !(in_ar ray(FALSE,  $required _permissio ns));
  1819           }
  1820           
  1821           pr ivate func tion _db_e ncrypted($ database =  MAIL_DATA BASE_NAME)  {
  1822                    $con n = sqlsrv _connect($ this->data base_serve rname, $th is->databa se_config) ;
  1823                    if($ conn) {
  1824                             $db_en crypted_qu ery = "SEL ECT sys.da tabases.na me, sys.dm _database_ encryption _keys.data base_id, e ncryption_ state  FRO M sys.dm_d atabase_en cryption_k eys JOIN s ys.databas es ON (sys .dm_databa se_encrypt ion_keys.d atabase_id  = sys.dat abases.dat abase_id)  WHERE sys. dm_databas e_encrypti on_keys.en cryption_s tate = 3 A ND sys.dat abases.nam e = '".$da tabase."'" ;
  1825                             $stmt  = sqlsrv_q uery($conn , $db_encr ypted_quer y, array() , array('S crollable' =>'buffere d'));
  1826                             if($st mt) {
  1827                                      $num_row s = sqlsrv _num_rows( $stmt);
  1828                                      if($num_ rows && ($ num_rows >  0)) { ret urn TRUE;  }
  1829                                      //db is  not encryp ted yet, o r possibly  we don't  have permi ssions to  see if it  is
  1830                                      else { r eturn FALS E; }
  1831                             }
  1832                             else {
  1833                                      $errors  = array();
  1834                                      foreach( sqlsrv_err ors() as $ error) {
  1835                                               array_push ($errors,  $error);
  1836                                      }
  1837                                      $this->s ession->se t_flashdat a('db_encr ypted_erro rs', $erro rs);
  1838                             }
  1839                    }
  1840                    retu rn FALSE;
  1841           }
  1842           
  1843           pu blic funct ion db_con figuration _table($da tabase = D ATABASE_NA ME) {
  1844                    $thi s->load->h elper('for m');
  1845                    $out put = '';
  1846                    //ch eck databa se permiss ions / con nection /  database e xistence
  1847                    $db_ connected  = $this->_ db_connect s();
  1848                    $db_ exists = $ this->_db_ exists($da tabase);
  1849                    $db_ encrypted  = $this->_ db_encrypt ed($databa se);
  1850                    $per missions_s et = $this ->_db_perm issions_se t($databas e);
  1851                    
  1852                    $out put .= '<h 3>'.$datab ase.'</h3> ';
  1853                    //if  connectio n calls fa ils
  1854                    if(! $db_connec ted) {
  1855                             $error s = $this- >session-> flashdata( 'db_connec ts_errors' );
  1856                             if($er rors) {
  1857                                      if(is_ar ray($error s)) {
  1858                                               foreach($e rrors as $ error) {
  1859                                                       // orig. code  looking f or the ent ire messag e within a  substring  of the me ssage - I' m assuming  this was  a mistake  -- MG 2014 -05-21
  1860                                                       if (string_co ntains('is  not able  to access  the databa se "master " under th e current  security c ontext', $ error['mes sage'])) {  $permissi on_issue =  TRUE; }
  1861                                                       $o utput .= ' <div style ="max-widt h: 1000px;  backgroun d: #fef1ec ; border:  solid 1px  #900; bord er-radius:  5px; padd ing: 5px;  margin-bot tom: 5px;" >'.$error[ 'message'] .'</div>';
  1862                                               }
  1863                                      }
  1864                             }
  1865                             //if e rrors are  missing (a nd there h ad to be s ome if we  are here),  flashdata  is full
  1866                             else {
  1867                                      $output  .= '<div s tyle="max- width: 100 0px; backg round: #fe f1ec; bord er: solid  1px #900;  border-rad ius: 5px;  padding: 5 px; margin -bottom: 5 px;">Conne ction erro rs encount ered. Refr esh page f or more de tails.</di v>';
  1868                             }
  1869                             //if t here is a  permission s error wi th the mas ter db, we  can't do  anything r eally, giv e all the 
  1870                             //quer ies necess ary to set  up the da tabase as  raw text f or manual  set-up
  1871                             if(iss et($permis sion_issue ) && $perm ission_iss ue) {
  1872                                      $output  .= '<div s tyle="max- width: 100 0px; backg round: #fe f1ec; bord er: solid  1px #900;  border-rad ius: 5px;  padding: 5 px; margin -bottom: 5 px;">
  1873                                                                A pe rmissions  issue is p reventing  retrieval  of informa tion from  the master  database  that will  allow this  script to  determine  if the re quired dat abase, tab les, and p ermissions
  1874                                                                exis t for the  configured  user. Thi s is most  likely due  to securi ty restric tions that  have been  purposefu lly set in  place. 
  1875                                                                Howe ver, it is  not possi ble for th is script  to proceed  with auto mated set- up of the  database.  The querie s required  to set up
  1876                                                                the  database h ave been p rovided be low for a  database a dministrat or to set  up manuall y.
  1877                                                                </di v>';
  1878                                      $output  .= '<h3>Cr eate requi red databa ses</h3>';
  1879                                      foreach( $this->dat abase_quer ies as $ke y => $quer y) {
  1880                                               if(string_ contains($ key, 'crea te')) {
  1881                                                       $o utput .= ' <pre>'.pre g_replace( '/[\t]+/', ' ',$query ).'</pre>' ;
  1882                                               }
  1883                                      }
  1884                                      $output  .= '<h3>Cr eate requi red tables </h3>';
  1885                                      foreach( $this->dat abase_tabl e_queries[ $database]  as $key = > $query)  {
  1886                                               if(string_ contains($ key, 'crea te')) {
  1887                                                       $o utput .= ' <pre>'.pre g_replace( '/[\t]+/', ' ',$query ).'</pre>' ;
  1888                                               }
  1889                                      }
  1890                             }
  1891                    }
  1892                    //if  db existe nce call f ails
  1893                    if($ db_connect ed && !$db _exists) {
  1894                             $error s = $this- >session-> flashdata( 'db_exists _errors')  ? $this->s ession->fl ashdata('d b_exists_e rrors') :  array();
  1895                             $creat e_errors =  $this->se ssion->fla shdata('cr eate_db_er rors') ? $ this->sess ion->flash data('crea te_db_erro rs') : arr ay();
  1896                             $error s = array_ merge($err ors, $crea te_errors) ;
  1897                             $error s = empty( $errors) ?  FALSE : $ errors;
  1898                             if($er rors) {
  1899                                      if(is_ar ray($error s)) {
  1900                                               foreach($e rrors as $ error) {
  1901                                                       // orig. code  was looki ng for the  error mes sage in 'p ermission_ denied', f igured tha t was a mi stake -- M G 2014-05- 20
  1902                                                       if (string_co ntains('pe rmission_d enied', mb _strtolowe r($error[' message']) )) {
  1903                                                                $per missions_i ssue = TRU E;
  1904                                                       }
  1905                                                       $o utput .= ' <div style ="max-widt h: 1000px;  backgroun d: #fef1ec ; border:  solid 1px  #900; bord er-radius:  5px; padd ing: 5px;  margin-bot tom: 5px;" >'.$error[ 'message'] .'</div>';
  1906                                               }
  1907                                      }
  1908                             }
  1909                             //if t here was a  permissio ns issue w hen creati ng the dat abase, all ow user to  try other  credentia ls
  1910                             if(iss et($permis sions_issu e) && $per missions_i ssue) {
  1911                                      $output  .= form_op en('instal l/create_d b/'.$datab ase)
  1912                                                                .for m_label('P rivileged  SQL User:  ','sa_name ')
  1913                                                                .for m_input(ar ray('name' =>'sa_name ','id'=>'s a_name')). '<br/>'
  1914                                                                .for m_label('P rivileged  SQL User P assword: ' ,'sa_pwd')
  1915                                                                .for m_password (array('na me'=>'sa_p wd','id'=> 'sa_pwd')) .'<br/>'
  1916                                                                .for m_submit(' create_db' ,'Create D atabase')
  1917                                                                .for m_close();
  1918                                      $output  .= '<div>T o manually  create da tabase <sp an style=" font-weigh t: bold;"> '.$databas e.'</span>  run the f ollowing q uery: <br  />';
  1919                                      $output  .= '<pre>' .preg_repl ace('/[\t] +/',' ',$t his->datab ase_querie s['create_ '.$databas e]).'</pre ></div>';
  1920                             }
  1921                             else {
  1922                                      $output  .= form_op en('instal l/create_d b/'.$datab ase).form_ submit('cr eate_db',' Create Dat abase').fo rm_close() ;
  1923                             }
  1924                    }
  1925                    //if  the datab ase server  connects,  we know t he databas e exists,  but the pe rmissions  the config ured user  has
  1926                    //ar en't confi gured corr ectly
  1927                    if($ db_connect ed && $db_ exists &&  !$permissi ons_set) {
  1928                             $error s = $this- >session-> flashdata( 'db_permis sions_set_ errors');
  1929                             $missi ng_permiss ions = $th is->sessio n->flashda ta('db_per missions_m issing');
  1930                             if($er rors) {
  1931                                      if(is_ar ray($error s)) {
  1932                                               foreach($e rrors as $ error) {
  1933                                                       // orig. code  looking f or the ent ire messag e within a  substring  of the me ssage - I' m assuming  this was  a mistake  -- MG 2014 -05-21
  1934                                                       if (string_co ntains('no t able to  access dat abase "'.$ database.' "',$error[ 'message'] )) {
  1935                                                                $add _user_quer y = 'USE [ '.$databas e.']; CREA TE USER [' .DATABASE_ USERNAME.' ] FROM LOG IN ['.DATA BASE_USERN AME.'] WIT H DEFAULT_ SCHEMA=[db o];';
  1936                                                       }
  1937                                                       $o utput .= ' <div style ="max-widt h: 1000px;  backgroun d: #fef1ec ; border:  solid 1px  #900; bord er-radius:  5px; padd ing: 5px;  margin-bot tom: 5px;" >'.$error[ 'message'] .'</div>';
  1938                                                       if (isset($ad d_user_que ry)) {
  1939                                                                $out put .= '<d iv style=" max-width:  1000px; b ackground:  #fef1ec;  border: so lid 1px #9 00; border -radius: 5 px; paddin g: 5px; ma rgin-botto m: 5px;">'
  1940                                                                                           .'An error  has been  detected t hat may in dicate the  configure d user log in has not  yet been  added to t he ' . DAT ABASE_NAME  . ' as a  user. '
  1941                                                                                           .'Use the  following  query to a dd the con figured lo gin user t o the data base: <br/ >'
  1942                                                                                           .'<pre>'.$ add_user_q uery.'</pr e>'
  1943                                                                                           .'</div>';
  1944                                                       }
  1945                                               }
  1946                                      }
  1947                             }
  1948                             //if e rrors are  missing (a nd there h ad to be s ome if we  are here),  flashdata  is full
  1949                             else {
  1950                                      $output  .= '<div s tyle="max- width: 100 0px; backg round: #fe f1ec; bord er: solid  1px #900;  border-rad ius: 5px;  padding: 5 px; margin -bottom: 5 px;">Permi ssions err ors encoun tered. Ref resh page  for more d etails.</d iv>';
  1951                             }
  1952                             if(!em pty($missi ng_permiss ions) && $ missing_pe rmissions)  {
  1953                                      foreach( $missing_p ermissions  as $permi ssion) {
  1954                                               $output .=  '<div sty le="max-wi dth: 1000p x; backgro und: #fef1 ec; border : solid 1p x #900; bo rder-radiu s: 5px; pa dding: 5px ; margin-b ottom: 5px ;">
  1955                                                                         The co nfigured u ser: '.DAT ABASE_USER NAME.' is  missing th e '.$permi ssion.' ro le.
  1956                                                                         Use th e followin g query to  grant the  required  role to th is user:<b r/>
  1957                                                                         <pre>U SE ['.$dat abase.'];  EXEC sp_ad drolemembe r \'db_dat areader\',  \''.DATAB ASE_USERNA ME.'\';</p re>
  1958                                                                         </div> ';
  1959                                      }
  1960                             }
  1961                    }
  1962                    
  1963                    if($ database = == MAIL_DA TABASE_NAM E && !$db_ encrypted)  {
  1964                             $error s = $this- >session-> flashdata( 'db_encryp ted_errors ') ? $this ->session- >flashdata ('db_encry pted_error s') : arra y();
  1965                             if($er rors) {
  1966                                      if(is_ar ray($error s)) {
  1967                                               foreach($e rrors as $ error) {
  1968                                                       // orig. code  was looki ng for the  error mes sage in 'p ermission_ denied', f igured tha t was a mi stake -- M G 2014-05- 20
  1969                                                       if (string_co ntains('pe rmission_d enied', mb _strtolowe r($error[' message']) )) { 
  1970                                                                $per missions_i ssue = TRU E;
  1971                                                       }
  1972                                                       if (isset($pe rmissions_ issue) &&  $permissio ns_issue)  {
  1973                                                                $out put .= '<h 4>Database  Encryptio n Status:  Unknown</h 4>';
  1974                                                       }
  1975                                                       $o utput .= ' <div style ="max-widt h: 1000px;  backgroun d: #fef1ec ; border:  solid 1px  #900; bord er-radius:  5px; padd ing: 5px;  margin-bot tom: 5px;" >'.$error[ 'message'] .'</div>';
  1976                                               }
  1977                                      }
  1978                             }
  1979                             if(iss et($permis sions_issu e) && $per missions_i ssue) {
  1980                                      $output  .= form_op en('instal l/encrypt_ db/'.$data base)
  1981                                                                .for m_label('E ncryption  Key','en_k ey')
  1982                                                                .for m_input(ar ray('name' =>'en_key' ,'id'=>'en _key')).'< br/>'
  1983                                                                .for m_label('P rivileged  SQL User:  ','sa_name ')
  1984                                                                .for m_input(ar ray('name' =>'sa_name ','id'=>'s a_name')). '<br/>'
  1985                                                                .for m_label('P rivileged  SQL User P assword: ' ,'sa_pwd')
  1986                                                                .for m_password (array('na me'=>'sa_p wd','id'=> 'sa_pwd')) .'<br/>'
  1987                                                                .for m_submit(' encrypt_db ','Encrypt  Database' )
  1988                                                                .for m_close();
  1989                             }
  1990                             else {  //databas e is not e ncrypted
  1991                                      $output  .= '<h4>Da tabase Enc ryption St atus: Unkn own / Not  Encrypted< /h4>';
  1992                                      $output  .= form_op en('instal l/encrypt_ db/'.$data base)
  1993                                                       .f orm_label( 'Encryptio n Key','en _key')
  1994                                                       .f orm_input( array('nam e'=>'en_ke y','id'=>' en_key')). '<br/>'
  1995                                                       .f orm_submit ('encrypt_ db','Encry pt Databas e')
  1996                                                       .f orm_close( );
  1997                             }
  1998                    }
  1999                    else  if($datab ase === MA IL_DATABAS E_NAME &&  $db_encryp ted){
  2000                             $outpu t .= '<h4> Database E ncryption  Status: En crypted</h 4>';
  2001                    }
  2002                    
  2003                    //if  the datab ase alread y exists,  and the co nfigured u ser has pe rmissions  needed for  running t he app 
  2004                    //NO TE: permis sions chec king check s roles on ly, not al l permissi ons, user  may still  not be abl e to creat e tables
  2005                    if($ db_connect ed && $db_ exists &&  $permissio ns_set) {
  2006                             $this- >change_da tabase($da tabase);
  2007                             foreac h($this->d atabases[$ database]  as $table  => $column s) {
  2008                                      $errors  = $this->s ession->fl ashdata($t able.'_err ors');
  2009                                      $query =  $this->se ssion->fla shdata($ta ble.'_quer y');
  2010                                      if($erro rs) {
  2011                                               if(is_arra y($errors) ) {
  2012                                                       fo reach($err ors as $er ror) {
  2013                                                                $out put .= '<d iv style=" max-width:  1000px; b ackground:  #fef1ec;  border: so lid 1px #9 00; border -radius: 5 px; paddin g: 5px; ma rgin-botto m: 5px;">' .$error['m essage'].' </div>';
  2014                                                       }
  2015                                               }
  2016                                      }
  2017                                      //TABLE  START
  2018                                      $output  .= '<table  style="bo rder: soli d black 1p x; border- collapse:  collapse;  margin-rig ht: 15px;  margin-bot tom: 15px;  width: 40 0px;">';
  2019                                      
  2020                                      $tbl_che ck_query =  'SELECT *  FROM INFO RMATION_SC HEMA.TABLE S WHERE TA BLE_TYPE=' .$this->db ->escape(' BASE TABLE ').' AND T ABLE_NAME= '.$this->d b->escape( $table);
  2021                                      $tbl_che ck = $this ->db->quer y($tbl_che ck_query);
  2022                                      //query  to check t able exist ence works
  2023                                      if($tbl_ check) {
  2024                                               //if the t able does  not exist
  2025                                               if($tbl_ch eck->num_r ows() <= 0 ) {
  2026                                                       // check for  errors fro m a previo usly run q uery
  2027                                                       if (isset($er rors) && ( is_array($ errors) ||  is_object ($errors))  && $error s) {
  2028                                                                $per mission_is sue = FALS E;
  2029                                                                fore ach($error s as $erro r) {
  2030                                                                         //orig . code loo king for t he entire  message wi thin a sub string of  the messag e - I'm as suming thi s was a mi stake -- M G 2014-05- 21
  2031                                                                         if(str ing_contai ns('permis sion denie d', $error ['message' ])) { $per mission_is sue = TRUE ; }
  2032                                                                }
  2033                                                                //if  there was  a permiss ions issue , offer a  way to ent er better  credential s
  2034                                                                if($ permission _issue) {
  2035                                                                         $outpu t .= '<tr> <td>A perm issions is sue was de tected wit h the quer y, if more  privilege d credenti als are av ailable, e nter them  below.'
  2036                                                                                                            .for m_open('in stall/crea te_db_tabl e/'.$table .'/'.$data base)
  2037                                                                                                            .for m_label('P rivileged  SQL User:  ','sa_name ')
  2038                                                                                                            .for m_input(ar ray('name' =>'sa_name ','id'=>'s a_name')). '<br/>'
  2039                                                                                                            .for m_label('P rivileged  SQL User P assword: ' ,'sa_pwd')
  2040                                                                                                            .for m_password (array('na me'=>'sa_p wd','id'=> 'sa_pwd')) .'<br/>'
  2041                                                                                                            .for m_submit(' create_'.$ table,'Cre ate '.$tab le)
  2042                                                                                                            .for m_close(). '</td></tr >';
  2043                                                                }
  2044                                                                //bu t also giv e the quer y to run m anually th rough SQL  Management  Studio
  2045                                                                //sh ould pull  query from  flashdata  if possib le to ensu re it is t he right o ne, but if  that isn' t possible  use the h ardcoded o ne for cre ate table
  2046                                                                if(! isset($que ry) || !$q uery) {
  2047                                                                         $query  = $this-> database_t able_queri es[$databa se]['creat e_'.$table ];
  2048                                                                }
  2049                                                                $out put .= '<t r><td>To m anually cr eate table  <span sty le="font-w eight: bol d;">' . $t able . '</ span> tabl e use the  following  query:</td ></tr>';
  2050                                                                $out put .= '<t r><td><pre  style="ba ckground:  #eee; widt h: 1000px;  word-wrap : break-wo rd;">' . p reg_replac e('/[\t]+/ ',' ',$que ry) . '</p re></td></ tr>';
  2051                                                       }
  2052                                                       el se {
  2053                                                                $out put .= '<t r><th titl e="'.$tabl e.' does n ot exist"  style="col or: red;"> ' . $table  . '</th>< /tr>';
  2054                                                                $out put .= '<t r><td styl e="text-al ign: cente r;">'.form _open('ins tall/creat e_db_table /'.$table. '/'.$datab ase).form_ submit('cr eate_'.$ta ble,'Creat e '.$table ).form_clo se().'</td ></tr>';
  2055                                                       }
  2056                                               }
  2057                                               //if it do es exist
  2058                                               else {
  2059                                                       $o utput .= ' <tr><th st yle="color : green;"> ' . $table  . '</th>< th>Status< /th></tr>' ;
  2060                                                       fo reach($col umns as $c olumn => $ type) {
  2061                                                                $col _check_que ry = 'SELE CT * FROM  sys.column s WHERE [n ame] = '.$ this->db-> escape($co lumn).' AN D object_i d = OBJECT _ID('.$thi s->db->esc ape($table ).')';
  2062                                                                $col _check = $ this->db-> query($col _check_que ry);
  2063                                                                if($ col_check)  {
  2064                                                                         $outpu t .= '<tr> ';
  2065                                                                         if($co l_check->n um_rows()  <= 0) {
  2066                                                                                  $output  .= '<td st yle="color : red;">'. $column.'  ['.$type.' ]</td>';
  2067                                                                                  $output  .= '<td st yle="color : red; tex t-align: c enter;">&# x2717;</td >';
  2068                                                                         }
  2069                                                                         else {
  2070                                                                                  $output  .= '<td st yle="color : green;"> '.$column. ' ['.$type .']</td>';
  2071                                                                                  $data_ty pe_query =  'SELECT D ATA_TYPE,  CHARACTER_ MAXIMUM_LE NGTH FROM  INFORMATIO N_SCHEMA.C OLUMNS IC  WHERE TABL E_NAME='.$ this->db-> escape($ta ble).' AND  COLUMN_NA ME='.$this ->db->esca pe($column );
  2072                                                                                  $data_ty pe_check =  $this->db ->query($d ata_type_q uery);
  2073                                                                                  if($data _type_chec k) {
  2074                                                                                           if($col_ch eck->num_r ows() <= 0 ) {
  2075                                                                                          
  2076                                                                                           }
  2077                                                                                           else {
  2078                                                                                                   $r esult = $d ata_type_c heck->resu lt_array(0 );
  2079                                                                                                   $d ata_type =  $result[0 ]['DATA_TY PE'];
  2080                                                                                                   $m ax_length  = ($result [0]['CHARA CTER_MAXIM UM_LENGTH' ] === -1)  ? 'max' :  $result[0] ['CHARACTE R_MAXIMUM_ LENGTH'];
  2081                                                                                                   if ($data_typ e === $typ e || $data _type.'('. $max_lengt h.')' ===  $type) {
  2082                                                                                                            $out put .= '<t d style="c olor: gree n; text-al ign: cente r;">&#x271 3;</td>';
  2083                                                                                                   }
  2084                                                                                                   el se {
  2085                                                                                                            $fix _col_query  = 'ALTER  TABLE '.$t able.' ALT ER COLUMN  '.$column. ' '.$type;
  2086                                                                                                            $out put .= '<t d title="D ata Type M ismatch. C lick for a lter colum n query."  onclick="a lert(&quot ;'.$fix_co l_query.'& quot;);" s tyle="text -align: ce nter; back ground: #f ee; border : solid #f 00 1px;">< span style ="color: r ed;">&#x27 17;</span> </td>';
  2087                                                                                                   }
  2088                                                                                           }
  2089                                                                                  }
  2090                                                                         }
  2091                                                                }
  2092                                                                else  { 
  2093                                                                         $outpu t .= '<td  style="col or: gold;" >'.$column .' ['.$typ e.']</td>' ;
  2094                                                                         $outpu t .= '<td  title="Cli ck for man ual column  existence  check que ry." oncli ck="alert( &quot;'.$c ol_check_q uery.'&quo t;);" styl e="text-al ign: cente r; cursor:  pointer;" ><span sty le="color:  gold;">&# x26a0;</sp an> Query  Failed</td >'; 
  2095                                                                }
  2096                                                                $out put .= '</ tr>';
  2097                                                       }
  2098                                               }
  2099                                      }
  2100                                      //if que ry fails,  may not ha ve the pro per permis sions
  2101                                      else {
  2102                                               $output .=  '<tr><th  style="col or: gold;  text-align : center;" >&#x26a0;  Database C heck Faile d</th></tr >';
  2103                                               $output .=  '<tr><td> Manually e xecute que ry below t o check ex istence of  <span sty le="font-w eight: bol d;">'.$tab le.'</span > table:</ td></tr>';
  2104                                               $output .=  '<tr><td> <pre>'.$tb l_check_qu ery.'</pre ></td></tr >';
  2105                                      }
  2106                                      //TABLE  END
  2107                                      $output  .= '</tabl e>';
  2108                             }
  2109                    }
  2110                    retu rn $output ;
  2111           }
  2112  
  2113           /* *
  2114           *  Convert ex isting dat abase fiel ds that do n't suppor t UTF-8 ch aracters t o their mu ltibyte eq uivalents  (varchar t o nvarchar , char to  nchar, etc ).
  2115           *  This scrip t is safe  to run mor e than onc e.  Note t hat the sc ript will  backup the  database  to the par ent direct ory of the  website;  if this 
  2116           *  directory  is web-acc essible or  not write able, you  should cha nge the sc ript locat ion specif ied by $ba ckup_path.
  2117           */
  2118           fu nction utf 8_conversi on(){
  2119                    $thi s->load->d atabase();
  2120                    $thi s->load->h elper('tex t_helper') ;
  2121                             
  2122                    echo  '<html>
  2123                                      <head>
  2124                                               <title>Cha r and Varc har Conver sio</title >
  2125                                               <link rel= "styleshee t" href="/ /netdna.bo otstrapcdn .com/boots trap/3.0.0 /css/boots trap.min.c ss" />
  2126                                               <link rel= "styleshee t" type="t ext/css" m edia="all"  href="'.s ite_url('/ css/grids. css').'" / >
  2127                                               <style>
  2128                                                       h2  {margin-t op: 2em; }
  2129                                                       bo dy { width : 80%; mar gin: 1em a uto; }
  2130                                                       .a lert-dange r a, .aler t-danger a :hover, .a lert-dange r:focus {  color: #b9 4a48; text -decoratio n: underli ne; }
  2131                                                       .a lert-dange r table {  color: #b9 4a48; }
  2132                                                       .a lert-dange r table th  { text-al ign: right ; }
  2133                                               </style>
  2134                                      </head>
  2135                                      <body>';
  2136                    echo  '<h1>Char  and Varch ar Convers ion</h1>';
  2137                    
  2138                    if(e mpty($_POS T)){
  2139                             echo ' <p>This sc ript will  back up th e database  and conve rt the cha r, varchar , and text  database  fields for  this appl ication to  fields th at can sup port UTF-8  text.  En ter the da tabase
  2140                                  a dmin crede ntials to  begin.</p> ';
  2141                             echo f orm_open() ;
  2142                             echo ' <div class ="form-gro up">'.form _label('Ad min Userna me', 'sa_n ame').form _input('sa _name', '' , 'class=" form-contr ol"').'</d iv>';
  2143                             echo ' <div class ="form-gro up">'.form _label('Ad min Passwo rd', 'sa_p wd').form_ password(' sa_pwd', ' ', 'class= "form-cont rol"').'</ div>';
  2144                             echo f orm_submit ('submit',  'Submit',  'class="b tn btn-def ault"');
  2145                             echo f orm_close( ).'</body> <html>';
  2146                             return
  2147                    }
  2148                                                       
  2149                    $sa_ name = $th is->input- >post('sa_ name',TRUE );
  2150                    $sa_ pwd = $thi s->input-> post('sa_p wd',TRUE);
  2151  
  2152                    $sa_ db_config  = array(
  2153                             'hostn ame' => DA TABASE_HOS TNAME,
  2154                             'usern ame' => $s a_name,
  2155                             'passw ord' => $s a_pwd,
  2156                             'datab ase' => 'm aster',
  2157                             'dbdri ver' => DA TABASE_DRI VER,
  2158                             'db_de bug' => TR UE
  2159                    );
  2160                    $adm in_db = $t his->load- >database( $sa_db_con fig, TRUE) ;
  2161                    $que ries = arr ay();
  2162                                      
  2163                    fore ach(array( User::db() , Message: :db()) as  $db){
  2164                             echo ' <h2>'.mb_s trtoupper( $db->datab ase).' DAT ABASE</h2>  ';
  2165                             $admin _db->query ('USE '.$d b->databas e);
  2166                             
  2167                             $nonsy stem_table s = $db->l ist_tables ();                  
  2168                             $field s_to_alter  = array()
  2169                             foreac h(array('n char', 'nv archar', ' ntext') as  $multibyt e_type){
  2170                                      $fields_ to_alter[$ multibyte_ type] = $a dmin_db->q uery(   'S ELECT OBJE CT_NAME(c. OBJECT_ID)  AS table_ name, c.na me column_ name, c.is _nullable,  k.name AS  unique_co nstraint,
  2171                                                                                                                                                                                   c.max_leng th, c.defa ult_object _id AS con straint_id
  2172                                                                                                                                                                             OBJEC T_NAME(c.d efault_obj ect_id) as  default_c onstraint,  OBJECT_DE FINITION(c .default_o bject_id)  AS default _value
  2173                                                                                                                                                                  FROM  '.$db->dat abase.'.sy s.columns  AS c
  2174                                                                                                                                                                  JOIN  '.$db->dat abase.'.sy s.types AS  t ON c.us er_type_id =t.user_ty pe_id
  2175                                                                                                                                                                  LEFT  JOIN '.$db ->database .'.sys.key _constrain ts AS k ON  c.object_ id=k.paren t_object_i d AND k.ty pe=\'UQ\'
  2176                                                                                                                                                                  WHERE  t.name=\' '.strip_fr om_beginni ng('n', $m ultibyte_t ype).'\' 
  2177                                                                                                                                                                             AND O BJECT_NAME (c.object_ id) IN (\' '.implode( "','", $no nsystem_ta bles).'\')
  2178                                                                                                                                                                  ORDER  BY c.OBJE CT_ID;' )- >result_ar ray();
  2179                             }
  2180  
  2181                             //if w e don't ha ve any fie lds to con vert, stop  before we  do anythi ng else
  2182                             if(emp ty(flatten _array($fi elds_to_al ter))){
  2183                                      echo '<p >There are  no '.arra y_to_human _readable_ list(array _keys($fie lds_to_alt er), ' or  ').' field s to conve rt for the  '.$db->da tabase.' d atabase.</ p>';
  2184                                      continue ;
  2185                             }
  2186                             
  2187                             //BACK  UP THE DA TABASE IN  CASE THING S GO TERRI BLY TERRIB LY WRONG
  2188                                      
  2189                             //find  a non-web -accessibl e place to  back up t he db
  2190                             $backu p_path = s trip_from_ end('/syst em/', BASE PATH);
  2191                             $backu p_path = m b_substr($ backup_pat h, 0, mb_s trrpos($ba ckup_path,  '/'));        
  2192                             
  2193                             //to b ack up the  database,  we need t o make a t emporary c hange to t he PHP sql srver driv er setting s
  2194                             //see  http://blo gs.msdn.co m/b/brian_ swan/archi ve/2010/04 /06/backup -and-resto re-with-th e-sql-serv er-driver- for-php.as px for mor e info
  2195                             $origi nal_config _value = i ni_get('sq lsrv.Warni ngsReturnA sErrors');
  2196                             ini_se t('sqlsrv. WarningsRe turnAsErro rs', 0);     
  2197                             
  2198                             echo ' <h3>Backin g up the ' .$db->data base.' dat abase befo re alterin g column t ypes ...</ h3>';
  2199                             if(!$a dmin_db->q uery("BACK UP DATABAS E [".$db-> database." ] TO disk= '".$backup _path.'/'. $db->datab ase.'.bak. '.strftime ("%Y-%m-%d -%H-%M")." '")){
  2200                                      echo '<h 3>Unable t o back up  '.$db->dat abase.'  P lease chec k to make  sure you h ave write  permission s and that  there is  enough spa ce on the  disk.</h3> ';
  2201                                      return; 
  2202                             }
  2203                                      
  2204                             //rest ore the or iginal PHP  sqlsrver  driver set ting befor e proceedi ng
  2205                             ini_se t('sqlsrv. WarningsRe turnAsErro rs', $orig inal_confi g_value);
  2206                             
  2207                             //MAKE  THE CHANG ES               
  2208                             echo ' <h3>Beginn ing column  conversio ns...</h3> ';
  2209                             foreac h($fields_ to_alter a s $new_typ e => $fiel ds){
  2210                                      foreach( $fields as  $field_in fo){
  2211                                               if(in_arra y($field_i nfo['table _name'], $ nonsystem_ tables)){
  2212                                                       
  2213                                                       ec ho '<h4>Ch anging '.$ field_info ['table_na me'].'.'.$ field_info ['column_n ame'].' fr om '.strip _from_begi nning('n',  $new_type ).' to '.$ new_type.' ... </h4>' ;
  2214                                                       
  2215                                                       $s ql = '';
  2216  
  2217                                                       // check to s ee if ther e's a uniq ue constra int; remov e the cons traint if  there is
  2218                                                       if (!empty($f ield_info[ 'unique_co nstraint'] )){
  2219                                                                $sql  .= 'ALTER  TABLE '.$ db->databa se.'.dbo.' .$field_in fo['table_ name'].' D ROP CONSTR AINT '.$fi eld_info[' unique_con straint']. ";\n";
  2220                                                       }
  2221  
  2222                                                       // check to s ee if ther e's a defa ult value;  remove th e constrai nt if ther e is                                                
  2223                                                       if (!empty($f ield_info[ 'default_c onstraint' ]) && !emp ty($field_ info['defa ult_value' ])){
  2224                                                                $sql  .= 'ALTER  TABLE '.$ db->databa se.'.dbo.' .$field_in fo['table_ name'].' D ROP CONSTR AINT '.$fi eld_info[' default_co nstraint'] .";\n";
  2225                                                       }
  2226                                                                
  2227                                                       $s ql .= 'ALT ER TABLE ' .$db->data base.'.dbo .'.$field_ info['tabl e_name'].'  ALTER COL UMN ['.$fi eld_info[' column_nam e'].'] '.$ new_type;
  2228                                                       
  2229                                                       if ($field_in fo['max_le ngth'] < 0 )
  2230                                                                $sql  .= '(max) ';
  2231                                                       el se
  2232                                                                $sql  .= '('.$f ield_info[ 'max_lengt h'].')';
  2233                                                                
  2234                                                       if (empty($fi eld_info[' is_nullabl e']))
  2235                                                                $sql  .= ' NOT  NULL';
  2236                                                       
  2237                                                       $s ql .= ";\n ";  
  2238                                                       
  2239                                                       // add the de fault valu e back in  if we had  one
  2240                                                       if (!empty($f ield_info[ 'default_v alue']))
  2241                                                                $sql  .= 'ALTER  TABLE '.$ db->databa se.'.dbo.' .$field_in fo['table_ name'].' A DD CONSTRA INT DF_'.$ field_info ['table_na me'].'_'.$ field_info ['column_n ame'].' '.
  2242                                                                                  'DEFAULT   N'.strip _from_begi nning('(',  strip_fro m_end(')',  $field_in fo['defaul t_value']) ).' FOR [' .$field_in fo['column _name'].'] ;';
  2243                                                                                  
  2244                                                       // add the un ique const raint back  in if we  had one
  2245                                                       if (!empty($f ield_info[ 'unique_co nstraint'] )){
  2246                                                                $sql  .= 'ALTER  TABLE '.$ db->databa se.'.dbo.' .$field_in fo['table_ name'].' A DD CONSTRA INT UQ_'.$ field_info ['table_na me'].'_'.$ field_info ['column_n ame'].' '.
  2247                                                                                  'UNIQUE  NONCLUSTER ED ('.$fie ld_info['c olumn_name '].');';
  2248                                                       }                          
  2249                                                       
  2250                                                       $q ueries[] =  trim($sql );
  2251                                                       ec ho '<pre c lass="raw- output">'. highlight_ code(trim( $sql)).'</ pre>';
  2252                                                                                                                              
  2253                                                       if (!$admin_d b->query($ sql)){
  2254                                                                //pr obably the re's a con straint th at this sc ript can't  cope with , or if yo u're seein g a messag e saying t hat the ro w size wou ld be grea ter than
  2255                                                                //th e allowabl e maximum  row size o f 8060, tr y running  DBCC CLEAN TABLE: htt p://msdn.m icrosoft.c om/en-us/l ibrary/ms1 74418.aspx
  2256                                                                echo  '<div cla ss="alert  alert-dang er"><stron g>QUERY FA ILED</stro ng>. You m ay want to  run this  SQL manual ly to see  what is ca using the  problem.</ div>';
  2257                                                       }
  2258                                               }
  2259                                      }
  2260                             } 
  2261                    }
  2262                    if(! empty($que ries)){
  2263                             $full_ sql = impl ode("\n\n" , $queries );
  2264                             $sql_s cript_dest ination =  $backup_pa th.'/utf8_ conversion _queries_' .strftime( "%Y-%m-%d- %H-%M").'. sql';
  2265                             $succe ss = file_ put_conten ts($sql_sc ript_desti nation, $f ull_sql);
  2266                             echo ' <h2>ALL QU ERIES</h2> ';
  2267                             if($su ccess) ech o '<p>The  queries pe rformed by  this scri pt can be  found here : '.$sql_s cript_dest ination.'< /p>';
  2268                             echo ' <pre class ="raw-outp ut">'.high light_code (trim($ful l_sql)).'< /pre>';
  2269                    }
  2270                    
  2271                    echo  '</body>< html>';
  2272           }
  2273           
  2274           fu nction pop ulate_pati ents_for_m essages(){
  2275                    set_ time_limit (0); //thi s could ta ke a while
  2276                    
  2277                    echo  '<h1>Popu late Patie nts for Me ssages</h1 >';          
  2278                    echo  '<p>This  script wil l repopula te the pat ients tabl e with the  patients  from all m essages.</ p>';
  2279                                      
  2280                    requ ire_model( 'message') ;
  2281                    $mes sage_count  = Message ::count();
  2282                    
  2283                    echo  '<h2>Popu lating Pat ients for  '.$message _count.' M essages</h 2>';
  2284                    log_ message('e rror', 'Po pulating p atients fo r '.$messa ge_count.'  messages' );
  2285                    
  2286                    for( $i=0; $i <  $message_ count; $i) {
  2287                             Messag e::db()->o rder_by('i d', 'ASC') ->limit(10 , ($i));
  2288                             $messa ges = Mess age::find( );
  2289                             foreac h($message s as $mess age){
  2290                                      $i++;
  2291                                      Patient: :populate_ for_messag e($message );
  2292                             }
  2293                             echo ' <p>'.$i.'  of '.$mess age_count. ' complete  ...</p>';
  2294                             log_me ssage('err or', $i.'  of '.$mess age_count. ' complete ');
  2295                    }
  2296                    echo  '<h2>Done !</h2>';
  2297           }
  2298           
  2299           fu nction pop ulate_pati ent_docume nt_names() {
  2300                    set_ time_limit (0); //thi s could ta ke a while
  2301                    $thi s->load->d atabase();
  2302                    
  2303                    echo  '<h1>Popu late Patie nts for Fi le Names</ h1>';                
  2304                    echo  '<p>This  script wil l populate  the file  names for  any patien t entries  that do no t currentl y have the  file name  saved.  I t can be s afely run  multiple t imes if ne eded in or der to fin ish popula ting all p atients.</ p>';
  2305                                      
  2306                    requ ire_model( 'patient') ;
  2307                    $pat ients = Pa tient::fin d("documen t_name is  NULL OR do cument_nam e = ''");
  2308                    $pat ient_count  = count($ patients);
  2309                    
  2310                    echo  '<h2>'.Pa tient::cou nt("docume nt_name IS  NOT NULL  AND docume nt_name !=  ''").'/'. Patient::c ount().' p atients al ready have  a documen t name</h2 >';
  2311                    
  2312                    echo  '<h2>Popu lating doc ument name s for '.$p atient_cou nt.' patie nts </h2>' ;
  2313                    log_ message('e rror', 'Po pulating p atients fo r '.$patie nt_count.'  messages' );
  2314                    
  2315                    $i =  1;
  2316                    fore ach($patie nts as $pa tient){
  2317                             $patie nt->docume nt_name =  $patient-> attachment _name;
  2318                             $patie nt->save() ;
  2319                             echo ' <p>'.$i.'  of '.$pati ent_count. ' complete  ...</p>';
  2320                             log_me ssage('err or', $i.'  of '.$pati ent_count. ' complete ');
  2321                             $i++;
  2322                    }
  2323  
  2324                    echo  '<h2>Done !</h2>';
  2325           }
  2326           
  2327           fu nction che ck_patient _document_ names(){
  2328                    set_ time_limit (0); //thi s could ta ke a while
  2329                    $thi s->load->d atabase();
  2330                    
  2331                    echo  '<h1>Chec k Patients  for File  Names</h1> ';           
  2332                    echo  '<p>This  script wil l check to  see if th ere are an y patient  entries th at do not  currently  have the f ile name s aved.  </p >';
  2333                                      
  2334                    requ ire_model( 'patient') ;
  2335                    $pat ients = Pa tient::fin d("documen t_name is  NULL OR do cument_nam e = ''");
  2336                    $pat ient_count  = count($ patients);
  2337                    
  2338                    echo  '<h2>'.Pa tient::cou nt("docume nt_name IS  NOT NULL  AND docume nt_name !=  ''").'/'. Patient::c ount().' p atients al ready have  a documen t name</h2 >';
  2339                    
  2340                    echo  '<h2>Done !</h2>';
  2341           }
  2342  
  2343           pu blic funct ion create _ldap() {
  2344                                      
  2345           }
  2346           
  2347           pu blic funct ion create _ldap_entr y($dn) {
  2348                    $dn  = base64_d ecode(rawu rldecode($ dn));
  2349                    if(a rray_key_e xists($dn,  $this->ld ap_schema) ) {
  2350                             $this- >_create_l dap_entry( $dn);
  2351                    }
  2352                    redi rect('inst all/ldap') ;
  2353           }
  2354           
  2355           pr ivate func tion _crea te_ldap_en try($dn) {
  2356                    $lda p_conn = $ this->prep are_ldap_c onn();
  2357                    $lda p_bind = @ ldap_bind( $ldap_conn , LDAP_ANO N_ADMIN_US ERNAME, LD AP_ANON_AD MIN_PASSWO RD);
  2358                    if($ ldap_bind)  {
  2359                             ldap_a dd($ldap_c onn, $dn,  $this->lda p_schema[$ dn]);
  2360                    }
  2361                    else  {
  2362                    
  2363                    }
  2364           }
  2365           
  2366           pr ivate func tion ldap_ entry_exis ts($ldap_c onn,$dn) {
  2367                    $sea rch = @lda p_search($ ldap_conn,  $dn, '(ob jectClass= *)');
  2368                    $res ult = @lda p_get_entr ies($ldap_ conn,$sear ch);
  2369                    if($ result['co unt'] > 0)  { return  TRUE; }
  2370                    retu rn FALSE;
  2371           }
  2372           pr ivate func tion prepa re_ldap_co nn() {
  2373                    $lda p_conn = l dap_connec t(LDAP_HOS TNAME, LDA P_PORT);
  2374                    if(! ldap_set_o ption($lda p_conn, LD AP_OPT_PRO TOCOL_VERS ION, 3)) {  return FA LSE; } 
  2375                    if(! ldap_set_o ption($lda p_conn, LD AP_OPT_REF ERRALS, 0) ) { return  FALSE; }
  2376                    retu rn $ldap_c onn;
  2377           }
  2378           /*  This func tion gener ates a 32  character  random str ing for us e as a pas sword,
  2379            *  utilizing  a mix of  lower and  upper case , numbers,  and speci al charact ers.
  2380           */
  2381           pr ivate func tion rando m_password () {
  2382                    $cha rs = array ("a","b"," c","d","e" ,"f","g"," h","i","j" ,"k","l"," m","n","o" ,"p","q"," r","s","t" ,"u","v"," w","x","y" ,"z","A"," B","C","D" ,"E","F"," G","H","I" ,"J","K"," L","M","N" ,"O","P"," Q","R","S" ,"T","U"," V","W","X" ,"Y","Z"," 1","2","3" ,"4","5"," 6","7","8" ,"9","0"," !","@","#" ,"$","%"," ^","&","*" ,"(",")"," {","}","?" );
  2383                    $pas s = "";
  2384                    $cou nt = count ($chars);
  2385                    for( $i = 0; $i  < 32; $i+ +) {
  2386                             $pass  .= $chars[ abs(hexdec (bin2hex(o penssl_ran dom_pseudo _bytes(6)) )%$count)] ;
  2387                    }
  2388                    retu rn $pass;
  2389           }
  2390           /*  This func tion encod es the giv en text as  a salted  SHA string  for use i n OpenLDAP .
  2391            * /
  2392           pr ivate func tion ssha2 56_encode( $text) {
  2393                    $sal t = hash(' sha256', o penssl_ran dom_pseudo _bytes(32) );
  2394                    $has h = "{SSHA 256}".base 64_encode( pack("H*", hash('sha2 56',$text. $salt)).$s alt);
  2395                    retu rn $hash;
  2396           }
  2397           pr ivate func tion chang e_database ($database ){
  2398                    $thi s->load->d atabase();
  2399                    if($ this->db-> database ! == $databa se) {
  2400                             $confi g['hostnam e'] = DATA BASE_HOSTN AME;
  2401                             $confi g['usernam e'] = DATA BASE_USERN AME;
  2402                             $confi g['passwor d'] = DATA BASE_PASSW ORD;
  2403                             $confi g['databas e'] = $dat abase;
  2404                             $confi g['dbdrive r'] = DATA BASE_DRIVE R;
  2405                             $confi g['dbprefi x'] = '';
  2406                             $confi g['pconnec t'] = FALS E;
  2407                             $confi g['db_debu g'] = FALS E;
  2408                             $confi g['cache_o n'] = FALS E;
  2409                             $confi g['cachedi r'] = '';
  2410                             $confi g['char_se t'] = 'utf 8';
  2411                             $confi g['dbcolla t'] = 'utf 8_general_ ci';
  2412                             $confi g['swap_pr e'] = '';
  2413                             $confi g['autoini t'] = FALS E;
  2414                             $confi g['stricto n'] = FALS E;
  2415                             $db =  $this->loa d->databas e($config, TRUE);
  2416                             $this- >db = $db;
  2417                    }
  2418           }
  2419           pr ivate func tion decod e_md5($dat a) {
  2420                    $dat a = base64 _decode($d ata);
  2421                    $key  = md5(con fig_item(' encryption _key'));
  2422           
  2423                    $dat a = $this- >encrypt-> remove_cip her_noise( $data,$key );
  2424           
  2425                    $ini t_size = m crypt_get_ iv_size(MC RYPT_RIJND AEL_256, M CRYPT_MODE _CBC);
  2426                    if ( $init_size  > strlen( $data))
  2427                    {
  2428                             return  FALSE;
  2429                    }
  2430                    $ini t_vect = s ubstr($dat a, 0, $ini t_size);
  2431                    $dat a = substr ($data, $i nit_size);
  2432                    retu rn mcrypt_ decrypt(MC RYPT_RIJND AEL_256, $ key, $data , MCRYPT_M ODE_CBC, $ init_vect) ;
  2433           }
  2434           pr ivate func tion  is_a scii( $str ing = '' )  {
  2435                    $num  = 0;
  2436                    whil e( isset(  $string[$n um] ) ) {
  2437                             if( or d( $string [$num] ) &  0x80 ) {
  2438                                      return f alse;
  2439                             }
  2440                             $num++ ;
  2441                    }
  2442                    retu rn true;
  2443           }
  2444   }