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