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