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