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     
46     public $phone_mobile; // varchar(32)  NOT NULL  DEFAULT '';
47     public $phone_direct; // varchar(32)  NOT NULL  DEFAULT '';
48     
49     /* the code above is auto generated do not remove the tag below */
50     ###END_AUTOCODE
51     
52     function owner()
53     {
54         $p = DB_DataObject::Factory('Person');
55         $p->get($this->owner_id);
56         return $p;
57     }
58     
59     /**
60      *
61      *
62      *
63      *
64      *  FIXME !!!! -- USE Pman_Core_Mailer !!!!!
65      *
66      *
67      *
68      *  
69      */
70     function buildMail($templateFile, $args)
71     {
72           
73         $args = (array) $args;
74         $content  = clone($this);
75         
76         foreach((array)$args as $k=>$v) {
77             $content->$k = $v;
78         }
79         
80         $ff = HTML_FlexyFramework::get();
81         
82         
83         //?? is this really the place for this???
84         if (
85                 !$ff->cli && 
86                 empty($args['no_auth']) &&
87                 !in_array($templateFile, array(
88                     // templates that can be sent without authentication.
89                      'password_reset' ,
90                      'password_welcome'
91                  ))
92             ) {
93             
94             $content->authUser = $this->getAuthUser();
95             if (!$content->authUser) {
96                 return PEAR::raiseError("Not authenticated");
97             }
98         }
99         
100         // should handle x-forwarded...
101         
102         $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
103             $_SERVER["HTTP_HOST"] :
104             (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
105             
106         /* use the regex compiler, as it doesnt parse <tags */
107         
108         $tops = array(
109             'compiler'    => 'Flexy',
110             'nonHTML' => true,
111             'filters' => array('SimpleTags','Mail'),
112             //     'debug'=>1,
113         );
114         
115         
116         
117         if (!empty($args['templateDir'])) {
118             $tops['templateDir'] = $args['templateDir'];
119         }
120         
121         
122         
123         require_once 'HTML/Template/Flexy.php';
124         $template = new HTML_Template_Flexy( $tops );
125         $template->compile("mail/$templateFile.txt");
126         
127         /* use variables from this object to ouput data. */
128         $mailtext = $template->bufferedOutputObject($content);
129         
130         $htmlbody = false;
131         // if a html file with the same name exists, use that as the body
132         // I've no idea where this code went, it was here before..
133         if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
134             $tops['nonHTML'] = false;
135             $template = new HTML_Template_Flexy( $tops );
136             $template->compile("mail/$templateFile.html");
137             $htmlbody = $template->bufferedOutputObject($content);
138             
139         }
140         
141         
142         
143         //echo "<PRE>";print_R($mailtext);
144         //print_R($mailtext);exit;
145         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
146         require_once 'Mail/mimeDecode.php';
147         require_once 'Mail.php';
148         
149         $decoder = new Mail_mimeDecode($mailtext);
150         $parts = $decoder->getSendArray();
151         
152         if (PEAR::isError($parts)) {
153             return $parts;
154             //echo "PROBLEM: {$parts->message}";
155             //exit;
156         } 
157         list($recipents,$headers,$body) = $parts;
158         $recipents = array($this->email);
159         if (!empty($content->bcc) && is_array($content->bcc)) {
160             $recipents =array_merge($recipents, $content->bcc);
161         }
162         $headers['Date'] = date('r');
163         
164         if ($htmlbody !== false) {
165             require_once 'Mail/mime.php';
166             $mime = new Mail_mime(array('eol' => "\n"));
167             $mime->setTXTBody($body);
168             $mime->setHTMLBody($htmlbody);
169             // I think there might be code in mediaoutreach toEmail somewhere
170             // h embeds images here..
171             $body = $mime->get();
172             $headers = $mime->headers($headers);
173             
174         }
175         
176          
177         
178         return array(
179             'recipients' => $recipents,
180             'headers'    => $headers,
181             'body'      => $body
182         );
183         
184         
185     }
186     
187     
188     /**
189      * send a template
190      * - user must be authenticate or args[no_auth] = true
191      *   or template = password_[reset|welcome]
192      * 
193      */
194     function sendTemplate($templateFile, $args)
195     {
196         
197         $ar = $this->buildMail($templateFile, $args);
198       
199         
200         //print_r($recipents);exit;
201         $mailOptions = PEAR::getStaticProperty('Mail','options');
202         $mail = Mail::factory("SMTP",$mailOptions);
203         
204         if (PEAR::isError($mail)) {
205             return $mail;
206         } 
207         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
208         $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
209         error_reporting($oe);
210        
211         return $ret;
212     
213     }
214     
215   
216     
217     
218     function getEmailFrom()
219     {
220         return '"' . addslashes($this->name) . '" <' . $this->email . '>';
221     }
222     function toEventString() 
223     {
224         return empty($this->name) ? $this->email : $this->name;
225     } 
226     function verifyAuth()
227     { 
228         $ff= HTML_FlexyFramework::get();
229         if (!empty($ff->Pman['auth_comptype']) &&
230             (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
231            ){
232             
233             // force a logout - without a check on the isAuth - as this is called from there..
234             $db = $this->getDatabaseConnection();
235             $sesPrefix = $ff->appNameShort .'-'.get_class($this) .'-'.$db->dsn['database'] ;
236             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
237             return false;
238             
239             $ff->page->jerr("Login not permited to outside companies");
240         }
241         return true;
242         
243     }    
244    
245    
246     //   ---------------- authentication / passwords and keys stuff  ----------------
247     function isAuth()
248     {
249         $db = $this->getDatabaseConnection();
250         // we combine db + project names,
251         // otherwise if projects use different 'auth' objects
252         // then we get unserialize issues.
253         $ff= HTML_FlexyFramework::get();
254         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
255         
256         
257         @session_start();
258          
259         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
260             // in session...
261             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
262             
263             $u = DB_DataObject::factory('Person');
264             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
265               
266                 return $u->verifyAuth();
267                 
268    
269                 return true;
270             }
271             
272             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
273             
274         }
275         // local auth - 
276         $default_admin = false;
277         if (!empty($ff->Pman['local_autoauth']) && 
278             ($ff->Pman['local_autoauth'] === true) &&
279             (!empty($_SERVER['SERVER_ADDR'])) &&
280             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
281             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
282         ) {
283             $group = DB_DataObject::factory('Groups');
284             $group->get('name', 'Administrators');
285             
286             $member = DB_DataObject::factory('group_members');
287             $member->group_id = $group->id;
288             if($member->find(true)){
289                 $default_admin = DB_DataObject::factory('Person');
290                 if(!$default_admin->get($member->user_id)){
291                     $default_admin = false;
292                 }
293             }
294         }
295         
296         $u = DB_DataObject::factory('Person');
297         $ff = HTML_FlexyFramework::get();
298         if (!empty($ff->Pman['local_autoauth']) && 
299             (!empty($_SERVER['SERVER_ADDR'])) &&
300             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
301             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
302             ($default_admin ||  $u->get('email', $ff->Pman['local_autoauth']))
303         ) {
304             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($default_admin ? $default_admin : $u);
305             return true;
306         }
307            
308         // http basic auth..
309         $u = DB_DataObject::factory('Person');
310
311         if (!empty($_SERVER['PHP_AUTH_USER']) 
312             &&
313             !empty($_SERVER['PHP_AUTH_PW'])
314             &&
315             $u->get('email', $_SERVER['PHP_AUTH_USER'])
316             &&
317             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
318            ) {
319             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
320             return true; 
321         }
322         
323         if (!empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
324             return false;
325         }
326         
327         // not in session or not matched...
328         $u = DB_DataObject::factory('Person');
329         $u->whereAdd(' LENGTH(passwd) > 0');
330         $n = $u->count();
331         $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $n;
332         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
333         if ($error) {
334             die($error->toString()); // not really a good thing to do...
335         }
336         if (!$n){ // authenticated as there are no users in the system...
337             return true;
338         }
339         
340         return false;
341         
342     }
343     function getAuthUser()
344     {
345         if (!$this->isAuth()) {
346             return false;
347         }
348         $db = $this->getDatabaseConnection();
349         
350         $ff= HTML_FlexyFramework::get();
351         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
352
353         
354         
355         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
356             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
357             
358             $u = DB_DataObject::factory('Person');
359             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
360                 return clone($u);
361             }
362              
363         }
364         
365         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
366             $u = DB_DataObject::factory('Person');
367             $u->whereAdd(' LENGTH(passwd) > 0');
368             $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $u->count();
369         }
370                 
371              
372         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
373             
374             // fake person - open system..
375             //$ce = DB_DataObject::factory('core_enum');
376             //$ce->initEnums();
377             
378             
379             $u = DB_DataObject::factory('Person');
380             $u->id = -1;
381             
382             // if a company has been created fill that in in company_id_id
383             $c = DB_DAtaObject::factory('Companies')->lookupOwner();
384             if ($c) {
385                 $u->company_id_id = $c->pid();
386                 $u->company_id= $c->pid();
387             }
388             
389             return $u;
390             
391         }
392         return false;
393     }     
394     function login()
395     {
396         $this->isAuth(); // force session start..
397         if (!$this->verifyAuth()) {
398             return false;
399         }
400         $db = $this->getDatabaseConnection();
401         
402         
403         // open up iptables at login..
404         $dbname = $this->database();
405         touch( '/tmp/run_pman_admin_iptables-'.$dbname);
406          
407         // refresh admin group if we are logged in as one..
408         //DB_DataObject::debugLevel(1);
409         $g = DB_DataObject::factory('Groups');
410         $g->type = 0;
411         $g->get('name', 'Administrators');
412         $gm = DB_DataObject::Factory('group_members');
413         if (in_array($g->id,$gm->listGroupMembership($this))) {
414             // refresh admin groups.
415             $gr = DB_DataObject::Factory('group_rights');
416             $gr->applyDefs($g, 0);
417         }
418         $ff= HTML_FlexyFramework::get();
419         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
420
421
422         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
423         
424     }
425     function logout()
426     {
427         $this->isAuth(); // force session start..
428         $db = $this->getDatabaseConnection();
429         $ff= HTML_FlexyFramework::get();
430         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
431
432         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
433         
434     }    
435     function genPassKey ($t) 
436     {
437         return md5($this->email . $t. $this->passwd);
438     }
439     function simpleAuthKey($m = 0)
440     {
441         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
442         
443         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
444     } 
445     function checkPassword($val)
446     {
447         
448         if (substr($this->passwd,0,1) == '$') {
449             return crypt($val,$this->passwd) == $this->passwd ;
450         }
451         // old style md5 passwords...- cant be used with courier....
452         return md5($val) == $this->passwd;
453     }
454     function setPassword($value) 
455     {
456         $salt='';
457         while(strlen($salt)<9) {
458             $salt.=chr(rand(64,126));
459             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
460         }
461         $this->passwd = crypt($value, '$1$'. $salt. '$');
462        
463        
464     }      
465     
466     function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
467     {
468         require_once 'Text/Password.php';
469         $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
470         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
471         $this->setPassword($this->rawPasswd);
472         return $this->rawPasswd;
473     }
474     
475     function company()
476     {
477         $x = DB_DataObject::factory('Companies');
478         $x->autoJoin();
479         $x->get($this->company_id);
480         return $x;
481     }
482     function loadCompany()
483     {
484         $this->company = $this->company();
485     }
486     
487     function active()
488     { 
489         return $this->active;
490     }
491     function authUserName($n) // set username prior to acheck user exists query.
492     {
493         
494         $this->whereAdd('LENGTH(passwd) > 1'); 
495         $this->email = $n;
496     }
497     function lang()
498     {
499         if (!func_num_args()) {
500             return $this->lang;
501         }
502         $val = array_shift(func_get_args());
503         if ($val == $this->lang) {
504             return;
505         }
506         $uu = clone($this);
507         $this->lang = $val;
508         $this->update($uu);
509         return $this->lang;
510     }
511             
512     
513     function authUserArray()
514     {
515         
516         $aur = $this->toArray();
517         
518         if ($this->id < 1) {
519             return $aur;
520         }
521         
522         
523         //DB_DataObject::debugLevel(1);
524         $c = DB_Dataobject::factory('Companies');
525         $im = DB_Dataobject::factory('Images');
526         $c->joinAdd($im, 'LEFT');
527         $c->selectAdd();
528         $c->selectAs($c, 'company_id_%s');
529         $c->selectAs($im, 'company_id_logo_id_%s');
530         $c->id = $this->company_id;
531         $c->limit(1);
532         $c->find(true);
533         
534         $aur = array_merge( $c->toArray(),$aur);
535         
536         if (empty($c->company_id_logo_id_id))  {
537                  
538             $im = DB_Dataobject::factory('Images');
539             $im->ontable = 'Companies';
540             $im->onid = $c->id;
541             $im->imgtype = 'LOGO';
542             $im->limit(1);
543             $im->selectAdd();
544             $im->selectAs($im,  'company_id_logo_id_%s');
545             if ($im->find(true)) {
546                     
547                 foreach($im->toArray() as $k=>$v) {
548                     $aur[$k] = $v;
549                 }
550             }
551         }
552       
553         // perms + groups.
554         $aur['perms']  = $this->getPerms();
555         $g = DB_DataObject::Factory('group_members');
556         $aur['groups']  = $g->listGroupMembership($this, 'name');
557         
558         $aur['passwd'] = '';
559         $aur['dailykey'] = '';
560         
561         
562         
563         return $aur;
564     }
565     
566     //   ----------PERMS------  ----------------
567     function getPerms() 
568     {
569          //DB_DataObject::debugLevel(1);
570         // find out all the groups they are a member of.. + Default..
571         
572         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
573         
574         $g = DB_DataObject::Factory('group_rights');
575         if (!$g->count()) {
576             $g->genDefault();
577         }
578         
579         if ($this->id < 0) {
580             return $g->adminRights(); // system is not set up - so they get full rights.
581         }
582         //DB_DataObject::debugLevel(1);
583         $g = DB_DataObject::Factory('group_members');
584         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
585         if (!$g->count()) {
586             // add the current user to the admin group..
587             $g = DB_DataObject::Factory('Groups');
588             if ($g->get('name', 'Administrators')) {
589                 $gm = DB_DataObject::Factory('group_members');
590                 $gm->group_id = $g->id;
591                 $gm->user_id = $this->id;
592                 $gm->insert();
593             }
594             
595         }
596         
597         // ------ STANDARD PERMISSION HANDLING.
598         $isOwner = $this->company()->comptype == 'OWNER';
599         $g = DB_DataObject::Factory('group_members');
600         $grps = $g->listGroupMembership($this);
601        //var_dump($grps);
602         $isAdmin = $g->inAdmin;
603         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
604         // the load all the perms for those groups, and add them all together..
605         // then load all those 
606         $g = DB_DataObject::Factory('group_rights');
607         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
608         //echo '<PRE>';print_r($ret);
609         return $ret;
610          
611         
612     }
613     /**
614      *Basic group fetching - probably needs to filter by type eventually.
615      *
616      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
617      */
618     
619     function groups($what=false)
620     {
621         $g = DB_DataObject::Factory('group_members');
622         $grps = $g->listGroupMembership($this);
623         $g = DB_DataObject::Factory('Groups');
624         $g->whereAddIn('id', $grps, 'int');
625         return $g->fetchAll($what);
626         
627     }
628     
629     
630     
631     function hasPerm($name, $lvl) 
632     {
633         static $pcache = array();
634         
635         if (!isset($pcache[$this->id])) {
636             $pcache[$this->id] = $this->getPerms();
637         }
638        // echo "<PRE>";print_r($pcache[$au->id]);
639        // var_dump($pcache[$au->id]);
640         if (empty($pcache[$this->id][$name])) {
641             return false;
642         }
643         
644         return strpos($pcache[$this->id][$name], $lvl) > -1;
645         
646     }    
647     
648     //  ------------ROO HOOKS------------------------------------
649     function applyFilters($q, $au, $roo)
650     {
651         //DB_DataObject::DebugLevel(1);
652         if (!empty($q['query']['person_not_internal'])) {
653             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
654         }
655         
656         
657         if (!empty($q['query']['person_internal_only_all'])) {
658             
659             
660             // must be internal and not current user (need for distribution list)
661             // user has a projectdirectory entry and role is not blank.
662             //DB_DataObject::DebugLevel(1);
663             $pd = DB_DataObject::factory('ProjectDirectory');
664             $pd->whereAdd("role != ''");
665             $pd->selectAdd();
666             $pd->selectAdd('distinct(person_id) as person_id');
667             $roled = $pd->fetchAll('person_id');
668             $rs = $roled  ? "  OR
669                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
670                     " : '';
671             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
672             
673         }
674         // -- for distribution
675         if (!empty($q['query']['person_internal_only'])) {
676             // must be internal and not current user (need for distribution list)
677             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
678             
679             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
680             //    ".id  != ".$au->id);
681             $this->whereAdd("Person.id != {$au->id}");
682         } 
683         
684         if (!empty($q['query']['comptype_or_company_id'])) {
685            // DB_DataObject::debugLevel(1);
686             $bits = explode(',', $q['query']['comptype_or_company_id']);
687             $id = (int) array_pop($bits);
688             $ct = $this->escape($bits[0]);
689             
690             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
691             
692         }
693         
694         
695         // staff list..
696         if (!empty($q['query']['person_inactive'])) {
697            // DB_Dataobject::debugLevel(1);
698             $this->active = 1;
699         }
700         $tn_p = $this->tableName();
701         $tn_gm = DB_DataObject::Factory('group_members')->tableName();
702         $tn_g = DB_DataObject::Factory('Groups')->tableName();
703
704         ///---------------- Group views --------
705         if (!empty($q['query']['in_group'])) {
706             // DB_DataObject::debugLevel(1);
707             $ing = (int) $q['query']['in_group'];
708             if ($q['query']['in_group'] == -1) {
709              
710                 // list all staff who are not in a group.
711                 $this->whereAdd("Person.id NOT IN (
712                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
713                         $tn_g ON $tn_g.id = $tn_gm.group_id
714                         WHERE $tn_g.type = ".$q['query']['type']."
715                     )");
716                 
717                 
718             } else {
719                 
720                 $this->whereAdd("$tn_p.id IN (
721                     SELECT distinct(user_id) FROM $tn_gm
722                         WHERE group_id = $ing
723                     )");
724                }
725             
726         }
727         
728         if (!empty($q['query']['not_in_directory'])) { 
729             // it's a Person list..
730             // DB_DATaobjecT::debugLevel(1);
731             
732             // specific to project directory which is single comp. login
733             //
734             $owncomp = DB_DataObject::Factory('Companies');
735             $owncomp->get('comptype', 'OWNER');
736             if ($q['company_id'] == $owncomp->id) {
737                 $this->active =1;
738             }
739             
740             
741
742             if ( $q['query']['not_in_directory'] > -1) {
743                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
744                 // can list current - so that it does not break!!!
745                 $this->whereAdd("$tn_p.id NOT IN 
746                     ( SELECT distinct person_id FROM $tn_pd WHERE
747                         project_id = " . $q['query']['not_in_directory'] . " AND 
748                         company_id = " . $this->company_id . ')');
749             }
750         }
751            
752         if (!empty($q['query']['role'])) { 
753             // it's a Person list..
754             // DB_DATaobjecT::debugLevel(1);
755             
756             // specific to project directory which is single comp. login
757             //
758             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
759                 // can list current - so that it does not break!!!
760             $this->whereAdd("$tn_p.id IN 
761                     ( SELECT distinct person_id FROM $tn_pd WHERE
762                         role = '". $this->escape($q['query']['role']) ."'
763             )");
764         
765         }
766         
767         
768         if (!empty($q['query']['project_member_of'])) {
769                // this is also a flag to return if they are a member..
770             //DB_DataObject::debugLevel(1);
771             $do = DB_DataObject::factory('ProjectDirectory');
772             $do->project_id = $q['query']['project_member_of'];
773             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
774             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
775             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
776                 
777                 
778             if (!empty($q['query']['project_member_filter'])) {
779                 $this->having('is_member !=0');
780             
781             }
782             
783         }
784         
785         if (!empty($q['query']['search'])) {
786             
787             // use our magic search builder...
788             
789              require_once 'Text/SearchParser.php';
790             $x = new Text_SearchParser($q['query']['search']);
791             
792             $props = array(
793                     "$tn_p.name",
794                     "$tn_p.email",
795                     "$tn_p.role",
796                     "$tn_p.phone",
797                     "$tn_p.remarks",
798                     "join_company_id_id.name"
799             );
800             
801             $str =  $x->toSQL(array(
802                 'default' => $props,
803                 'map' => array(
804                     'company' => 'join_company_id_id.name',
805                     //'country' => 'Clipping.country',
806                     //  'media' => 'Clipping.media_name',
807                 ),
808                 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
809
810             ));
811             
812             
813             $this->whereAdd($str); /*
814                         $tn_p.name LIKE '%$s%'  OR
815                         $tn_p.email LIKE '%$s%'  OR
816                         $tn_p.role LIKE '%$s%'  OR
817                         $tn_p.phone LIKE '%$s%' OR
818                         $tn_p.remarks LIKE '%$s%' 
819                         
820                     ");*/
821         }
822         
823         //
824     }
825     function setFromRoo($ar, $roo)
826     {
827         $this->setFrom($ar);
828         if (!empty($ar['passwd1'])) {
829             $this->setPassword($ar['passwd1']);
830         }
831         
832         
833         if (    $this->id &&
834                 ($this->email == $roo->old->email)&&
835                 ($this->company_id == $roo->old->company_id)
836             ) {
837             return true;
838         }
839         if (empty($this->email)) {
840             return true;
841         }
842         $xx = DB_Dataobject::factory('Person');
843         $xx->setFrom(array(
844             'email' => $this->email,
845            // 'company_id' => $x->company_id
846         ));
847         
848         if ($xx->count()) {
849             return "Duplicate Email found";
850         }
851         return true;
852     }
853     /**
854      *
855      * before Delete - delete significant dependancies..
856      * this is called after checkPerm..
857      */
858     
859     function beforeDelete()
860     {
861         
862         $e = DB_DataObject::Factory('Events');
863         $e->whereAdd('person_id = ' . $this->id);
864         $e->delete(true);
865         
866         // anything else?  
867         
868     }
869     
870     
871     /***
872      * Check if the a user has access to modify this item.
873      * @param String $lvl Level (eg. Core.Projects)
874      * @param Pman_Core_DataObjects_Person $au The authenticated user.
875      * @param boolean $changes alllow changes???
876      *
877      * @return false if no access..
878      */
879     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
880     {
881          
882        // do we have an empty system..
883         if ($au && $au->id == -1) {
884             return true;
885         }
886         
887         // determine if it's staff!!!
888          
889         if ($au->company()->comptype != 'OWNER') {
890             
891             // - can not change company!!!
892             if ($changes && 
893                 isset($changes['company_id']) && 
894                 $changes['company_id'] != $au->company_id) {
895                 return false;
896             }
897             // can only set new emails..
898             if ($changes && 
899                     !empty($this->email) && 
900                     isset($changes['email']) && 
901                     $changes['email'] != $this->email) {
902                 return false;
903             }
904             
905             // edit self... - what about other staff members...
906             
907             return $this->company_id == $au->company_id;
908         }
909          
910          
911         // yes, only owner company can mess with this...
912         $owncomp = DB_DataObject::Factory('Companies');
913         $owncomp->get('comptype', 'OWNER');
914         
915         $isStaff = ($this->company_id ==  $owncomp->id);
916         
917     
918         switch ($lvl) {
919             // extra case change passwod?
920             case 'P': //??? password
921                 // standard perms -- for editing + if the user is dowing them selves..
922                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
923                 return $ret || $au->id == $this->id;
924             
925             default:                
926                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
927         
928         }
929         return false;
930     }
931     function onInsert($req, $roo)  
932     {
933          
934         $p = DB_DataObject::factory('person');
935         if ($roo->authUser->id < 0 && $p->count() == 1) {
936             // this seems a bit risky...
937             
938             $g = DB_DataObject::factory('Groups');
939             $g->initGroups();
940             
941             $g->type = 0;
942             $g->get('name', 'Administrators');
943             
944             $p = DB_DataObject::factory('group_members');
945             $p->group_id = $g->id;
946             $p->user_id = $this->id;     
947             if (!$p->count()) {
948                 $p->insert();
949                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
950             }
951             $this->login();
952         }
953         if (!empty($req['project_id_addto'])) {
954             $pd = DB_DataObject::factory('ProjectDirectory');
955             $pd->project_id = $req['project_id_addto'];
956             $pd->person_id = $this->id; 
957             $pd->ispm =0;
958             $pd->office_id = $this->office_id;
959             $pd->company_id = $this->company_id;
960             $pd->insert();
961         }
962         
963     }
964     
965     function importFromArray($roo, $persons, $opts)
966     {
967         if (empty($opts['prefix'])) {
968             $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
969         }
970         
971         if (!is_array($persons) || empty($persons)) {
972             $roo->jerr("error in the person data. - empty on not valid");
973         }
974         DB_DataObject::factory('groups')->initGroups();
975         
976         foreach($persons as $person){
977             $p = DB_DataObject::factory('person');
978             if($p->get('name', $person['name'])){
979                 continue;
980             }
981             $p->setFrom($person);
982             
983             $companies = DB_DataObject::factory('companies');
984             if(!$companies->get('comptype', 'OWNER')){
985                 $roo->jerr("Missing OWNER companies!");
986             }
987             $p->company_id = $companies->pid();
988             // strip the 'spaces etc.. make lowercase..
989             $name = strtolower(str_replace(' ', '', $person['name']));
990             $p->setPassword("{$opts['prefix']}{$name}");
991             $p->insert();
992             // set up groups
993             // if $person->groups is set.. then
994             // add this person to that group eg. groups : [ 'Administrator' ] 
995             if(!empty($person['groups'])){
996                 $groups = DB_DataObject::factory('groups');
997                 if(!$groups->get('name', $person['groups'])){
998                     $roo->jerr("Missing groups : {$person['groups']}");
999                 }
1000                 $gm = DB_DataObject::factory('group_members');
1001                 $gm->change($p, $groups, true);
1002             }
1003             
1004             $p->onInsert(array(), $roo);
1005         }
1006     }
1007  }