3. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 8/16/2019 12:01:55 PM Eastern 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.

3.1 Files compared

# Location File Last Modified
1 Direct_DSM.zip\Direct_DSM\api\application\controllers Install.php Tue Aug 13 17:30:18 2019 UTC
2 Direct_DSM.zip\Direct_DSM\api\application\controllers Install.php Wed Aug 14 12:29:25 2019 UTC

3.2 Comparison summary

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

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

3.4 Active regular expressions

No regular expressions were active.

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