3 * Table Definition for Person
5 require_once 'DB/DataObject.php';
7 class Pman_Core_DataObjects_Person extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'Person'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
14 public $email; // string(128) not_null
16 public $company_id; // int(11)
17 public $office_id; // int(11)
19 public $name; // string(128) not_null
20 public $firstname; // string(128) not_null
21 public $lastname; // string(128) not_null
22 public $phone; // string(32) not_null
23 public $fax; // string(32) not_null
25 public $role; // string(32) not_null
26 public $remarks; // blob(65535) not_null blob
27 public $passwd; // string(64) not_null
28 public $owner_id; // int(11) not_null
29 public $lang; // string(8)
30 public $no_reset_sent; // int(11)
31 public $action_type; // string(32)
32 public $project_id; // int(11)
35 public $active; // int(11) not_null
36 public $deleted_by; // int(11) not_null
37 public $deleted_dt; // datetime(19) binary
40 /* the code above is auto generated do not remove the tag below */
45 $p = DB_DataObject::Factory('Person');
46 $p->get($this->owner_id);
55 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
61 function buildMail($templateFile, $args)
64 $args = (array) $args;
65 $content = clone($this);
67 foreach((array)$args as $k=>$v) {
71 $ff = HTML_FlexyFramework::get();
74 //?? is this really the place for this???
77 empty($args['no_auth']) &&
78 !in_array($templateFile, array(
79 // templates that can be sent without authentication.
85 $content->authUser = $this->getAuthUser();
86 if (!$content->authUser) {
87 return PEAR::raiseError("Not authenticated");
91 // should handle x-forwarded...
93 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
94 $_SERVER["HTTP_HOST"] :
95 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
97 /* use the regex compiler, as it doesnt parse <tags */
100 'compiler' => 'Flexy',
102 'filters' => array('SimpleTags','Mail'),
108 if (!empty($args['templateDir'])) {
109 $tops['templateDir'] = $args['templateDir'];
114 require_once 'HTML/Template/Flexy.php';
115 $template = new HTML_Template_Flexy( $tops );
116 $template->compile("mail/$templateFile.txt");
118 /* use variables from this object to ouput data. */
119 $mailtext = $template->bufferedOutputObject($content);
122 // if a html file with the same name exists, use that as the body
123 // I've no idea where this code went, it was here before..
124 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
125 $tops['nonHTML'] = false;
126 $template = new HTML_Template_Flexy( $tops );
127 $template->compile("mail/$templateFile.html");
128 $htmlbody = $template->bufferedOutputObject($content);
134 //echo "<PRE>";print_R($mailtext);
135 //print_R($mailtext);exit;
136 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
137 require_once 'Mail/mimeDecode.php';
138 require_once 'Mail.php';
140 $decoder = new Mail_mimeDecode($mailtext);
141 $parts = $decoder->getSendArray();
143 if (PEAR::isError($parts)) {
145 //echo "PROBLEM: {$parts->message}";
148 list($recipents,$headers,$body) = $parts;
149 $recipents = array($this->email);
150 if (!empty($content->bcc) && is_array($content->bcc)) {
151 $recipents =array_merge($recipents, $content->bcc);
153 $headers['Date'] = date('r');
155 if ($htmlbody !== false) {
156 require_once 'Mail/mime.php';
157 $mime = new Mail_mime(array('eol' => "\n"));
158 $mime->setTXTBody($body);
159 $mime->setHTMLBody($htmlbody);
160 // I think there might be code in mediaoutreach toEmail somewhere
161 // h embeds images here..
162 $body = $mime->get();
163 $headers = $mime->headers($headers);
170 'recipients' => $recipents,
171 'headers' => $headers,
181 * - user must be authenticate or args[no_auth] = true
182 * or template = password_[reset|welcome]
185 function sendTemplate($templateFile, $args)
188 $ar = $this->buildMail($templateFile, $args);
191 //print_r($recipents);exit;
192 $mailOptions = PEAR::getStaticProperty('Mail','options');
193 $mail = Mail::factory("SMTP",$mailOptions);
195 if (PEAR::isError($mail)) {
198 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
199 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
200 error_reporting($oe);
209 function getEmailFrom()
211 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
213 function toEventString()
215 return empty($this->name) ? $this->email : $this->name;
217 function verifyAuth()
219 $ff= HTML_FlexyFramework::get();
220 if (!empty($ff->Pman['auth_comptype']) && $ff->Pman['auth_comptype'] != $this->company()->comptype) {
221 $ff->page->jerr("Login not permited to outside companies");
228 // ---------------- authentication / passwords and keys stuff ----------------
231 $db = $this->getDatabaseConnection();
232 // we combine db + project names,
233 // otherwise if projects use different 'auth' objects
234 // then we get unserialize issues.
235 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
239 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
241 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
243 $u = DB_DataObject::factory('Person');
244 if ($u->get($a->id)) { //&& strlen($u->passwd)) {
250 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
254 $u = DB_DataObject::factory('Person');
255 $ff = HTML_FlexyFramework::get();
256 if (!empty($ff->Pman['local_autoauth']) &&
257 (!empty($_SERVER['SERVER_ADDR'])) &&
258 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
259 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
260 $u->get('email', $ff->Pman['local_autoauth'])
262 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
267 $u = DB_DataObject::factory('Person');
269 if (!empty($_SERVER['PHP_AUTH_USER'])
271 !empty($_SERVER['PHP_AUTH_PW'])
273 $u->get('email', $_SERVER['PHP_AUTH_USER'])
275 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
277 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
281 if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
285 // not in session or not matched...
286 $u = DB_DataObject::factory('Person');
287 $u->whereAdd(' LENGTH(passwd) > 0');
289 $_SESSION[__CLASS__][$sesPrefix .'-empty'] = $n;
290 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
292 die($error->toString()); // not really a good thing to do...
294 if (!$n){ // authenticated as there are no users in the system...
301 function getAuthUser()
303 if (!$this->isAuth()) {
306 $db = $this->getDatabaseConnection();
307 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
309 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
310 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
312 $u = DB_DataObject::factory('Person');
313 if ($u->get($a->id)) { /// && strlen($u->passwd)) {
319 if (empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
320 $u = DB_DataObject::factory('Person');
321 $u->whereAdd(' LENGTH(passwd) > 0');
322 $_SESSION[__CLASS__][$sesPrefix .'-empty'] = $u->count();
326 if (empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
328 // fake person - open system..
329 //$ce = DB_DataObject::factory('core_enum');
333 $u = DB_DataObject::factory('Person');
342 $this->isAuth(); // force session start..
344 $db = $this->getDatabaseConnection();
345 // refresh admin group if we are logged in as one..
346 //DB_DataObject::debugLevel(1);
347 $g = DB_DataObject::factory('Groups');
349 $g->get('name', 'Administrators');
350 $gm = DB_DataObject::Factory('group_members');
351 if (in_array($g->id,$gm->listGroupMembership($this))) {
352 // refresh admin groups.
353 $gr = DB_DataObject::Factory('group_rights');
354 $gr->applyDefs($g, 0);
357 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
358 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
363 $this->isAuth(); // force session start..
364 $db = $this->getDatabaseConnection();
365 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
366 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
369 function genPassKey ($t)
371 return md5($this->email . $t. $this->passwd);
373 function simpleAuthKey($m = 0)
375 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
377 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
379 function checkPassword($val)
382 if (substr($this->passwd,0,1) == '$') {
383 return crypt($val,$this->passwd) == $this->passwd ;
385 // old style md5 passwords...- cant be used with courier....
386 return md5($val) == $this->passwd;
388 function setPassword($value)
391 while(strlen($salt)<9) {
392 $salt.=chr(rand(64,126));
393 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
395 $this->passwd = crypt($value, '$1$'. $salt. '$');
400 function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
402 require_once 'Text/Password.php';
403 $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
404 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
405 $this->setPassword($this->rawPasswd);
406 return $this->rawPasswd;
411 $x = DB_DataObject::factory('Companies');
412 $x->get($this->company_id);
415 function loadCompany()
417 $this->company = $this->company();
422 return $this->active;
424 function authUserName($n) // set username prior to acheck user exists query.
427 $this->whereAdd('LENGTH(passwd) > 1');
432 if ($val == $this->lang) {
442 function authUserArray()
445 $aur = $this->toArray();
452 //DB_DataObject::debugLevel(1);
453 $c = DB_Dataobject::factory('Companies');
454 $im = DB_Dataobject::factory('Images');
455 $c->joinAdd($im, 'LEFT');
457 $c->selectAs($c, 'company_id_%s');
458 $c->selectAs($im, 'company_id_logo_id_%s');
459 $c->id = $this->company_id;
463 $aur = array_merge( $c->toArray(),$aur);
465 if (empty($c->company_id_logo_id_id)) {
467 $im = DB_Dataobject::factory('Images');
468 $im->ontable = 'Companies';
470 $im->imgtype = 'LOGO';
473 $im->selectAs($im, 'company_id_logo_id_%s');
474 if ($im->find(true)) {
476 foreach($im->toArray() as $k=>$v) {
483 $aur['perms'] = $this->getPerms();
484 $g = DB_DataObject::Factory('group_members');
485 $aur['groups'] = $g->listGroupMembership($this, 'name');
488 $aur['dailykey'] = '';
495 // ----------PERMS------ ----------------
498 //DB_DataObject::debugLevel(1);
499 // find out all the groups they are a member of.. + Default..
501 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
503 $g = DB_DataObject::Factory('group_rights');
509 return $g->adminRights(); // system is not set up - so they get full rights.
511 //DB_DataObject::debugLevel(1);
512 $g = DB_DataObject::Factory('group_members');
513 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
515 // add the current user to the admin group..
516 $g = DB_DataObject::Factory('Groups');
517 if ($g->get('name', 'Administrators')) {
518 $gm = DB_DataObject::Factory('group_members');
519 $gm->group_id = $g->id;
520 $gm->user_id = $this->id;
526 // ------ STANDARD PERMISSION HANDLING.
527 $isOwner = $this->company()->comptype == 'OWNER';
528 $g = DB_DataObject::Factory('group_members');
529 $grps = $g->listGroupMembership($this);
531 $isAdmin = $g->inAdmin;
532 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
533 // the load all the perms for those groups, and add them all together..
534 // then load all those
535 $g = DB_DataObject::Factory('group_rights');
536 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
537 //echo '<PRE>';print_r($ret);
543 *Basic group fetching - probably needs to filter by type eventually.
545 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
548 function groups($what=false)
550 $g = DB_DataObject::Factory('group_members');
551 $grps = $g->listGroupMembership($this);
552 $g = DB_DataObject::Factory('Groups');
553 $g->whereAddIn('id', $grps, 'int');
554 return $g->fetchAll($what);
560 function hasPerm($name, $lvl)
562 static $pcache = array();
564 if (!isset($pcache[$this->id])) {
565 $pcache[$this->id] = $this->getPerms();
567 // echo "<PRE>";print_r($pcache[$au->id]);
568 // var_dump($pcache[$au->id]);
569 if (empty($pcache[$this->id][$name])) {
573 return strpos($pcache[$this->id][$name], $lvl) > -1;
577 // ------------ROO HOOKS------------------------------------
578 function applyFilters($q, $au, $roo)
580 //DB_DataObject::DebugLevel(1);
581 if (!empty($q['query']['person_not_internal'])) {
582 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
586 if (!empty($q['query']['person_internal_only_all'])) {
589 // must be internal and not current user (need for distribution list)
590 // user has a projectdirectory entry and role is not blank.
591 //DB_DataObject::DebugLevel(1);
592 $pd = DB_DataObject::factory('ProjectDirectory');
593 $pd->whereAdd("role != ''");
595 $pd->selectAdd('distinct(person_id) as person_id');
596 $roled = $pd->fetchAll('person_id');
598 {$this->tableName()}.id IN (".implode(',', $roled) . ")
600 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
603 // -- for distribution
604 if (!empty($q['query']['person_internal_only'])) {
605 // must be internal and not current user (need for distribution list)
606 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
608 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
609 // ".id != ".$au->id);
610 $this->whereAdd("Person.id != {$au->id}");
613 if (!empty($q['query']['comptype_or_company_id'])) {
614 // DB_DataObject::debugLevel(1);
615 $bits = explode(',', $q['query']['comptype_or_company_id']);
616 $id = (int) array_pop($bits);
617 $ct = $this->escape($bits[0]);
619 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
625 if (!empty($q['query']['person_inactive'])) {
626 // DB_Dataobject::debugLevel(1);
629 $tn_p = $this->tableName();
630 $tn_gm = DB_DataObject::Factory('group_members')->tableName();
631 $tn_g = DB_DataObject::Factory('Groups')->tableName();
633 ///---------------- Group views --------
634 if (!empty($q['query']['in_group'])) {
635 // DB_DataObject::debugLevel(1);
636 $ing = (int) $q['query']['in_group'];
637 if ($q['query']['in_group'] == -1) {
639 // list all staff who are not in a group.
640 $this->whereAdd("Person.id NOT IN (
641 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
642 $tn_g ON $tn_g.id = $tn_gm.group_id
643 WHERE $tn_g.type = ".$q['query']['type']."
649 $this->whereAdd("$tn_p.id IN (
650 SELECT distinct(user_id) FROM $tn_gm
651 WHERE group_id = $ing
657 if (!empty($q['query']['not_in_directory'])) {
658 // it's a Person list..
659 // DB_DATaobjecT::debugLevel(1);
661 // specific to project directory which is single comp. login
663 $owncomp = DB_DataObject::Factory('Companies');
664 $owncomp->get('comptype', 'OWNER');
665 if ($q['company_id'] == $owncomp->id) {
671 if ( $q['query']['not_in_directory'] > -1) {
672 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
673 // can list current - so that it does not break!!!
674 $this->whereAdd("$tn_p.id NOT IN
675 ( SELECT distinct person_id FROM $tn_pd WHERE
676 project_id = " . $q['query']['not_in_directory'] . " AND
677 company_id = " . $this->company_id . ')');
681 if (!empty($q['query']['role'])) {
682 // it's a Person list..
683 // DB_DATaobjecT::debugLevel(1);
685 // specific to project directory which is single comp. login
687 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
688 // can list current - so that it does not break!!!
689 $this->whereAdd("$tn_p.id IN
690 ( SELECT distinct person_id FROM $tn_pd WHERE
691 role = '". $this->escape($q['query']['role']) ."'
697 if (!empty($q['query']['project_member_of'])) {
698 // this is also a flag to return if they are a member..
699 //DB_DataObject::debugLevel(1);
700 $do = DB_DataObject::factory('ProjectDirectory');
701 $do->project_id = $q['query']['project_member_of'];
702 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
703 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
704 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
707 if (!empty($q['query']['project_member_filter'])) {
708 $this->having('is_member !=0');
714 if (!empty($q['query']['search'])) {
715 $s = $this->escape($q['query']['search']);
717 $tn_p.name LIKE '%$s%' OR
718 $tn_p.email LIKE '%$s%' OR
719 $tn_p.role LIKE '%$s%' OR
720 $tn_p.phone LIKE '%$s%' OR
721 $tn_p.remarks LIKE '%$s%'
728 function setFromRoo($ar, $roo)
731 if (!empty($ar['passwd1'])) {
732 $this->setPassword($ar['passwd1']);
737 ($this->email == $roo->old->email)&&
738 ($this->company_id == $roo->old->company_id)
742 if (empty($this->email)) {
745 $xx = DB_Dataobject::factory('Person');
747 'email' => $this->email,
748 // 'company_id' => $x->company_id
752 return "Duplicate Email found";
758 * before Delete - delete significant dependancies..
759 * this is called after checkPerm..
762 function beforeDelete()
765 $e = DB_DataObject::Factory('Events');
766 $e->whereAdd('person_id = ' . $this->id);
775 * Check if the a user has access to modify this item.
776 * @param String $lvl Level (eg. Core.Projects)
777 * @param Pman_Core_DataObjects_Person $au The authenticated user.
778 * @param boolean $changes alllow changes???
780 * @return false if no access..
782 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
785 // do we have an empty system..
786 if ($au && $au->id == -1) {
790 // determine if it's staff!!!
792 if ($au->company()->comptype != 'OWNER') {
794 // - can not change company!!!
796 isset($changes['company_id']) &&
797 $changes['company_id'] != $au->company_id) {
800 // can only set new emails..
802 !empty($this->email) &&
803 isset($changes['email']) &&
804 $changes['email'] != $this->email) {
808 // edit self... - what about other staff members...
810 return $this->company_id == $au->company_id;
814 // yes, only owner company can mess with this...
815 $owncomp = DB_DataObject::Factory('Companies');
816 $owncomp->get('comptype', 'OWNER');
818 $isStaff = ($this->company_id == $owncomp->id);
822 // extra case change passwod?
823 case 'P': //??? password
824 // standard perms -- for editing + if the user is dowing them selves..
825 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
826 return $ret || $au->id == $this->id;
829 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
834 function onInsert($req, $roo)
837 $p = DB_DataObject::factory('person');
838 if ($roo->authUser->id < 0 && $p->count() == 1) {
839 // this seems a bit risky...
841 $g = DB_DataObject::factory('Groups');
845 $g->get('name', 'Administrators');
847 $p = DB_DataObject::factory('group_members');
848 $p->group_id = $g->id;
849 $p->user_id = $this->id;
852 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
856 if (!empty($req['project_id_addto'])) {
857 $pd = DB_DataObject::factory('ProjectDirectory');
858 $pd->project_id = $req['project_id_addto'];
859 $pd->person_id = $this->id;
861 $pd->office_id = $this->office_id;
862 $pd->company_id = $this->company_id;