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