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