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