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