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