fix creating dupe email
[Pman.Core] / DataObjects / Core_person.php
1 <?php
2 /**
3  * Table Definition for Person
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7
8 class Pman_Core_DataObjects_Core_person extends DB_DataObject 
9 {
10     ###START_AUTOCODE
11     /* the code below is auto generated do not remove the above tag */
12
13     public $__table = 'core_person';                          // table name
14     public $id;                              // int(11)  not_null primary_key auto_increment
15     public $email;                           // string(128)  not_null
16     public $alt_email;
17     
18     public $company_id;                      // int(11)  
19     public $office_id;                       // int(11)  
20     public $name;                            // string(128)  not_null
21     public $firstname;                            // string(128)  not_null
22     public $lastname;                            // string(128)  not_null
23     public $phone;                           // string(32)  not_null
24     public $fax;                             // string(32)  not_null
25     
26     public $role;                            // string(32)  not_null
27     public $remarks;                         // blob(65535)  not_null blob
28     public $passwd;                          // string(64)  not_null
29     public $owner_id;                        // int(11)  not_null
30     public $lang;                            // string(8)  
31     public $no_reset_sent;                   // int(11)  
32     public $action_type;                     // string(32)  
33     public $project_id;                      // int(11)
34
35     
36     public $active;                          // int(11)  not_null
37     public $deleted_by;                      // int(11)  not_null
38     public $deleted_dt;                      // datetime(19)  binary
39
40
41     public $name_facebook; // VARCHAR(128) NULL;
42     public $url_blog; // VARCHAR(256) NULL ;
43     public $url_twitter; // VARCHAR(256) NULL ;
44     public $url_linkedin; // VARCHAR(256) NULL ;
45     public $linkedin_id; // VARCHAR(256) NULL ;
46     
47     public $phone_mobile; // varchar(32)  NOT NULL  DEFAULT '';
48     public $phone_direct; // varchar(32)  NOT NULL  DEFAULT '';
49     public $countries; // VARCHAR(128) NULL;
50     
51     public $language;
52     
53     /* the code above is auto generated do not remove the tag below */
54     ###END_AUTOCODE
55     
56     static $authUser = false;
57     
58  
59     function owner()
60     {
61         // this might be a Person in some old code? 
62         $p = DB_DataObject::Factory('core_person');
63         $p->get($this->owner_id);
64         return $p;
65     }
66     
67     /**
68      *
69      *
70      *
71      *
72      *  FIXME !!!! -- USE Pman_Core_Mailer !!!!!
73      *
74      *
75      *
76      *  
77      */
78     function buildMail($templateFile, $args)
79     {
80           
81         $args = (array) $args;
82         $content  = clone($this);
83         
84         foreach((array)$args as $k=>$v) {
85             $content->$k = $v;
86         }
87         
88         $ff = HTML_FlexyFramework::get();
89         
90         
91         //?? is this really the place for this???
92         if (
93                 !$ff->cli && 
94                 empty($args['no_auth']) &&
95                 !in_array($templateFile, array(
96                     // templates that can be sent without authentication.
97                      'password_reset' ,
98                      'password_welcome'
99                  ))
100             ) {
101             
102             $content->authUser = $this->getAuthUser();
103             if (!$content->authUser) {
104                 return PEAR::raiseError("Not authenticated");
105             }
106         }
107         
108         // should handle x-forwarded...
109         
110         $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
111             $_SERVER["HTTP_HOST"] :
112             (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
113             
114         /* use the regex compiler, as it doesnt parse <tags */
115         
116         $tops = array(
117             'compiler'    => 'Flexy',
118             'nonHTML' => true,
119             'filters' => array('SimpleTags','Mail'),
120             //     'debug'=>1,
121         );
122         
123         
124         
125         if (!empty($args['templateDir'])) {
126             $tops['templateDir'] = $args['templateDir'];
127         }
128         
129         
130         
131         require_once 'HTML/Template/Flexy.php';
132         $template = new HTML_Template_Flexy( $tops );
133         $template->compile("mail/$templateFile.txt");
134         
135         /* use variables from this object to ouput data. */
136         $mailtext = $template->bufferedOutputObject($content);
137         
138         $htmlbody = false;
139         // if a html file with the same name exists, use that as the body
140         // I've no idea where this code went, it was here before..
141         if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
142             $tops['nonHTML'] = false;
143             $template = new HTML_Template_Flexy( $tops );
144             $template->compile("mail/$templateFile.html");
145             $htmlbody = $template->bufferedOutputObject($content);
146             
147         }
148         
149         
150         
151         //echo "<PRE>";print_R($mailtext);
152         //print_R($mailtext);exit;
153         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
154         require_once 'Mail/mimeDecode.php';
155         require_once 'Mail.php';
156         
157         $decoder = new Mail_mimeDecode($mailtext);
158         $parts = $decoder->getSendArray();
159         
160         if (is_a($parts,'PEAR_Error')) {
161             return $parts;
162             //echo "PROBLEM: {$parts->message}";
163             //exit;
164         } 
165         list($recipents,$headers,$body) = $parts;
166         $recipents = array($this->email);
167         if (!empty($content->bcc) && is_array($content->bcc)) {
168             $recipents =array_merge($recipents, $content->bcc);
169         }
170         $headers['Date'] = date('r');
171         
172         if ($htmlbody !== false) {
173             require_once 'Mail/mime.php';
174             $mime = new Mail_mime(array('eol' => "\n"));
175             $mime->setTXTBody($body);
176             $mime->setHTMLBody($htmlbody);
177             // I think there might be code in mediaoutreach toEmail somewhere
178             // h embeds images here..
179             $body = $mime->get();
180             $headers = $mime->headers($headers);
181         }
182         
183         return array(
184             'recipients' => $recipents,
185             'headers'    => $headers,
186             'body'      => $body
187         );
188     }
189     
190     
191     /**
192      * send a template
193      * - user must be authenticate or args[no_auth] = true
194      *   or template = password_[reset|welcome]
195      * 
196      */
197     function sendTemplate($templateFile, $args)
198     {
199         $ar = $this->buildMail($templateFile, $args);
200       
201         //print_r($recipents);exit;
202         $mailOptions = PEAR::getStaticProperty('Mail','options');
203         $mail = Mail::factory("SMTP",$mailOptions);
204         
205         if (PEAR::isError($mail)) {
206             return $mail;
207         } 
208         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
209         $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
210         error_reporting($oe);
211        
212         return $ret;
213     }
214     
215   
216     
217     
218     function getEmailFrom()
219     {
220         if (empty($this->name)) {
221             return $this->email;
222         }
223         
224         return '"' . addslashes($this->name) . '" <' . $this->email . '>';
225     }
226     
227     function toEventString() 
228     {
229         return empty($this->name) ? $this->email : $this->name;
230     } 
231     
232     function verifyAuth()
233     { 
234         $ff= HTML_FlexyFramework::get();
235         if (!empty($ff->Pman['auth_comptype']) &&
236             (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
237            ){
238             
239             $sesPrefix = $this->sesPrefix();
240        
241             self::$authUser = false;
242             $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
243             
244             return false;
245             
246             //$ff->page->jerr("Login not permited to outside companies");
247         }
248         return true;
249         
250     }    
251    
252    
253     //   ---------------- authentication / passwords and keys stuff  ----------------
254     function isAuth()
255     {
256         // do not start a session if we are using http auth...
257         // we have a situation where the app is behind a http access and is also login
258         // need to work out a way to handle that.
259         $ff= HTML_FlexyFramework::get();
260         if (php_sapi_name() != "cli" && (empty($_SERVER['PHP_AUTH_USER']) || !empty($ff->disable_http_auth)))  {
261              @session_start();
262         }
263         
264          
265        
266         $sesPrefix = $this->sesPrefix();
267         
268         if (self::$authUser) {
269             return self::$authUser;
270         }
271         
272         
273         if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
274             // in session...
275             $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
276             $u = DB_DataObject::factory($this->tableName());
277             $u->autoJoin();
278             if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
279                 if ($u->verifyAuth()) {
280                     self::$authUser = $u;
281                     return true;
282                 }
283             }
284             unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
285             unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
286             setcookie('Pman.timeout', -1, time() + (30*60), '/');
287             return false;
288         }
289         
290         // http basic auth..
291         $u = DB_DataObject::factory($this->tableName());
292         
293         if (empty($ff->disable_http_auth)  // http auth requests should not have this...
294             &&
295             !empty($_SERVER['PHP_AUTH_USER']) 
296             &&
297             !empty($_SERVER['PHP_AUTH_PW'])
298             &&
299             $u->get('email', $_SERVER['PHP_AUTH_USER'])
300             &&
301             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
302            ) {
303             // logged in via http auth
304             // http auth will not need session... 
305             //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
306             self::$authUser = $u;
307             return true; 
308         }
309         
310         // at this point all http auth stuff is done, so we can init session
311         
312         
313         //die("test init");
314         if (!$this->canInitializeSystem()) {
315           //  die("can not init");
316             return false;
317         }
318         
319         
320         $auto_auth_allow = false;
321         if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
322             $auto_auth_allow  = true;
323         }
324         if  ( !empty($ff->Pman['local_autoauth'])
325              &&
326                 !empty($_SERVER['SERVER_ADDR']) &&
327                 !empty($_SERVER['REMOTE_ADDR']) &&
328                 (
329                     (
330                        $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
331                        $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
332                    )
333                    ||
334                    (
335                        $_SERVER['SERVER_ADDR'] == '::1' &&
336                        $_SERVER['REMOTE_ADDR'] == '::1'
337                    )
338                 )
339                 
340             ){
341             $auto_auth_allow  = true;
342         }
343         
344         
345         if (empty($_SERVER['PATH_INFO']) ||  $_SERVER['PATH_INFO'] == '/Login') {
346             $auto_auth_allow  = false;
347         }
348          //var_dump($auto_auth_allow);
349         // local auth - 
350         $default_admin = false;
351         if ($auto_auth_allow) {
352             $group = DB_DataObject::factory('core_group');
353             $group->get('name', 'Administrators');
354             
355             $member = DB_DataObject::factory('core_group_member');
356             $member->autoJoin();
357             $member->group_id = $group->id;
358             $member->whereAdd("
359                 join_user_id_id.id IS NOT NULL
360             ");
361             if($member->find(true)){
362                 $default_admin = DB_DataObject::factory($this->tableName());
363                 $default_admin->autoJoin();
364                 if(!$default_admin->get($member->user_id)){
365                     $default_admin = false;
366                 }
367             }
368         }
369         
370         //var_dump($ff->Pman['local_autoauth']);         var_dump($_SERVER); exit;
371         $u = DB_DataObject::factory($this->tableName());
372         $u->autoJoin();
373         $ff = HTML_FlexyFramework::get();
374         
375         if ($auto_auth_allow && 
376             ($default_admin ||  $u->get('email', $ff->Pman['local_autoauth']))
377         ) {
378             
379             $user = $default_admin ? $default_admin->toArray() : $u->toArray();
380             
381             // if we request other URLS.. then we get auto logged in..
382             self::$authUser = $default_admin ? $default_admin : $u;;
383             //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
384             return true;
385         }
386         
387         //var_dump(session_id());
388         //var_dump($_SESSION[__CLASS__]);
389         
390         //if (!empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
391         //    return false;
392         //}
393         //die("got this far?");
394         // not in session or not matched...
395         $u = DB_DataObject::factory($this->tableName());
396         $u->whereAdd(' LENGTH(passwd) > 0');
397         $n = $u->count();
398         if (empty($_SESSION[get_class($this)]) || !is_array($_SESSION[get_class($this)])) { 
399             $_SESSION[get_class($this)] = array();
400         }
401         $_SESSION[get_class($this)][$sesPrefix .'-empty']  = $n;
402         if (class_exists('PEAR')) {
403             $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
404             if ($error) {
405                 die($error->toString()); // not really a good thing to do...
406             }
407         }
408         if (!$n){ // authenticated as there are no users in the system...
409              return true;
410         }
411          return false;
412         
413     }
414     
415     function canInitializeSystem()
416     {
417         
418         return !strcasecmp(get_class($this) , __CLASS__);
419     }
420     
421     function getAuthUser()
422     {
423         if (!$this->isAuth()) {
424             return false;
425         }
426         
427         $ff= HTML_FlexyFramework::get();
428         
429         $sesPrefix = $this->sesPrefix();
430         
431         //var_dump(array(get_class($this),$sesPrefix .'-auth'));
432        
433         if (self::$authUser) {
434              
435             if (isset($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
436                 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
437                 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
438             }
439             // not really sure why it's cloned..
440             return   clone (self::$authUser);
441              
442             
443         }
444         
445         
446         
447         if (!$this->canInitializeSystem()) {
448             return false;
449         }
450         
451         
452         
453         if (empty(   $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
454             $u = DB_DataObject::factory($this->tableName());
455             $u->whereAdd(' LENGTH(passwd) > 0');
456             $_SESSION[get_class($this)][$sesPrefix .'-empty']  = $u->count();
457         }
458                 
459              
460         if (
461             isset(   $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) && 
462             $_SESSION[get_class($this)][$sesPrefix .'-empty']  < 1
463         ) {
464             
465             // fake person - open system..
466             //$ce = DB_DataObject::factory('core_enum');
467             //$ce->initEnums();
468             
469             
470             $u = DB_DataObject::factory($this->tableName());
471             $u->id = -1;
472             
473             // if a company has been created fill that in in company_id_id
474             $c = DB_DAtaObject::factory('core_company')->lookupOwner();
475             if ($c) {
476                 $u->company_id_id = $c->pid();
477                 $u->company_id = $c->pid();
478             }
479             
480             return $u;
481             
482         }
483         return false;
484     }     
485     function login()
486     {
487         $this->isAuth(); // force session start..
488         if (!$this->verifyAuth()) { // check for company valid..
489             return false;
490         }
491         
492         // open up iptables at login..
493         $dbname = $this->databaseNickname();
494         touch( '/tmp/run_pman_admin_iptables-'.$dbname);
495          
496         // refresh admin group if we are logged in as one..
497         //DB_DataObject::debugLevel(1);
498         $g = DB_DataObject::factory('core_group');
499         $g->type = 0;
500         $g->get('name', 'Administrators');
501         $gm = DB_DataObject::Factory('core_group_member');
502         if (in_array($g->id,$gm->listGroupMembership($this))) {
503             // refresh admin groups.
504             $gr = DB_DataObject::Factory('core_group_right');
505             $gr->applyDefs($g, 0);
506         }
507         
508         $sesPrefix = $this->sesPrefix();
509         
510         // we should not store the whole data in the session - otherwise it get's huge.
511         $p = DB_DAtaObject::Factory($this->tableName());
512         $p->get($this->pid());
513         
514         $d = $p->toArray();
515         
516         $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
517         setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
518         
519         //var_dump(array(get_class($this),$sesPrefix .'-auth'));
520         $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
521         
522         $pp = DB_DAtaObject::Factory($this->tableName());
523         $pp->get($this->pid());
524         $pp->autoJoin();
525         
526         self::$authUser = $pp;
527         // ensure it's written so that ajax calls can fetch it..
528         
529         
530         
531     }
532     function logout()
533     {
534         $this->isAuth(); // force session start..
535         
536         $sesPrefix = $this->sesPrefix();
537         $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
538         $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
539         self::$authUser = false;
540         
541     }    
542     function genPassKey ($t) 
543     {
544         return md5($this->email . $t. $this->passwd);
545     }
546     function simpleAuthKey($m = 0)
547     {
548         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
549         
550         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
551     }
552     /**
553      * When we generate autologin urls:
554      * eg. /Somesite/Test/12
555      * it will generate:
556      * /Somesite/Test/12/{datetime}/{sha256(url + expires_datetime + password)}
557      *
558      * eg. genAutoLoginURL($sub, $expires)
559      */
560     function genAutoLoginURL($url, $expires = false)  
561     {
562         $expires = $expires  === false ? strtotime("NOW + 1 WEEK") : $expires;
563         //echo serialize(array($url, $expires, $this->email, $this->passwd));
564         //echo hash('sha256', serialize(array($url, $expires, $this->email, $this->passwd)));
565         
566         return $url.'/'.$this->id .'/'.$expires.'/'.
567             hash('sha256',
568                 serialize(
569                     array($url, $expires, $this->email,$this->passwd)
570                 )
571             );
572         
573     }
574     
575     function validateAutoLogin($called)
576     {
577         $bits = explode("/",$called);
578         if (count($bits) < 4) {
579             return false; // unrelated.
580         }
581         $hash = array_pop($bits);
582         $time = array_pop($bits);
583         
584         $id = array_pop($bits);
585         if (!is_numeric($time) || !is_numeric($id)) {
586             return false; // wrong format.
587         }
588         $u = DB_DataObject::Factory($this->tableName());
589         $u->get($id);
590         $url = implode("/", $bits);
591         if ($time < time()) {
592             return "Expired";
593         }
594         //echo serialize(array('/'.$url, $time, $u->email, $u->passwd));
595         //echo hash('sha256', serialize(array('/'.$url, $time, $u->email, $u->passwd)));
596         if ($hash == hash('sha256', serialize(array('/'.$url, $time*1, $u->email, $u->passwd)))) {
597             $u->login();
598             return $u;
599         }
600         return false;
601     }
602     
603     
604     function checkTwoFactorAuthentication($val)
605     {
606         
607         
608         // also used in login
609         require_once 'System.php';
610         
611         if(
612             empty($this->id) ||
613             empty($this->oath_key)
614         ) {
615             return false;
616         }
617         
618         $oathtool = System::which('oathtool');
619         
620         if (!$oathtool) {
621             return false;
622         }
623         
624         $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
625         
626         $password = exec($cmd);
627         
628         return ($password == $val) ? true : false;
629     }
630     
631     function checkPassword($val)
632     {
633         if (substr($this->passwd,0,1) == '$') {
634             if (function_exists('pasword_verify')) {
635                 return password_verify($val, $this->passwd);
636             }
637             return crypt($val,$this->passwd) == $this->passwd ;
638         }
639         // old style md5 passwords...- cant be used with courier....
640         return md5($val) == $this->passwd;
641     }
642     
643     function setPassword($value) 
644     {
645         if (function_exists('pasword_hash')) {
646             return password_hash($value);
647         }
648         
649         $salt='';
650         while(strlen($salt)<9) {
651             $salt.=chr(rand(64,126));
652             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
653         }
654         $this->passwd = crypt($value, '$1$'. $salt. '$');
655        
656        
657     }      
658     
659     function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
660     {
661         require_once 'Text/Password.php';
662         $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
663         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
664         $this->setPassword($this->rawPasswd);
665         return $this->rawPasswd;
666     }
667     
668     function company()
669     {
670         if (empty($this->company_id)) {
671             return false;
672         }
673         $x = DB_DataObject::factory('core_company');
674         $x->autoJoin();
675         $x->get($this->company_id);
676         return $x;
677     }
678     function loadCompany()
679     {
680         $this->company = $this->company();
681     }
682     
683     function active()
684     { 
685         return $this->active;
686     }
687     function authUserName($n) // set username prior to acheck user exists query.
688     {
689         
690         $this->whereAdd('LENGTH(passwd) > 1'); 
691         $this->email = $n;
692     }
693     function lang()
694     {
695         if (!func_num_args()) {
696             return $this->lang;
697         }
698         $ar = func_get_args();
699         $val = array_shift($ar);
700         if ($val == $this->lang) {
701             return;
702         }
703         $uu = clone($this);
704         $this->lang = $val;
705         $this->update($uu);
706         if(!empty(self::$authUser) && self::$authUser->id == $this->id) {
707             self::$authUser->lang = $this->lang;
708         }
709         return $this->lang;
710     }
711             
712     
713     function authUserArray()
714     {
715         $aur = $this->toArray();
716         
717         if ($this->id < 1) {
718             return $aur;
719         }
720         
721         //DB_DataObject::debugLevel(1);
722         $c = DB_Dataobject::factory('core_company');
723         $im = DB_Dataobject::factory('Images');
724         $c->joinAdd($im, 'LEFT');
725         $c->selectAdd();
726         $c->selectAs($c, 'company_id_%s');
727         $c->selectAs($im, 'company_id_logo_id_%s');
728         $c->id = $this->company_id;
729         $c->limit(1);
730         $c->find(true);
731         
732         $aur = array_merge( $c->toArray(),$aur);
733         
734         if (empty($c->company_id_logo_id_id))  {
735                  
736             $im = DB_Dataobject::factory('Images');
737             $im->ontable = DB_DataObject::factory('core_company')->tableName();
738             $im->onid = $c->id;
739             $im->imgtype = 'LOGO';
740             $im->limit(1);
741             $im->selectAdd();
742             $im->selectAs($im,  'company_id_logo_id_%s');
743             if ($im->find(true)) {
744                 
745                 foreach($im->toArray() as $k=>$v) {
746                     if (!preg_match('/^company_id_logo_id_/', $k)) {
747                         continue;
748                     }
749                     $aur[$k] = $v;
750                 }
751             }
752         }
753       
754         // perms + groups.
755         $aur['perms']  = $this->getPerms();
756         $g = DB_DataObject::Factory('core_group_member');
757         $aur['groups']  = $g->listGroupMembership($this, 'name');
758         
759         $aur['passwd'] = '';
760         $aur['dailykey'] = '';
761         $aur['oath_key'] = '';
762         
763         $aur['oath_key_enable'] = !empty($this->oath_key);
764         $aur['require_oath'] = 1;
765         
766         $s = DB_DataObject::Factory('core_setting');
767         $oath_require = $s->lookup('core', 'two_factor_auth_required');
768         $aur['require_oath'] = $oath_require ?  $oath_require->val : 0;
769         
770         $aur['core_person_settings'] = array();
771                 
772         $core_person_settings = DB_DataObject::factory('core_person_settings');
773         $core_person_settings->setFrom(array(
774             'person_id' => $this->id
775         ));
776         
777         $aur['core_person_settings'] = $core_person_settings->fetchAll('scope', 'data');
778         
779         return $aur;
780     }
781     
782     //   ----------PERMS------  ----------------
783     function getPerms() 
784     {
785          //DB_DataObject::debugLevel(1);
786         // find out all the groups they are a member of.. + Default..
787         
788         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
789         
790         $g = DB_DataObject::Factory('core_group_right');
791         if (!$g->count()) {
792             $g->genDefault();
793         }
794         
795         if ($this->id < 0) {
796             return $g->adminRights(); // system is not set up - so they get full rights.
797         }
798         //DB_DataObject::debugLevel(1);
799         $g = DB_DataObject::Factory('core_group_member');
800         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
801         if (!$g->count()) {
802             // add the current user to the admin group..
803             $g = DB_DataObject::Factory('core_group');
804             if ($g->get('name', 'Administrators')) {
805                 $gm = DB_DataObject::Factory('core_group_member');
806                 $gm->group_id = $g->id;
807                 $gm->user_id = $this->id;
808                 $gm->insert();
809             }
810             
811         }
812         
813         // ------ STANDARD PERMISSION HANDLING.
814         $isOwner = $this->company()->comptype == 'OWNER';
815         $g = DB_DataObject::Factory('core_group_member');
816         $grps = $g->listGroupMembership($this);
817        //var_dump($grps);
818         $isAdmin = $g->inAdmin;   //???  what???
819         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
820         // the load all the perms for those groups, and add them all together..
821         // then load all those 
822         $g = DB_DataObject::Factory('core_group_right');
823         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
824         //echo '<PRE>';print_r($ret);
825         return $ret;
826          
827         
828     }
829     /**
830      *Basic group fetching - probably needs to filter by type eventually.
831      *
832      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
833      */
834     
835     function groups($what=false)
836     {
837         $g = DB_DataObject::Factory('core_group_member');
838         $grps = $g->listGroupMembership($this);
839         $g = DB_DataObject::Factory('core_group');
840         $g->whereAddIn('id', $grps, 'int');
841         return $g->fetchAll($what);
842         
843     }
844     
845     
846     
847     function hasPerm($name, $lvl) 
848     {
849         static $pcache = array();
850         
851         if (!isset($pcache[$this->id])) {
852             $pcache[$this->id] = $this->getPerms();
853         }
854         
855        // echo "<PRE>";print_r($pcache[$au->id]);
856        // var_dump($pcache[$au->id]);
857         if (empty($pcache[$this->id][$name])) {
858             return false;
859         }
860         
861         return strpos($pcache[$this->id][$name], $lvl) > -1;
862         
863     }    
864     
865     //  ------------ROO HOOKS------------------------------------
866     function applyFilters($q, $au, $roo)
867     {
868         //DB_DataObject::DebugLevel(1);
869         if(!empty($q['_to_qr_code'])){
870             $person = DB_DataObject::factory('Core_person');
871             $person->id = $q['id']; 
872             
873             if(!$person->find(true)) {
874                 $roo->jerr('_invalid_person');
875             }
876             
877             $hash = $this->generateOathKey();
878             
879             $_SESSION[__CLASS__] = 
880                 isset($_SESSION[__CLASS__]) ? 
881                     $_SESSION[__CLASS__] : array();
882             $_SESSION[__CLASS__]['oath'] = 
883                 isset($_SESSION[__CLASS__]['oath']) ? 
884                     $_SESSION[__CLASS__]['oath'] : array();
885                 
886             $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
887
888             $qrcode = $person->generateQRCode($hash);
889             
890             if(empty($qrcode)){
891                 $roo->jerr('Fail to generate QR Code');
892             }
893             
894             $roo->jdata(array(
895                 'secret' => $hash,
896                 'image' => $qrcode,
897                 'issuer' => $person->qrCodeIssuer()
898             ));
899         }
900         
901         if(!empty($q['two_factor_auth_code'])) {
902             $person = DB_DataObject::factory('core_person');
903             $person->get($q['id']);
904             $o = clone($person);
905             $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
906             
907             if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
908                 $person->update($o);
909                 unset($_SESSION[__CLASS__]['oath'][$person->id]);
910                 $roo->jok('DONE');
911             }
912             
913             $roo->jerr('_invalid_auth_code');
914         }
915         
916         if(!empty($q['oath_key_disable'])) {
917             $person = DB_DataObject::factory('core_person');
918             $person->get($q['id']);
919             
920             $o = clone($person);
921             
922             $person->oath_key = '';
923             $person->update($o);
924             
925             $roo->jok('DONE');
926         }
927         
928         if (!empty($q['query']['is_owner'])) {
929             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
930         }
931         
932         if (!empty($q['query']['person_not_internal'])) {
933             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
934         }
935         
936         if (!empty($q['query']['person_internal_only_all'])) {
937             
938             
939             // must be internal and not current user (need for distribution list)
940             // user has a projectdirectory entry and role is not blank.
941             //DB_DataObject::DebugLevel(1);
942             $pd = DB_DataObject::factory('ProjectDirectory');
943             $pd->whereAdd("role != ''");
944             $pd->selectAdd();
945             $pd->selectAdd('distinct(person_id) as person_id');
946             $roled = $pd->fetchAll('person_id');
947             $rs = $roled  ? "  OR
948                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
949                     " : '';
950             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
951             
952         }
953         // -- for distribution
954         if (!empty($q['query']['person_internal_only'])) {
955             // must be internal and not current user (need for distribution list)
956             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
957             
958             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
959             //    ".id  != ".$au->id);
960             $this->whereAdd("{$this->tableName()}.id != {$au->id}");
961         } 
962         
963         if (!empty($q['query']['comptype_or_company_id'])) {
964            // DB_DataObject::debugLevel(1);
965             $bits = explode(',', $q['query']['comptype_or_company_id']);
966             $id = (int) array_pop($bits);
967             $ct = $this->escape($bits[0]);
968             
969             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
970             
971         }
972         
973         
974         // staff list..
975         if (!empty($q['query']['person_inactive'])) {
976            // DB_Dataobject::debugLevel(1);
977             $this->active = 1;
978         }
979         $tn_p = $this->tableName();
980         $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
981         $tn_g = DB_DataObject::Factory('core_group')->tableName();
982
983         ///---------------- Group views --------
984         if (!empty($q['query']['in_group'])) {
985             // DB_DataObject::debugLevel(1);
986             $ing = (int) $q['query']['in_group'];
987             if ($q['query']['in_group'] == -1) {
988              
989                 // list all staff who are not in a group.
990                 $this->whereAdd("{$this->tableName()}.id NOT IN (
991                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
992                         $tn_g ON $tn_g.id = $tn_gm.group_id)");
993                 
994             } else {
995                 
996                 $this->whereAdd("$tn_p.id IN (
997                     SELECT distinct(user_id) FROM $tn_gm
998                         WHERE group_id = $ing
999                     )");
1000                }
1001             
1002         }
1003         
1004         if(!empty($q['in_group_name'])){
1005             
1006             $v = $this->escape($q['in_group_name']);
1007             
1008             $this->whereAdd("
1009                 $tn_p.id IN (
1010                     SELECT 
1011                         DISTINCT(user_id) FROM $tn_gm
1012                     LEFT JOIN
1013                         $tn_g
1014                     ON
1015                         $tn_g.id = $tn_gm.group_id
1016                     WHERE 
1017                         $tn_g.name = '{$v}'
1018                 )"
1019             );
1020         }
1021         if(!empty($q['in_group_starts'])){
1022             
1023             $v = $this->escape($q['in_group_starts']);
1024             
1025             $this->whereAdd("
1026                 $tn_p.id IN (
1027                     SELECT 
1028                         DISTINCT(user_id) FROM $tn_gm
1029                     LEFT JOIN
1030                         $tn_g
1031                     ON
1032                         $tn_g.id = $tn_gm.group_id
1033                     WHERE 
1034                         $tn_g.name LIKE '{$v}%'
1035                 )"
1036             );
1037         }
1038         
1039         
1040         
1041         // #2307 Search Country!!
1042         if (!empty($q['query']['in_country'])) {
1043             // DB_DataObject::debugLevel(1);
1044             $inc = $q['query']['in_country'];
1045             $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
1046         }
1047         
1048         if (!empty($q['query']['not_in_directory'])) { 
1049             // it's a Person list..
1050             // DB_DATaobjecT::debugLevel(1);
1051             
1052             // specific to project directory which is single comp. login
1053             //
1054             $owncomp = DB_DataObject::Factory('core_company');
1055             $owncomp->get('comptype', 'OWNER');
1056             if ($q['company_id'] == $owncomp->id) {
1057                 $this->active =1;
1058             }
1059             
1060             
1061
1062             if ( $q['query']['not_in_directory'] > -1) {
1063                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1064                 // can list current - so that it does not break!!!
1065                 $this->whereAdd("$tn_p.id NOT IN 
1066                     ( SELECT distinct person_id FROM $tn_pd WHERE
1067                         project_id = " . $q['query']['not_in_directory'] . " AND 
1068                         company_id = " . $this->company_id . ')');
1069             }
1070         }
1071            
1072         if (!empty($q['query']['role'])) { 
1073             // it's a Person list..
1074             // DB_DATaobjecT::debugLevel(1);
1075             
1076             // specific to project directory which is single comp. login
1077             //
1078             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1079                 // can list current - so that it does not break!!!
1080             $this->whereAdd("$tn_p.id IN 
1081                     ( SELECT distinct person_id FROM $tn_pd WHERE
1082                         role = '". $this->escape($q['query']['role']) ."'
1083             )");
1084         
1085         }
1086         
1087         
1088         if (!empty($q['query']['project_member_of'])) {
1089                // this is also a flag to return if they are a member..
1090             //DB_DataObject::debugLevel(1);
1091             $do = DB_DataObject::factory('ProjectDirectory');
1092             $do->project_id = $q['query']['project_member_of'];
1093             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1094             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
1095             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
1096                 
1097                 
1098             if (!empty($q['query']['project_member_filter'])) {
1099                 $this->having('is_member !=0');
1100             
1101             }
1102             
1103         }
1104         
1105         if(!empty($q['query']['name'])){
1106             $this->whereAdd("
1107                 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
1108             ");
1109         }
1110         
1111          if(!empty($q['query']['name_or_email'])){
1112             $v = $this->escape($q['query']['name_or_email']);
1113             $this->whereAdd("
1114                 {$this->tableName()}.name LIKE '%{$v}%'
1115                 OR
1116                 {$this->tableName()}.email LIKE '%{$v}%'
1117             ");
1118         }
1119          if(!empty($q['query']['name_starts'])){
1120             $this->whereAdd("
1121                 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
1122             ");
1123         }
1124         
1125         if (!empty($q['query']['search'])) {
1126             
1127             // use our magic search builder...
1128             
1129              require_once 'Text/SearchParser.php';
1130             $x = new Text_SearchParser($q['query']['search']);
1131             
1132             $props = array(
1133                     "$tn_p.name",
1134                     "$tn_p.email",
1135                     "$tn_p.role",
1136                     "$tn_p.phone",
1137                     "$tn_p.remarks",
1138                     "join_company_id_id.name"
1139             );
1140             $tbcols = $this->table();
1141             foreach(array('firstname','lastname') as $k) {
1142                 if (isset($tbcols[$k])) {
1143                     $props[] = "{$tn_p}.{$k}";
1144                 }
1145             }
1146             
1147             
1148             
1149             
1150             $str =  $x->toSQL(array(
1151                 'default' => $props,
1152                 'map' => array(
1153                     'company' => 'join_company_id_id.name',
1154                     //'country' => 'Clipping.country',
1155                     //  'media' => 'Clipping.media_name',
1156                 ),
1157                 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1158
1159             ));
1160             
1161             
1162             $this->whereAdd($str); /*
1163                         $tn_p.name LIKE '%$s%'  OR
1164                         $tn_p.email LIKE '%$s%'  OR
1165                         $tn_p.role LIKE '%$s%'  OR
1166                         $tn_p.phone LIKE '%$s%' OR
1167                         $tn_p.remarks LIKE '%$s%' 
1168                         
1169                     ");*/
1170         }
1171         
1172         // project directory rules -- this may distrupt things.
1173         $p = DB_DataObject::factory('ProjectDirectory');
1174         // if project directories are set up, then we can apply project query rules..
1175         if ($p->count()) {
1176             $p->autoJoin();
1177             $pids = $p->projects($au);
1178             if (isset($q['query']['project_id'])) {   
1179                 $pid = (int)$q['query']['project_id'];
1180                 if (!in_array($pid, $pids)) {
1181                     $roo->jerr("Project not in users valid projects");
1182                 }
1183                 $pids = array($pid);
1184             }
1185             // project roles..
1186             //if (empty($q['_anyrole'])) {  // should be project_directry_role
1187             //    $p->whereAdd("{$p->tableName()}.role != ''");
1188             // }
1189             if (!empty($q['query']['role'])) {  // should be project_directry_role
1190                 $role = $this->escape($q['query']['role']); 
1191                
1192                 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1193                  
1194             }
1195             
1196             if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1197                 $peps = $p->people($pids);
1198                 $this->whereAddIn("{$this->tableName()}.id", $peps, 'int');
1199             }
1200         }    
1201         
1202         // fixme - this needs a more generic fix - it was from the mtrack_person code...
1203         if (isset($q['query']['ticket_id'])) {  
1204             // find out what state the ticket is in.
1205             $t = DB_DataObject::Factory('mtrack_ticket');
1206             $t->autoJoin();
1207             $t->get($q['query']['ticket_id']);
1208             
1209             if (!$this->checkPerm('S', $au)) {
1210                 $roo->jerr("permssion denied to query state of ticket");
1211             }
1212             
1213             $p = DB_DataObject::factory('ProjectDirectory');
1214             $pids = array($t->project_id);
1215            
1216             $peps = $p->people($pids);
1217             
1218             $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1219             
1220             //$this->whereAdd('join_prole != ''");
1221             
1222         }
1223         
1224         /*
1225          * Seems we never expose oath_key / passwd, so...
1226          */
1227         
1228         if($this->tableName() == 'core_person'){
1229             $this->_extra_cols = array('length_passwd', 'length_oath_key');
1230         
1231             $this->selectAdd("
1232                 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1233                 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1234             ");
1235         }
1236         if (isset($q['_with_group_membership'])) {
1237             $this->selectAddGroupMemberships();
1238         }
1239         
1240     }
1241     
1242     function selectAddGroupMemberships()
1243     {
1244         $this->selectAdd("
1245             
1246             COALESCE((
1247                 SELECT
1248                     GROUP_CONCAT(  CASE WHEN core_group.display_name = '' THEN core_group.name ELSE core_group.display_name  END  separator  '\n')
1249                 FROM
1250                     core_group_member
1251                 LEFT JOIN
1252                     core_group
1253                 ON
1254                     core_group.id = core_group_member.group_id
1255                 WHERE
1256                     core_group_member.user_id = core_person.id
1257                 ORDER BY
1258                     core_group.display_name ASC
1259             ), '')  as member_of");
1260     }
1261     
1262     function setFromRoo($ar, $roo)
1263     {
1264         $this->setFrom($ar); 
1265         
1266         if(!empty($ar['_enable_oath_key'])){
1267             $oath_key = $this->generateOathKey();
1268         }
1269         
1270         if (!empty($ar['passwd1'])) {
1271             $this->setPassword($ar['passwd1']);
1272         }
1273         
1274         if (    $this->id &&
1275                 ($this->email == $roo->old->email)&&
1276                 ($this->company_id == $roo->old->company_id)
1277             ) {
1278             return true;
1279         }
1280         if (empty($this->email)) {
1281             return true;
1282         }
1283         // this only applies to our owner company..
1284         $c = $this->company();
1285         if (empty($c) || empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1286             return true;
1287         }
1288         
1289         
1290         $xx = DB_Dataobject::factory($this->tableName());
1291         $xx->setFrom(array(
1292             'email' => $this->email,
1293            // 'company_id' => $x->company_id
1294         ));
1295         
1296         if ($xx->count()) {
1297             return "Duplicate Email found";
1298         }
1299         
1300         return true;
1301     }
1302     /**
1303      *
1304      * before Delete - delete significant dependancies..
1305      * this is called after checkPerm..
1306      */
1307     
1308     function beforeDelete($dependants_array, $roo)
1309     {
1310         //delete group membership except for admin group..
1311         // if they are a member of admin group do not delete anything.
1312         $default_admin = false;
1313         
1314         $e = DB_DataObject::Factory('Events');
1315         $e->whereAdd('person_id = ' . $this->id);
1316         
1317         $g = DB_DataObject::Factory('core_group');
1318         $g->get('name', 'Administrators');  // select * from core_group where name = 'Administrators'
1319         
1320         $p = DB_DataObject::Factory('core_group_member');
1321         $p->setFrom(array(
1322             'user_id' => $this->id,
1323             'group_id' => $g->id
1324         ));
1325
1326         if ($p->count()) {
1327            $roo->jerr("Please remove this user from the Administrator group before deleting");
1328         }
1329  
1330          
1331         $p = DB_DataObject::Factory('core_group_member');
1332         $p->user_id = $this->id;
1333         $mem = $p->fetchAll();  // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1334         $e->logDeletedRecord($mem);
1335                 
1336         foreach($mem as $p) { 
1337             $p->delete();
1338         }  
1339         
1340         $e = DB_DataObject::Factory('Events');        
1341         $e->person_id = $this->id;
1342         $eve = $e->fetchAll();  // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1343
1344         $e->logDeletedRecord($eve);
1345         foreach($eve as $e) { 
1346             $e->delete();
1347         }  
1348         
1349         
1350         // anything else?  
1351         
1352     }
1353     
1354     
1355     /***
1356      * Check if the a user has access to modify this item.
1357      * @param String $lvl Level (eg. Core.Projects)
1358      * @param Pman_Core_DataObjects_Person $au The authenticated user.
1359      * @param boolean $changes alllow changes???
1360      *
1361      * @return false if no access..
1362      */
1363     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1364     {
1365          
1366        // do we have an empty system..
1367         if ($au && $au->id == -1) {
1368             return true;
1369         }
1370         // if not authenticated... do not allow in???
1371         if (!$au ) {
1372             return false;
1373         }
1374         
1375         // determine if it's staff!!!
1376         $owncomp = DB_DataObject::Factory('core_company');
1377         $owncomp->get('comptype', 'OWNER');
1378         $isStaff = ($au->company_id ==  $owncomp->id);
1379        
1380        
1381         if (!$isStaff) {
1382             
1383             // - can not change company!!!
1384             if ($changes && 
1385                 isset($changes['company_id']) && 
1386                 $changes['company_id'] != $au->company_id) {
1387                 return false;
1388             }
1389             // can only set new emails..
1390             if ($changes && 
1391                     !empty($this->email) && 
1392                     isset($changes['email']) && 
1393                     $changes['email'] != $this->email) {
1394                 return false;
1395             }
1396             
1397             
1398             // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1399             // ???? do we want this?
1400             
1401             // edit self... - what about other staff members...
1402             
1403             //return $this->company_id == $au->company_id;
1404         }
1405         
1406          
1407         // yes, only owner company can mess with this...
1408         
1409         
1410         
1411     
1412         switch ($lvl) {
1413             // extra case change passwod?
1414             case 'P': //??? password
1415                 // standard perms -- for editing + if the user is dowing them selves..
1416                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1417                 return $ret || $au->id == $this->id;
1418             
1419             default:                
1420                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1421         
1422         }
1423         return false;
1424     }
1425     
1426     function beforeInsert($req, $roo)
1427     {
1428         $p = DB_DataObject::factory('core_person');
1429         if ($roo->authUser->id > -1 ||  $p->count() > 1) {
1430             $pp = DB_DataObject::factory('core_person');
1431             $pp->email  =  trim($this->email);
1432             if ($pp->count()){
1433                 $roo->jerr("that email already exists in the database");
1434             }
1435             
1436             
1437             return;
1438         }
1439         $c = DB_DataObject::Factory('core_company');
1440         $tc = $c->count();
1441         
1442         if (!$tc || $tc> 1) {
1443             $roo->jerr("can not create initial user as multiple companies already exist");
1444         }
1445         $c->find(true);
1446         $this->company_id = $c->id;
1447         $this->email = trim($this->email);
1448         
1449         
1450         
1451         
1452         
1453         
1454     }
1455     
1456     function onInsert($req, $roo)
1457     {
1458          
1459         $p = DB_DataObject::factory('core_person');
1460         if ($roo->authUser->id < 0 && $p->count() == 1) {
1461             // this seems a bit risky...
1462             
1463             $g = DB_DataObject::factory('core_group');
1464             $g->initGroups();
1465             
1466             $g->type = 0;
1467             $g->get('name', 'Administrators');
1468             
1469             $p = DB_DataObject::factory('core_group_member');
1470             $p->group_id = $g->id;
1471             $p->user_id = $this->id;     
1472             if (!$p->count()) {
1473                 $p->insert();
1474                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1475             }
1476             $this->login();
1477         }
1478         if (!empty($req['project_id_addto'])) {
1479             $pd = DB_DataObject::factory('ProjectDirectory');
1480             $pd->project_id = $req['project_id_addto'];
1481             $pd->person_id = $this->id; 
1482             $pd->ispm =0;
1483             $pd->office_id = $this->office_id;
1484             $pd->company_id = $this->company_id;
1485             $pd->insert();
1486         }
1487         
1488     }
1489     
1490     function importFromArray($roo, $persons, $opts)
1491     {
1492         if (empty($opts['prefix'])) {
1493             $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1494         }
1495         
1496         if (!is_array($persons) || empty($persons)) {
1497             $roo->jerr("error in the person data. - empty on not valid");
1498         }
1499         DB_DataObject::factory('core_group')->initGroups();
1500         
1501         foreach($persons as $person){
1502             $p = DB_DataObject::factory('core_person');
1503             if($p->get('name', $person['name'])){
1504                 continue;
1505             }
1506             $p->setFrom($person);
1507             
1508             $companies = DB_DataObject::factory('core_company');
1509             if(!$companies->get('comptype', 'OWNER')){
1510                 $roo->jerr("Missing OWNER companies!");
1511             }
1512             $p->company_id = $companies->pid();
1513             // strip the 'spaces etc.. make lowercase..
1514             $name = strtolower(str_replace(' ', '', $person['name']));
1515             $p->setPassword("{$opts['prefix']}{$name}");
1516             $p->insert();
1517             // set up groups
1518             // if $person->groups is set.. then
1519             // add this person to that group eg. groups : [ 'Administrator' ] 
1520             if(!empty($person['groups'])){
1521                 $groups = DB_DataObject::factory('core_group');
1522                 if(!$groups->get('name', $person['groups'])){
1523                     $roo->jerr("Missing groups : {$person['groups']}");
1524                 }
1525                 $gm = DB_DataObject::factory('core_group_member');
1526                 $gm->change($p, $groups, true);
1527             }
1528             
1529             $p->onInsert(array(), $roo);
1530         }
1531     }
1532     
1533     // this is for the To: "{getEmailName()}" <email@address>
1534     // not good for Dear XXXX, - use {person.firstname} for that.
1535     function getEmailName()
1536     {
1537         $name = array();
1538         
1539         if(!empty($this->honor)){
1540             array_push($name, $this->honor);
1541         }
1542         
1543         if(!empty($this->name)){
1544             array_push($name, $this->name);
1545             
1546             return implode(' ', $name);
1547         }
1548         
1549         if(!empty($this->firstname) || !empty($this->lastname)){
1550             array_push($name, $this->firstname);
1551             array_push($name, $this->lastname);
1552             
1553             $name = array_filter($name);
1554             
1555             return implode(' ', $name);
1556         }
1557         
1558         return $this->email;
1559     }
1560     
1561     function sesPrefix()
1562     {
1563         $ff= HTML_FlexyFramework::get();
1564         
1565         $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1566         
1567         $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1568         
1569         $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1570
1571         return $sesPrefix;
1572     }
1573     
1574     function loginPublic() // used where???
1575     {
1576         $this->isAuth(); // force session start..
1577          
1578         $db = $this->getDatabaseConnection();
1579         
1580         $ff = HTML_FlexyFramework::get();
1581         
1582         if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1583             return false;
1584         }
1585         
1586         $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1587         
1588         $p = DB_DAtaObject::Factory($this->tableName());
1589         $p->get($this->pid());
1590         
1591         $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1592         
1593         return true;
1594     }
1595     
1596     function beforeUpdate($old, $q, $roo)
1597     {
1598         $this->email = trim($this->email);
1599     }
1600     
1601     function generateOathKey()
1602     {
1603         require 'Base32.php';
1604         
1605         $base32 = new Base32();
1606         
1607         return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1608     }
1609     
1610     function generateQRCode($hash)
1611     {
1612         if(
1613             empty($this->email) &&
1614             empty($hash)
1615         ){
1616             return false;
1617         }
1618         
1619         $issuer = rawurlencode($this->qrCodeIssuer());
1620         
1621         $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1622         
1623         require_once 'Image/QRCode.php';
1624         
1625         $qrcode = new Image_QRCode();
1626         
1627         $image = $qrcode->makeCode($uri, array(
1628             'output_type' => 'return'
1629         ));
1630         
1631         ob_start();
1632         imagepng($image);
1633         $base64 = base64_encode(ob_get_contents());
1634         ob_end_clean();
1635         
1636         return "data:image/png;base64,{$base64}";
1637     }
1638     
1639     function qrCodeIssuer()
1640     {
1641         $pg= HTML_FlexyFramework::get()->page;
1642         
1643         $issuer = (empty($pg->company->name)) ?  'ROOJS' : "{$pg->company->name}";
1644         
1645         return $issuer;
1646     }
1647     
1648     static function test_ADMIN_PASSWORD_RESET($pg, $to)
1649     {
1650         $ff = HTML_FlexyFramework::get();
1651         $person = DB_DataObject::Factory('core_person');
1652         $person->id = -1;
1653         
1654         return array(
1655             'HTTP_HOST' => $_SERVER['SERVER_NAME'],
1656             'person' => $person,
1657             'authFrom' => 'FAKE_LINK',
1658             'authKey' => 'FAKE_KEY',
1659
1660             'rcpts' => $to->email,
1661         );
1662         
1663         return $content;
1664     }
1665     
1666     
1667  }