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