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