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
17 public $company_id; // int(11)
18 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 public $name_facebook; // VARCHAR(128) NULL;
41 public $url_blog; // VARCHAR(256) NULL ;
42 public $url_twitter; // VARCHAR(256) NULL ;
43 public $url_linkedin; // VARCHAR(256) NULL ;
45 public $phone_mobile; // varchar(32) NOT NULL DEFAULT '';
46 public $phone_direct; // varchar(32) NOT NULL DEFAULT '';
48 /* the code above is auto generated do not remove the tag below */
53 $p = DB_DataObject::Factory('Person');
54 $p->get($this->owner_id);
63 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
69 function buildMail($templateFile, $args)
72 $args = (array) $args;
73 $content = clone($this);
75 foreach((array)$args as $k=>$v) {
79 $ff = HTML_FlexyFramework::get();
82 //?? is this really the place for this???
85 empty($args['no_auth']) &&
86 !in_array($templateFile, array(
87 // templates that can be sent without authentication.
93 $content->authUser = $this->getAuthUser();
94 if (!$content->authUser) {
95 return PEAR::raiseError("Not authenticated");
99 // should handle x-forwarded...
101 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
102 $_SERVER["HTTP_HOST"] :
103 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
105 /* use the regex compiler, as it doesnt parse <tags */
108 'compiler' => 'Flexy',
110 'filters' => array('SimpleTags','Mail'),
116 if (!empty($args['templateDir'])) {
117 $tops['templateDir'] = $args['templateDir'];
122 require_once 'HTML/Template/Flexy.php';
123 $template = new HTML_Template_Flexy( $tops );
124 $template->compile("mail/$templateFile.txt");
126 /* use variables from this object to ouput data. */
127 $mailtext = $template->bufferedOutputObject($content);
130 // if a html file with the same name exists, use that as the body
131 // I've no idea where this code went, it was here before..
132 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
133 $tops['nonHTML'] = false;
134 $template = new HTML_Template_Flexy( $tops );
135 $template->compile("mail/$templateFile.html");
136 $htmlbody = $template->bufferedOutputObject($content);
142 //echo "<PRE>";print_R($mailtext);
143 //print_R($mailtext);exit;
144 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
145 require_once 'Mail/mimeDecode.php';
146 require_once 'Mail.php';
148 $decoder = new Mail_mimeDecode($mailtext);
149 $parts = $decoder->getSendArray();
151 if (PEAR::isError($parts)) {
153 //echo "PROBLEM: {$parts->message}";
156 list($recipents,$headers,$body) = $parts;
157 $recipents = array($this->email);
158 if (!empty($content->bcc) && is_array($content->bcc)) {
159 $recipents =array_merge($recipents, $content->bcc);
161 $headers['Date'] = date('r');
163 if ($htmlbody !== false) {
164 require_once 'Mail/mime.php';
165 $mime = new Mail_mime(array('eol' => "\n"));
166 $mime->setTXTBody($body);
167 $mime->setHTMLBody($htmlbody);
168 // I think there might be code in mediaoutreach toEmail somewhere
169 // h embeds images here..
170 $body = $mime->get();
171 $headers = $mime->headers($headers);
178 'recipients' => $recipents,
179 'headers' => $headers,
189 * - user must be authenticate or args[no_auth] = true
190 * or template = password_[reset|welcome]
193 function sendTemplate($templateFile, $args)
196 $ar = $this->buildMail($templateFile, $args);
199 //print_r($recipents);exit;
200 $mailOptions = PEAR::getStaticProperty('Mail','options');
201 $mail = Mail::factory("SMTP",$mailOptions);
203 if (PEAR::isError($mail)) {
206 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
207 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
208 error_reporting($oe);
217 function getEmailFrom()
219 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
221 function toEventString()
223 return empty($this->name) ? $this->email : $this->name;
225 function verifyAuth()
227 $ff= HTML_FlexyFramework::get();
228 if (!empty($ff->Pman['auth_comptype']) &&
229 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
231 $ff->page->jerr("Login not permited to outside companies");
238 // ---------------- authentication / passwords and keys stuff ----------------
241 $db = $this->getDatabaseConnection();
242 // we combine db + project names,
243 // otherwise if projects use different 'auth' objects
244 // then we get unserialize issues.
245 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
250 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
252 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
254 $u = DB_DataObject::factory('Person');
255 if ($u->get($a->id)) { //&& strlen($u->passwd)) {
262 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
266 $u = DB_DataObject::factory('Person');
267 $ff = HTML_FlexyFramework::get();
268 if (!empty($ff->Pman['local_autoauth']) &&
269 (!empty($_SERVER['SERVER_ADDR'])) &&
270 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
271 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
272 $u->get('email', $ff->Pman['local_autoauth'])
274 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
279 $u = DB_DataObject::factory('Person');
281 if (!empty($_SERVER['PHP_AUTH_USER'])
283 !empty($_SERVER['PHP_AUTH_PW'])
285 $u->get('email', $_SERVER['PHP_AUTH_USER'])
287 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
289 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
293 if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
297 // not in session or not matched...
298 $u = DB_DataObject::factory('Person');
299 $u->whereAdd(' LENGTH(passwd) > 0');
301 $_SESSION[__CLASS__][$sesPrefix .'-empty'] = $n;
302 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
304 die($error->toString()); // not really a good thing to do...
306 if (!$n){ // authenticated as there are no users in the system...
313 function getAuthUser()
315 if (!$this->isAuth()) {
318 $db = $this->getDatabaseConnection();
319 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
323 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
324 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
326 $u = DB_DataObject::factory('Person');
327 if ($u->get($a->id)) { /// && strlen($u->passwd)) {
333 if (empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
334 $u = DB_DataObject::factory('Person');
335 $u->whereAdd(' LENGTH(passwd) > 0');
336 $_SESSION[__CLASS__][$sesPrefix .'-empty'] = $u->count();
340 if (empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
342 // fake person - open system..
343 //$ce = DB_DataObject::factory('core_enum');
347 $u = DB_DataObject::factory('Person');
356 $this->isAuth(); // force session start..
358 $db = $this->getDatabaseConnection();
361 // open up iptables at login..
362 $dbname = $this->database();
363 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
365 // refresh admin group if we are logged in as one..
366 //DB_DataObject::debugLevel(1);
367 $g = DB_DataObject::factory('Groups');
369 $g->get('name', 'Administrators');
370 $gm = DB_DataObject::Factory('group_members');
371 if (in_array($g->id,$gm->listGroupMembership($this))) {
372 // refresh admin groups.
373 $gr = DB_DataObject::Factory('group_rights');
374 $gr->applyDefs($g, 0);
377 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
378 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
383 $this->isAuth(); // force session start..
384 $db = $this->getDatabaseConnection();
385 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
386 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
389 function genPassKey ($t)
391 return md5($this->email . $t. $this->passwd);
393 function simpleAuthKey($m = 0)
395 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
397 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
399 function checkPassword($val)
402 if (substr($this->passwd,0,1) == '$') {
403 return crypt($val,$this->passwd) == $this->passwd ;
405 // old style md5 passwords...- cant be used with courier....
406 return md5($val) == $this->passwd;
408 function setPassword($value)
411 while(strlen($salt)<9) {
412 $salt.=chr(rand(64,126));
413 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
415 $this->passwd = crypt($value, '$1$'. $salt. '$');
420 function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
422 require_once 'Text/Password.php';
423 $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
424 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
425 $this->setPassword($this->rawPasswd);
426 return $this->rawPasswd;
431 $x = DB_DataObject::factory('Companies');
433 $x->get($this->company_id);
436 function loadCompany()
438 $this->company = $this->company();
443 return $this->active;
445 function authUserName($n) // set username prior to acheck user exists query.
448 $this->whereAdd('LENGTH(passwd) > 1');
453 if ($val == $this->lang) {
463 function authUserArray()
466 $aur = $this->toArray();
473 //DB_DataObject::debugLevel(1);
474 $c = DB_Dataobject::factory('Companies');
475 $im = DB_Dataobject::factory('Images');
476 $c->joinAdd($im, 'LEFT');
478 $c->selectAs($c, 'company_id_%s');
479 $c->selectAs($im, 'company_id_logo_id_%s');
480 $c->id = $this->company_id;
484 $aur = array_merge( $c->toArray(),$aur);
486 if (empty($c->company_id_logo_id_id)) {
488 $im = DB_Dataobject::factory('Images');
489 $im->ontable = 'Companies';
491 $im->imgtype = 'LOGO';
494 $im->selectAs($im, 'company_id_logo_id_%s');
495 if ($im->find(true)) {
497 foreach($im->toArray() as $k=>$v) {
504 $aur['perms'] = $this->getPerms();
505 $g = DB_DataObject::Factory('group_members');
506 $aur['groups'] = $g->listGroupMembership($this, 'name');
509 $aur['dailykey'] = '';
516 // ----------PERMS------ ----------------
519 //DB_DataObject::debugLevel(1);
520 // find out all the groups they are a member of.. + Default..
522 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
524 $g = DB_DataObject::Factory('group_rights');
530 return $g->adminRights(); // system is not set up - so they get full rights.
532 //DB_DataObject::debugLevel(1);
533 $g = DB_DataObject::Factory('group_members');
534 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
536 // add the current user to the admin group..
537 $g = DB_DataObject::Factory('Groups');
538 if ($g->get('name', 'Administrators')) {
539 $gm = DB_DataObject::Factory('group_members');
540 $gm->group_id = $g->id;
541 $gm->user_id = $this->id;
547 // ------ STANDARD PERMISSION HANDLING.
548 $isOwner = $this->company()->comptype == 'OWNER';
549 $g = DB_DataObject::Factory('group_members');
550 $grps = $g->listGroupMembership($this);
552 $isAdmin = $g->inAdmin;
553 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
554 // the load all the perms for those groups, and add them all together..
555 // then load all those
556 $g = DB_DataObject::Factory('group_rights');
557 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
558 //echo '<PRE>';print_r($ret);
564 *Basic group fetching - probably needs to filter by type eventually.
566 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
569 function groups($what=false)
571 $g = DB_DataObject::Factory('group_members');
572 $grps = $g->listGroupMembership($this);
573 $g = DB_DataObject::Factory('Groups');
574 $g->whereAddIn('id', $grps, 'int');
575 return $g->fetchAll($what);
581 function hasPerm($name, $lvl)
583 static $pcache = array();
585 if (!isset($pcache[$this->id])) {
586 $pcache[$this->id] = $this->getPerms();
588 // echo "<PRE>";print_r($pcache[$au->id]);
589 // var_dump($pcache[$au->id]);
590 if (empty($pcache[$this->id][$name])) {
594 return strpos($pcache[$this->id][$name], $lvl) > -1;
598 // ------------ROO HOOKS------------------------------------
599 function applyFilters($q, $au, $roo)
601 //DB_DataObject::DebugLevel(1);
602 if (!empty($q['query']['person_not_internal'])) {
603 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
607 if (!empty($q['query']['person_internal_only_all'])) {
610 // must be internal and not current user (need for distribution list)
611 // user has a projectdirectory entry and role is not blank.
612 //DB_DataObject::DebugLevel(1);
613 $pd = DB_DataObject::factory('ProjectDirectory');
614 $pd->whereAdd("role != ''");
616 $pd->selectAdd('distinct(person_id) as person_id');
617 $roled = $pd->fetchAll('person_id');
619 {$this->tableName()}.id IN (".implode(',', $roled) . ")
621 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
624 // -- for distribution
625 if (!empty($q['query']['person_internal_only'])) {
626 // must be internal and not current user (need for distribution list)
627 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
629 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
630 // ".id != ".$au->id);
631 $this->whereAdd("Person.id != {$au->id}");
634 if (!empty($q['query']['comptype_or_company_id'])) {
635 // DB_DataObject::debugLevel(1);
636 $bits = explode(',', $q['query']['comptype_or_company_id']);
637 $id = (int) array_pop($bits);
638 $ct = $this->escape($bits[0]);
640 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
646 if (!empty($q['query']['person_inactive'])) {
647 // DB_Dataobject::debugLevel(1);
650 $tn_p = $this->tableName();
651 $tn_gm = DB_DataObject::Factory('group_members')->tableName();
652 $tn_g = DB_DataObject::Factory('Groups')->tableName();
654 ///---------------- Group views --------
655 if (!empty($q['query']['in_group'])) {
656 // DB_DataObject::debugLevel(1);
657 $ing = (int) $q['query']['in_group'];
658 if ($q['query']['in_group'] == -1) {
660 // list all staff who are not in a group.
661 $this->whereAdd("Person.id NOT IN (
662 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
663 $tn_g ON $tn_g.id = $tn_gm.group_id
664 WHERE $tn_g.type = ".$q['query']['type']."
670 $this->whereAdd("$tn_p.id IN (
671 SELECT distinct(user_id) FROM $tn_gm
672 WHERE group_id = $ing
678 if (!empty($q['query']['not_in_directory'])) {
679 // it's a Person list..
680 // DB_DATaobjecT::debugLevel(1);
682 // specific to project directory which is single comp. login
684 $owncomp = DB_DataObject::Factory('Companies');
685 $owncomp->get('comptype', 'OWNER');
686 if ($q['company_id'] == $owncomp->id) {
692 if ( $q['query']['not_in_directory'] > -1) {
693 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
694 // can list current - so that it does not break!!!
695 $this->whereAdd("$tn_p.id NOT IN
696 ( SELECT distinct person_id FROM $tn_pd WHERE
697 project_id = " . $q['query']['not_in_directory'] . " AND
698 company_id = " . $this->company_id . ')');
702 if (!empty($q['query']['role'])) {
703 // it's a Person list..
704 // DB_DATaobjecT::debugLevel(1);
706 // specific to project directory which is single comp. login
708 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
709 // can list current - so that it does not break!!!
710 $this->whereAdd("$tn_p.id IN
711 ( SELECT distinct person_id FROM $tn_pd WHERE
712 role = '". $this->escape($q['query']['role']) ."'
718 if (!empty($q['query']['project_member_of'])) {
719 // this is also a flag to return if they are a member..
720 //DB_DataObject::debugLevel(1);
721 $do = DB_DataObject::factory('ProjectDirectory');
722 $do->project_id = $q['query']['project_member_of'];
723 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
724 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
725 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
728 if (!empty($q['query']['project_member_filter'])) {
729 $this->having('is_member !=0');
735 if (!empty($q['query']['search'])) {
737 // use our magic search builder...
739 require_once 'Text/SearchParser.php';
740 $x = new Text_SearchParser($q['query']['search']);
748 "join_company_id_id.name"
751 $str = $x->toSQL(array(
754 'company' => 'join_company_id_id.name',
755 //'country' => 'Clipping.country',
756 // 'media' => 'Clipping.media_name',
758 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
763 $this->whereAdd($str); /*
764 $tn_p.name LIKE '%$s%' OR
765 $tn_p.email LIKE '%$s%' OR
766 $tn_p.role LIKE '%$s%' OR
767 $tn_p.phone LIKE '%$s%' OR
768 $tn_p.remarks LIKE '%$s%'
775 function setFromRoo($ar, $roo)
778 if (!empty($ar['passwd1'])) {
779 $this->setPassword($ar['passwd1']);
784 ($this->email == $roo->old->email)&&
785 ($this->company_id == $roo->old->company_id)
789 if (empty($this->email)) {
792 $xx = DB_Dataobject::factory('Person');
794 'email' => $this->email,
795 // 'company_id' => $x->company_id
799 return "Duplicate Email found";
805 * before Delete - delete significant dependancies..
806 * this is called after checkPerm..
809 function beforeDelete()
812 $e = DB_DataObject::Factory('Events');
813 $e->whereAdd('person_id = ' . $this->id);
822 * Check if the a user has access to modify this item.
823 * @param String $lvl Level (eg. Core.Projects)
824 * @param Pman_Core_DataObjects_Person $au The authenticated user.
825 * @param boolean $changes alllow changes???
827 * @return false if no access..
829 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
832 // do we have an empty system..
833 if ($au && $au->id == -1) {
837 // determine if it's staff!!!
839 if ($au->company()->comptype != 'OWNER') {
841 // - can not change company!!!
843 isset($changes['company_id']) &&
844 $changes['company_id'] != $au->company_id) {
847 // can only set new emails..
849 !empty($this->email) &&
850 isset($changes['email']) &&
851 $changes['email'] != $this->email) {
855 // edit self... - what about other staff members...
857 return $this->company_id == $au->company_id;
861 // yes, only owner company can mess with this...
862 $owncomp = DB_DataObject::Factory('Companies');
863 $owncomp->get('comptype', 'OWNER');
865 $isStaff = ($this->company_id == $owncomp->id);
869 // extra case change passwod?
870 case 'P': //??? password
871 // standard perms -- for editing + if the user is dowing them selves..
872 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
873 return $ret || $au->id == $this->id;
876 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
881 function onInsert($req, $roo)
884 $p = DB_DataObject::factory('person');
885 if ($roo->authUser->id < 0 && $p->count() == 1) {
886 // this seems a bit risky...
888 $g = DB_DataObject::factory('Groups');
892 $g->get('name', 'Administrators');
894 $p = DB_DataObject::factory('group_members');
895 $p->group_id = $g->id;
896 $p->user_id = $this->id;
899 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
903 if (!empty($req['project_id_addto'])) {
904 $pd = DB_DataObject::factory('ProjectDirectory');
905 $pd->project_id = $req['project_id_addto'];
906 $pd->person_id = $this->id;
908 $pd->office_id = $this->office_id;
909 $pd->company_id = $this->company_id;
915 function importFromArray($roo, $persons, $prefix)
917 if (!is_array($persons) || empty($persons)) {
918 $roo->jerr("error in the person data. - empty on not valid");
920 DB_DataObject::factory('groups')->initGroups();
922 foreach($persons as $person){
923 $p = DB_DataObject::factory('person');
924 if($p->get('name', $person['name'])){
927 $p->setFrom($person);
929 $companies = DB_DataObject::factory('companies');
930 if(!$companies->get('comptype', 'OWNER')){
931 $roo->jerr("Missing OWNER companies!");
933 $p->company_id = $companies->pid();
934 // strip the 'spaces etc.. make lowercase..
935 $name = strtolower(str_replace(' ', '', $person['name']));
936 $p->setPassword("$prefix$name");
939 // if $person->groups is set.. then
940 // add this person to that group eg. groups : [ 'Administrator' ]
941 if(!empty($person['groups'])){
942 $groups = DB_DataObject::factory('groups');
943 if(!$groups->get('name', $person['groups'])){
944 $roo->jerr("Missing groups : {$person['groups']}");
946 $gm = DB_DataObject::factory('group_members');
947 $gm->change($p, $groups, true);
950 $p->onInsert(array(), $roo);