DataObjects/Person.php
[Pman.Core] / DataObjects / Person.php
1 <?php
2 /**
3  * Table Definition for Person
4  */
5 require_once 'DB/DataObject.php';
6
7
8 class Pman_Core_DataObjects_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 = '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('Person');
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 (PEAR::isError($parts)) {
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         return '"' . addslashes($this->name) . '" <' . $this->email . '>';
226     }
227     
228     function toEventString() 
229     {
230         return empty($this->name) ? $this->email : $this->name;
231     } 
232     
233     function verifyAuth()
234     { 
235         $ff= HTML_FlexyFramework::get();
236         if (!empty($ff->Pman['auth_comptype']) &&
237             (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
238            ){
239             
240             // force a logout - without a check on the isAuth - as this is called from there..
241             $db = $this->getDatabaseConnection();
242             $sesPrefix = $ff->appNameShort .'-'.get_class($this) .'-'.$db->dsn['database'] ;
243             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
244             return false;
245             
246             $ff->page->jerr("Login not permited to outside companies");
247         }
248         return true;
249         
250     }    
251    
252    
253     //   ---------------- authentication / passwords and keys stuff  ----------------
254     function isAuth()
255     {
256         $db = $this->getDatabaseConnection();
257         // we combine db + project names,
258         // otherwise if projects use different 'auth' objects
259         // then we get unserialize issues.
260         $ff= HTML_FlexyFramework::get();
261         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
262         
263         
264         @session_start();
265          
266         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
267             // in session...
268             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
269             
270             $u = DB_DataObject::factory('Person');
271             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
272               
273                 return $u->verifyAuth();
274                 
275    
276                 return true;
277             }
278             
279             unset($_SESSION[__CLASS__][$sesPrefix .'-auth']);
280             
281         }
282         // local auth - 
283         $default_admin = false;
284         if (!empty($ff->Pman['local_autoauth']) && 
285             ($ff->Pman['local_autoauth'] === true) &&
286             (!empty($_SERVER['SERVER_ADDR'])) &&
287             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
288             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
289         ) {
290             $group = DB_DataObject::factory('Groups');
291             $group->get('name', 'Administrators');
292             
293             $member = DB_DataObject::factory('group_members');
294             $member->autoJoin();
295             $member->group_id = $group->id;
296             $member->whereAdd("
297                 join_user_id_id.id IS NOT NULL
298             ");
299             if($member->find(true)){
300                 $default_admin = DB_DataObject::factory('Person');
301                 if(!$default_admin->get($member->user_id)){
302                     $default_admin = false;
303                 }
304             }
305         }
306         
307         //var_dump($ff->Pman['local_autoauth']);         var_dump($_SERVER); exit;
308         $u = DB_DataObject::factory('Person');
309         $ff = HTML_FlexyFramework::get();
310         if (!empty($ff->Pman['local_autoauth']) && 
311             (!empty($_SERVER['SERVER_ADDR'])) &&
312             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
313             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
314             ($default_admin ||  $u->get('email', $ff->Pman['local_autoauth']))
315         ) {
316             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($default_admin ? $default_admin : $u);
317             return true;
318         }
319            
320         // http basic auth..
321         $u = DB_DataObject::factory('Person');
322
323         if (!empty($_SERVER['PHP_AUTH_USER']) 
324             &&
325             !empty($_SERVER['PHP_AUTH_PW'])
326             &&
327             $u->get('email', $_SERVER['PHP_AUTH_USER'])
328             &&
329             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
330            ) {
331             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
332             return true; 
333         }
334         //var_dump(session_id());
335         //var_dump($_SESSION[__CLASS__]);
336         
337         //if (!empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
338         //    return false;
339         //}
340         //die("got this far?");
341         // not in session or not matched...
342         $u = DB_DataObject::factory('Person');
343         $u->whereAdd(' LENGTH(passwd) > 0');
344         $n = $u->count();
345         $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $n;
346         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
347         if ($error) {
348             die($error->toString()); // not really a good thing to do...
349         }
350         if (!$n){ // authenticated as there are no users in the system...
351             return true;
352         }
353         
354         return false;
355         
356     }
357     function getAuthUser()
358     {
359         if (!$this->isAuth()) {
360             return false;
361         }
362         $db = $this->getDatabaseConnection();
363         
364         $ff= HTML_FlexyFramework::get();
365         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
366
367         
368         
369         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
370             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
371             
372             $u = DB_DataObject::factory('Person');
373             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
374                 return clone($u);
375             }
376             unset($_SESSION[__CLASS__][$sesPrefix .'-auth']);
377         }
378         
379         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
380             $u = DB_DataObject::factory('Person');
381             $u->whereAdd(' LENGTH(passwd) > 0');
382             $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $u->count();
383         }
384                 
385              
386         if (isset(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] ) && $_SESSION[__CLASS__][$sesPrefix .'-empty']  < 1) {
387             
388             // fake person - open system..
389             //$ce = DB_DataObject::factory('core_enum');
390             //$ce->initEnums();
391             
392             
393             $u = DB_DataObject::factory('Person');
394             $u->id = -1;
395             
396             // if a company has been created fill that in in company_id_id
397             $c = DB_DAtaObject::factory('Companies')->lookupOwner();
398             if ($c) {
399                 $u->company_id_id = $c->pid();
400                 $u->company_id = $c->pid();
401             }
402             
403             return $u;
404             
405         }
406         return false;
407     }     
408     function login()
409     {
410         $this->isAuth(); // force session start..
411         if (!$this->verifyAuth()) {
412             return false;
413         }
414         $db = $this->getDatabaseConnection();
415         
416         
417         // open up iptables at login..
418         $dbname = $this->database();
419         touch( '/tmp/run_pman_admin_iptables-'.$dbname);
420          
421         // refresh admin group if we are logged in as one..
422         //DB_DataObject::debugLevel(1);
423         $g = DB_DataObject::factory('Groups');
424         $g->type = 0;
425         $g->get('name', 'Administrators');
426         $gm = DB_DataObject::Factory('group_members');
427         if (in_array($g->id,$gm->listGroupMembership($this))) {
428             // refresh admin groups.
429             $gr = DB_DataObject::Factory('group_rights');
430             $gr->applyDefs($g, 0);
431         }
432         $ff= HTML_FlexyFramework::get();
433         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
434
435
436         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
437         
438     }
439     function logout()
440     {
441         $this->isAuth(); // force session start..
442         $db = $this->getDatabaseConnection();
443         $ff= HTML_FlexyFramework::get();
444         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
445
446         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
447        
448         
449        
450         
451     }    
452     function genPassKey ($t) 
453     {
454         return md5($this->email . $t. $this->passwd);
455     }
456     function simpleAuthKey($m = 0)
457     {
458         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
459         
460         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
461     } 
462     function checkPassword($val)
463     {
464         
465         if (substr($this->passwd,0,1) == '$') {
466             return crypt($val,$this->passwd) == $this->passwd ;
467         }
468         // old style md5 passwords...- cant be used with courier....
469         return md5($val) == $this->passwd;
470     }
471     function setPassword($value) 
472     {
473         $salt='';
474         while(strlen($salt)<9) {
475             $salt.=chr(rand(64,126));
476             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
477         }
478         $this->passwd = crypt($value, '$1$'. $salt. '$');
479        
480        
481     }      
482     
483     function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
484     {
485         require_once 'Text/Password.php';
486         $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
487         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
488         $this->setPassword($this->rawPasswd);
489         return $this->rawPasswd;
490     }
491     
492     function company()
493     {
494         $x = DB_DataObject::factory('Companies');
495         $x->autoJoin();
496         $x->get($this->company_id);
497         return $x;
498     }
499     function loadCompany()
500     {
501         $this->company = $this->company();
502     }
503     
504     function active()
505     { 
506         return $this->active;
507     }
508     function authUserName($n) // set username prior to acheck user exists query.
509     {
510         
511         $this->whereAdd('LENGTH(passwd) > 1'); 
512         $this->email = $n;
513     }
514     function lang()
515     {
516         if (!func_num_args()) {
517             return $this->lang;
518         }
519         $val = array_shift(func_get_args());
520         if ($val == $this->lang) {
521             return;
522         }
523         $uu = clone($this);
524         $this->lang = $val;
525         $this->update($uu);
526         return $this->lang;
527     }
528             
529     
530     function authUserArray()
531     {
532         
533         $aur = $this->toArray();
534         
535         if ($this->id < 1) {
536             return $aur;
537         }
538         
539         
540         //DB_DataObject::debugLevel(1);
541         $c = DB_Dataobject::factory('Companies');
542         $im = DB_Dataobject::factory('Images');
543         $c->joinAdd($im, 'LEFT');
544         $c->selectAdd();
545         $c->selectAs($c, 'company_id_%s');
546         $c->selectAs($im, 'company_id_logo_id_%s');
547         $c->id = $this->company_id;
548         $c->limit(1);
549         $c->find(true);
550         
551         $aur = array_merge( $c->toArray(),$aur);
552         
553         if (empty($c->company_id_logo_id_id))  {
554                  
555             $im = DB_Dataobject::factory('Images');
556             $im->ontable = 'Companies';
557             $im->onid = $c->id;
558             $im->imgtype = 'LOGO';
559             $im->limit(1);
560             $im->selectAdd();
561             $im->selectAs($im,  'company_id_logo_id_%s');
562             if ($im->find(true)) {
563                     
564                 foreach($im->toArray() as $k=>$v) {
565                     $aur[$k] = $v;
566                 }
567             }
568         }
569       
570         // perms + groups.
571         $aur['perms']  = $this->getPerms();
572         $g = DB_DataObject::Factory('group_members');
573         $aur['groups']  = $g->listGroupMembership($this, 'name');
574         
575         $aur['passwd'] = '';
576         $aur['dailykey'] = '';
577         
578         
579         
580         return $aur;
581     }
582     
583     //   ----------PERMS------  ----------------
584     function getPerms() 
585     {
586          //DB_DataObject::debugLevel(1);
587         // find out all the groups they are a member of.. + Default..
588         
589         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
590         
591         $g = DB_DataObject::Factory('group_rights');
592         if (!$g->count()) {
593             $g->genDefault();
594         }
595         
596         if ($this->id < 0) {
597             return $g->adminRights(); // system is not set up - so they get full rights.
598         }
599         //DB_DataObject::debugLevel(1);
600         $g = DB_DataObject::Factory('group_members');
601         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
602         if (!$g->count()) {
603             // add the current user to the admin group..
604             $g = DB_DataObject::Factory('Groups');
605             if ($g->get('name', 'Administrators')) {
606                 $gm = DB_DataObject::Factory('group_members');
607                 $gm->group_id = $g->id;
608                 $gm->user_id = $this->id;
609                 $gm->insert();
610             }
611             
612         }
613         
614         // ------ STANDARD PERMISSION HANDLING.
615         $isOwner = $this->company()->comptype == 'OWNER';
616         $g = DB_DataObject::Factory('group_members');
617         $grps = $g->listGroupMembership($this);
618         print_R($grps);exit;
619        //var_dump($grps);
620         $isAdmin = $g->inAdmin;
621         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
622         // the load all the perms for those groups, and add them all together..
623         // then load all those 
624         $g = DB_DataObject::Factory('group_rights');
625         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
626         //echo '<PRE>';print_r($ret);
627         return $ret;
628          
629         
630     }
631     /**
632      *Basic group fetching - probably needs to filter by type eventually.
633      *
634      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
635      */
636     
637     function groups($what=false)
638     {
639         $g = DB_DataObject::Factory('group_members');
640         $grps = $g->listGroupMembership($this);
641         $g = DB_DataObject::Factory('Groups');
642         $g->whereAddIn('id', $grps, 'int');
643         return $g->fetchAll($what);
644         
645     }
646     
647     
648     
649     function hasPerm($name, $lvl) 
650     {
651         static $pcache = array();
652         
653         if (!isset($pcache[$this->id])) {
654             $pcache[$this->id] = $this->getPerms();
655         }
656        // echo "<PRE>";print_r($pcache[$au->id]);
657        // var_dump($pcache[$au->id]);
658         if (empty($pcache[$this->id][$name])) {
659             return false;
660         }
661         
662         return strpos($pcache[$this->id][$name], $lvl) > -1;
663         
664     }    
665     
666     //  ------------ROO HOOKS------------------------------------
667     function applyFilters($q, $au, $roo)
668     {
669         //DB_DataObject::DebugLevel(1);
670         
671         if (!empty($q['query']['is_owner'])) {
672             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
673         }
674         
675         if (!empty($q['query']['person_not_internal'])) {
676             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
677         }
678         
679         if (!empty($q['query']['person_internal_only_all'])) {
680             
681             
682             // must be internal and not current user (need for distribution list)
683             // user has a projectdirectory entry and role is not blank.
684             //DB_DataObject::DebugLevel(1);
685             $pd = DB_DataObject::factory('ProjectDirectory');
686             $pd->whereAdd("role != ''");
687             $pd->selectAdd();
688             $pd->selectAdd('distinct(person_id) as person_id');
689             $roled = $pd->fetchAll('person_id');
690             $rs = $roled  ? "  OR
691                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
692                     " : '';
693             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
694             
695         }
696         // -- for distribution
697         if (!empty($q['query']['person_internal_only'])) {
698             // must be internal and not current user (need for distribution list)
699             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
700             
701             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
702             //    ".id  != ".$au->id);
703             $this->whereAdd("Person.id != {$au->id}");
704         } 
705         
706         if (!empty($q['query']['comptype_or_company_id'])) {
707            // DB_DataObject::debugLevel(1);
708             $bits = explode(',', $q['query']['comptype_or_company_id']);
709             $id = (int) array_pop($bits);
710             $ct = $this->escape($bits[0]);
711             
712             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
713             
714         }
715         
716         
717         // staff list..
718         if (!empty($q['query']['person_inactive'])) {
719            // DB_Dataobject::debugLevel(1);
720             $this->active = 1;
721         }
722         $tn_p = $this->tableName();
723         $tn_gm = DB_DataObject::Factory('group_members')->tableName();
724         $tn_g = DB_DataObject::Factory('Groups')->tableName();
725
726         ///---------------- Group views --------
727         if (!empty($q['query']['in_group'])) {
728             // DB_DataObject::debugLevel(1);
729             $ing = (int) $q['query']['in_group'];
730             if ($q['query']['in_group'] == -1) {
731              
732                 // list all staff who are not in a group.
733                 $this->whereAdd("Person.id NOT IN (
734                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
735                         $tn_g ON $tn_g.id = $tn_gm.group_id
736                         WHERE $tn_g.type = ".$q['query']['type']."
737                     )");
738                 
739                 
740             } else {
741                 
742                 $this->whereAdd("$tn_p.id IN (
743                     SELECT distinct(user_id) FROM $tn_gm
744                         WHERE group_id = $ing
745                     )");
746                }
747             
748         }
749         
750         // #2307 Search Country!!
751         if (!empty($q['query']['in_country'])) {
752             // DB_DataObject::debugLevel(1);
753             $inc = $q['query']['in_country'];
754             $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
755         }
756         
757         if (!empty($q['query']['not_in_directory'])) { 
758             // it's a Person list..
759             // DB_DATaobjecT::debugLevel(1);
760             
761             // specific to project directory which is single comp. login
762             //
763             $owncomp = DB_DataObject::Factory('Companies');
764             $owncomp->get('comptype', 'OWNER');
765             if ($q['company_id'] == $owncomp->id) {
766                 $this->active =1;
767             }
768             
769             
770
771             if ( $q['query']['not_in_directory'] > -1) {
772                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
773                 // can list current - so that it does not break!!!
774                 $this->whereAdd("$tn_p.id NOT IN 
775                     ( SELECT distinct person_id FROM $tn_pd WHERE
776                         project_id = " . $q['query']['not_in_directory'] . " AND 
777                         company_id = " . $this->company_id . ')');
778             }
779         }
780            
781         if (!empty($q['query']['role'])) { 
782             // it's a Person list..
783             // DB_DATaobjecT::debugLevel(1);
784             
785             // specific to project directory which is single comp. login
786             //
787             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
788                 // can list current - so that it does not break!!!
789             $this->whereAdd("$tn_p.id IN 
790                     ( SELECT distinct person_id FROM $tn_pd WHERE
791                         role = '". $this->escape($q['query']['role']) ."'
792             )");
793         
794         }
795         
796         
797         if (!empty($q['query']['project_member_of'])) {
798                // this is also a flag to return if they are a member..
799             //DB_DataObject::debugLevel(1);
800             $do = DB_DataObject::factory('ProjectDirectory');
801             $do->project_id = $q['query']['project_member_of'];
802             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
803             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
804             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
805                 
806                 
807             if (!empty($q['query']['project_member_filter'])) {
808                 $this->having('is_member !=0');
809             
810             }
811             
812         }
813         
814         if(!empty($q['query']['name'])){
815             $this->whereAdd("
816                 Person.name LIKE '%{$this->escape($q['query']['name'])}%'
817             ");
818         }
819         
820         if (!empty($q['query']['search'])) {
821             
822             // use our magic search builder...
823             
824              require_once 'Text/SearchParser.php';
825             $x = new Text_SearchParser($q['query']['search']);
826             
827             $props = array(
828                     "$tn_p.name",
829                     "$tn_p.email",
830                     "$tn_p.role",
831                     "$tn_p.phone",
832                     "$tn_p.remarks",
833                     "join_company_id_id.name"
834             );
835             
836             $str =  $x->toSQL(array(
837                 'default' => $props,
838                 'map' => array(
839                     'company' => 'join_company_id_id.name',
840                     //'country' => 'Clipping.country',
841                     //  'media' => 'Clipping.media_name',
842                 ),
843                 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
844
845             ));
846             
847             
848             $this->whereAdd($str); /*
849                         $tn_p.name LIKE '%$s%'  OR
850                         $tn_p.email LIKE '%$s%'  OR
851                         $tn_p.role LIKE '%$s%'  OR
852                         $tn_p.phone LIKE '%$s%' OR
853                         $tn_p.remarks LIKE '%$s%' 
854                         
855                     ");*/
856         }
857         
858     }
859     function setFromRoo($ar, $roo)
860     {
861         $this->setFrom($ar);
862         if (!empty($ar['passwd1'])) {
863             $this->setPassword($ar['passwd1']);
864         }
865         
866         
867         if (    $this->id &&
868                 ($this->email == $roo->old->email)&&
869                 ($this->company_id == $roo->old->company_id)
870             ) {
871             return true;
872         }
873         if (empty($this->email)) {
874             return true;
875         }
876         $xx = DB_Dataobject::factory('Person');
877         $xx->setFrom(array(
878             'email' => $this->email,
879            // 'company_id' => $x->company_id
880         ));
881         
882         if ($xx->count()) {
883             return "Duplicate Email found";
884         }
885         return true;
886     }
887     /**
888      *
889      * before Delete - delete significant dependancies..
890      * this is called after checkPerm..
891      */
892     
893     function beforeDelete()
894     {
895         
896         $e = DB_DataObject::Factory('Events');
897         $e->whereAdd('person_id = ' . $this->id);
898         $e->delete(true);
899         
900         // anything else?  
901         
902     }
903     
904     
905     /***
906      * Check if the a user has access to modify this item.
907      * @param String $lvl Level (eg. Core.Projects)
908      * @param Pman_Core_DataObjects_Person $au The authenticated user.
909      * @param boolean $changes alllow changes???
910      *
911      * @return false if no access..
912      */
913     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
914     {
915          
916        // do we have an empty system..
917         if ($au && $au->id == -1) {
918             return true;
919         }
920         
921         // determine if it's staff!!!
922          
923         if ($au->company()->comptype != 'OWNER') {
924             
925             // - can not change company!!!
926             if ($changes && 
927                 isset($changes['company_id']) && 
928                 $changes['company_id'] != $au->company_id) {
929                 return false;
930             }
931             // can only set new emails..
932             if ($changes && 
933                     !empty($this->email) && 
934                     isset($changes['email']) && 
935                     $changes['email'] != $this->email) {
936                 return false;
937             }
938             
939             // edit self... - what about other staff members...
940             
941             return $this->company_id == $au->company_id;
942         }
943          
944          
945         // yes, only owner company can mess with this...
946         $owncomp = DB_DataObject::Factory('Companies');
947         $owncomp->get('comptype', 'OWNER');
948         
949         $isStaff = ($this->company_id ==  $owncomp->id);
950         
951     
952         switch ($lvl) {
953             // extra case change passwod?
954             case 'P': //??? password
955                 // standard perms -- for editing + if the user is dowing them selves..
956                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
957                 return $ret || $au->id == $this->id;
958             
959             default:                
960                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
961         
962         }
963         return false;
964     }
965     
966     function onInsert($req, $roo)
967     {
968          
969         $p = DB_DataObject::factory('person');
970         if ($roo->authUser->id < 0 && $p->count() == 1) {
971             // this seems a bit risky...
972             
973             $g = DB_DataObject::factory('Groups');
974             $g->initGroups();
975             
976             $g->type = 0;
977             $g->get('name', 'Administrators');
978             
979             $p = DB_DataObject::factory('group_members');
980             $p->group_id = $g->id;
981             $p->user_id = $this->id;     
982             if (!$p->count()) {
983                 $p->insert();
984                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
985             }
986             $this->login();
987         }
988         if (!empty($req['project_id_addto'])) {
989             $pd = DB_DataObject::factory('ProjectDirectory');
990             $pd->project_id = $req['project_id_addto'];
991             $pd->person_id = $this->id; 
992             $pd->ispm =0;
993             $pd->office_id = $this->office_id;
994             $pd->company_id = $this->company_id;
995             $pd->insert();
996         }
997         
998     }
999     
1000     function importFromArray($roo, $persons, $opts)
1001     {
1002         if (empty($opts['prefix'])) {
1003             $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1004         }
1005         
1006         if (!is_array($persons) || empty($persons)) {
1007             $roo->jerr("error in the person data. - empty on not valid");
1008         }
1009         DB_DataObject::factory('groups')->initGroups();
1010         
1011         foreach($persons as $person){
1012             $p = DB_DataObject::factory('person');
1013             if($p->get('name', $person['name'])){
1014                 continue;
1015             }
1016             $p->setFrom($person);
1017             
1018             $companies = DB_DataObject::factory('companies');
1019             if(!$companies->get('comptype', 'OWNER')){
1020                 $roo->jerr("Missing OWNER companies!");
1021             }
1022             $p->company_id = $companies->pid();
1023             // strip the 'spaces etc.. make lowercase..
1024             $name = strtolower(str_replace(' ', '', $person['name']));
1025             $p->setPassword("{$opts['prefix']}{$name}");
1026             $p->insert();
1027             // set up groups
1028             // if $person->groups is set.. then
1029             // add this person to that group eg. groups : [ 'Administrator' ] 
1030             if(!empty($person['groups'])){
1031                 $groups = DB_DataObject::factory('groups');
1032                 if(!$groups->get('name', $person['groups'])){
1033                     $roo->jerr("Missing groups : {$person['groups']}");
1034                 }
1035                 $gm = DB_DataObject::factory('group_members');
1036                 $gm->change($p, $groups, true);
1037             }
1038             
1039             $p->onInsert(array(), $roo);
1040         }
1041     }
1042     
1043     function getEmailName()
1044     {
1045         $name = array();
1046         
1047         if(!empty($this->honor)){
1048             array_push($name, $this->honor);
1049         }
1050         
1051         if(!empty($this->name)){
1052             array_push($name, $this->name);
1053             
1054             return implode(' ', $name);
1055         }
1056         
1057         if(!empty($this->firstname) || !empty($this->lastname)){
1058             array_push($name, $this->firstname);
1059             array_push($name, $this->lastname);
1060             
1061             $name = array_filter($name);
1062             
1063             return $name;
1064         }
1065         
1066         return $this->email;
1067     }
1068     
1069  }