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