3 * Table Definition for Person
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
8 class Pman_Core_DataObjects_Core_person extends DB_DataObject
11 /* the code below is auto generated do not remove the above tag */
13 public $__table = 'core_person'; // table name
14 public $id; // int(11) not_null primary_key auto_increment
15 public $email; // string(128) not_null
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
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)
36 public $active; // int(11) not_null
37 public $deleted_by; // int(11) not_null
38 public $deleted_dt; // datetime(19) binary
41 public $name_facebook; // VARCHAR(128) NULL;
42 public $url_blog; // VARCHAR(256) NULL ;
43 public $url_twitter; // VARCHAR(256) NULL ;
44 public $url_linkedin; // VARCHAR(256) NULL ;
45 public $linkedin_id; // VARCHAR(256) NULL ;
47 public $phone_mobile; // varchar(32) NOT NULL DEFAULT '';
48 public $phone_direct; // varchar(32) NOT NULL DEFAULT '';
49 public $countries; // VARCHAR(128) NULL;
51 /* the code above is auto generated do not remove the tag below */
54 static $authUser = false;
59 // this might be a Person in some old code?
60 $p = DB_DataObject::Factory('core_person');
61 $p->get($this->owner_id);
70 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
76 function buildMail($templateFile, $args)
79 $args = (array) $args;
80 $content = clone($this);
82 foreach((array)$args as $k=>$v) {
86 $ff = HTML_FlexyFramework::get();
89 //?? is this really the place for this???
92 empty($args['no_auth']) &&
93 !in_array($templateFile, array(
94 // templates that can be sent without authentication.
100 $content->authUser = $this->getAuthUser();
101 if (!$content->authUser) {
102 return PEAR::raiseError("Not authenticated");
106 // should handle x-forwarded...
108 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
109 $_SERVER["HTTP_HOST"] :
110 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
112 /* use the regex compiler, as it doesnt parse <tags */
115 'compiler' => 'Flexy',
117 'filters' => array('SimpleTags','Mail'),
123 if (!empty($args['templateDir'])) {
124 $tops['templateDir'] = $args['templateDir'];
129 require_once 'HTML/Template/Flexy.php';
130 $template = new HTML_Template_Flexy( $tops );
131 $template->compile("mail/$templateFile.txt");
133 /* use variables from this object to ouput data. */
134 $mailtext = $template->bufferedOutputObject($content);
137 // if a html file with the same name exists, use that as the body
138 // I've no idea where this code went, it was here before..
139 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
140 $tops['nonHTML'] = false;
141 $template = new HTML_Template_Flexy( $tops );
142 $template->compile("mail/$templateFile.html");
143 $htmlbody = $template->bufferedOutputObject($content);
149 //echo "<PRE>";print_R($mailtext);
150 //print_R($mailtext);exit;
151 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
152 require_once 'Mail/mimeDecode.php';
153 require_once 'Mail.php';
155 $decoder = new Mail_mimeDecode($mailtext);
156 $parts = $decoder->getSendArray();
158 if (is_a($parts,'PEAR_Error')) {
160 //echo "PROBLEM: {$parts->message}";
163 list($recipents,$headers,$body) = $parts;
164 $recipents = array($this->email);
165 if (!empty($content->bcc) && is_array($content->bcc)) {
166 $recipents =array_merge($recipents, $content->bcc);
168 $headers['Date'] = date('r');
170 if ($htmlbody !== false) {
171 require_once 'Mail/mime.php';
172 $mime = new Mail_mime(array('eol' => "\n"));
173 $mime->setTXTBody($body);
174 $mime->setHTMLBody($htmlbody);
175 // I think there might be code in mediaoutreach toEmail somewhere
176 // h embeds images here..
177 $body = $mime->get();
178 $headers = $mime->headers($headers);
182 'recipients' => $recipents,
183 'headers' => $headers,
191 * - user must be authenticate or args[no_auth] = true
192 * or template = password_[reset|welcome]
195 function sendTemplate($templateFile, $args)
197 $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);
216 function getEmailFrom()
218 if (empty($this->name)) {
222 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
225 function toEventString()
227 return empty($this->name) ? $this->email : $this->name;
230 function verifyAuth()
232 $ff= HTML_FlexyFramework::get();
233 if (!empty($ff->Pman['auth_comptype']) &&
234 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
237 $sesPrefix = $this->sesPrefix();
239 self::$authUser = false;
240 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
244 //$ff->page->jerr("Login not permited to outside companies");
251 // ---------------- authentication / passwords and keys stuff ----------------
256 $ff= HTML_FlexyFramework::get();
258 $sesPrefix = $this->sesPrefix();
260 if (self::$authUser) {
261 return self::$authUser;
265 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
267 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
268 $u = DB_DataObject::factory($this->tableName());
270 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
271 if ($u->verifyAuth()) {
272 self::$authUser = $u;
276 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
277 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
278 setcookie('Pman.timeout', -1, time() + (30*60), '/');
283 $u = DB_DataObject::factory($this->tableName());
285 if (!empty($_SERVER['PHP_AUTH_USER'])
287 !empty($_SERVER['PHP_AUTH_PW'])
289 $u->get('email', $_SERVER['PHP_AUTH_USER'])
291 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
293 // logged in via http auth
294 // http auth will not need session...
295 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
296 self::$authUser = $u;
300 if (!$this->canInitializeSystem()) {
301 // die("can not init");
306 $auto_auth_allow = false;
307 if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
308 $auto_auth_allow = true;
310 if ( !empty($ff->Pman['local_autoauth'])
312 !empty($_SERVER['SERVER_ADDR']) &&
313 !empty($_SERVER['REMOTE_ADDR']) &&
316 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
317 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
321 $_SERVER['SERVER_ADDR'] == '::1' &&
322 $_SERVER['REMOTE_ADDR'] == '::1'
327 $auto_auth_allow = true;
331 if (empty($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '/Login') {
332 $auto_auth_allow = false;
334 //var_dump($auto_auth_allow);
336 $default_admin = false;
337 if ($auto_auth_allow) {
338 $group = DB_DataObject::factory('core_group');
339 $group->get('name', 'Administrators');
341 $member = DB_DataObject::factory('core_group_member');
343 $member->group_id = $group->id;
345 join_user_id_id.id IS NOT NULL
347 if($member->find(true)){
348 $default_admin = DB_DataObject::factory($this->tableName());
349 $default_admin->autoJoin();
350 if(!$default_admin->get($member->user_id)){
351 $default_admin = false;
356 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
357 $u = DB_DataObject::factory($this->tableName());
359 $ff = HTML_FlexyFramework::get();
361 if ($auto_auth_allow &&
362 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
365 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
367 // if we request other URLS.. then we get auto logged in..
368 self::$authUser = $default_admin ? $default_admin : $u;;
369 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
373 //var_dump(session_id());
374 //var_dump($_SESSION[__CLASS__]);
376 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
379 //die("got this far?");
380 // not in session or not matched...
381 $u = DB_DataObject::factory($this->tableName());
382 $u->whereAdd(' LENGTH(passwd) > 0');
384 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
385 if (class_exists('PEAR')) {
386 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
388 die($error->toString()); // not really a good thing to do...
391 if (!$n){ // authenticated as there are no users in the system...
398 function canInitializeSystem()
401 return !strcasecmp(get_class($this) , __CLASS__);
404 function getAuthUser()
406 if (!$this->isAuth()) {
410 $ff= HTML_FlexyFramework::get();
412 $sesPrefix = $this->sesPrefix();
414 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
416 if (self::$authUser) {
418 if (isset($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
419 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
420 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
422 // not really sure why it's cloned..
423 return clone (self::$authUser);
430 if (!$this->canInitializeSystem()) {
436 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
437 $u = DB_DataObject::factory($this->tableName());
438 $u->whereAdd(' LENGTH(passwd) > 0');
439 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
444 isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) &&
445 $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1
448 // fake person - open system..
449 //$ce = DB_DataObject::factory('core_enum');
453 $u = DB_DataObject::factory($this->tableName());
456 // if a company has been created fill that in in company_id_id
457 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
459 $u->company_id_id = $c->pid();
460 $u->company_id = $c->pid();
470 $this->isAuth(); // force session start..
471 if (!$this->verifyAuth()) { // check for company valid..
475 // open up iptables at login..
476 $dbname = $this->databaseNickname();
477 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
479 // refresh admin group if we are logged in as one..
480 //DB_DataObject::debugLevel(1);
481 $g = DB_DataObject::factory('core_group');
483 $g->get('name', 'Administrators');
484 $gm = DB_DataObject::Factory('core_group_member');
485 if (in_array($g->id,$gm->listGroupMembership($this))) {
486 // refresh admin groups.
487 $gr = DB_DataObject::Factory('core_group_right');
488 $gr->applyDefs($g, 0);
491 $sesPrefix = $this->sesPrefix();
493 // we should not store the whole data in the session - otherwise it get's huge.
494 $p = DB_DAtaObject::Factory($this->tableName());
495 $p->get($this->pid());
499 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
500 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
502 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
503 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
505 $pp = DB_DAtaObject::Factory($this->tableName());
506 $pp->get($this->pid());
509 self::$authUser = $pp;
510 // ensure it's written so that ajax calls can fetch it..
517 $this->isAuth(); // force session start..
519 $sesPrefix = $this->sesPrefix();
521 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
523 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
525 self::$authUser = false;
528 function genPassKey ($t)
530 return md5($this->email . $t. $this->passwd);
532 function simpleAuthKey($m = 0)
534 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
536 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
539 function checkTwoFactorAuthentication($val)
543 // also used in login
544 require_once 'System.php';
548 empty($this->oath_key)
553 $oathtool = System::which('oathtool');
559 $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
561 $password = exec($cmd);
563 return ($password == $val) ? true : false;
566 function checkPassword($val)
568 if (substr($this->passwd,0,1) == '$') {
569 if (function_exists('pasword_verify')) {
570 return password_verify($val, $this->passwd);
572 return crypt($val,$this->passwd) == $this->passwd ;
574 // old style md5 passwords...- cant be used with courier....
575 return md5($val) == $this->passwd;
578 function setPassword($value)
580 if (function_exists('pasword_hash')) {
581 return password_hash($value);
585 while(strlen($salt)<9) {
586 $salt.=chr(rand(64,126));
587 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
589 $this->passwd = crypt($value, '$1$'. $salt. '$');
594 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
596 require_once 'Text/Password.php';
597 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
598 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
599 $this->setPassword($this->rawPasswd);
600 return $this->rawPasswd;
605 $x = DB_DataObject::factory('core_company');
607 $x->get($this->company_id);
610 function loadCompany()
612 $this->company = $this->company();
617 return $this->active;
619 function authUserName($n) // set username prior to acheck user exists query.
622 $this->whereAdd('LENGTH(passwd) > 1');
627 if (!func_num_args()) {
630 $ar = func_get_args();
631 $val = array_shift($ar);
632 if ($val == $this->lang) {
642 function authUserArray()
644 $aur = $this->toArray();
650 //DB_DataObject::debugLevel(1);
651 $c = DB_Dataobject::factory('core_company');
652 $im = DB_Dataobject::factory('Images');
653 $c->joinAdd($im, 'LEFT');
655 $c->selectAs($c, 'company_id_%s');
656 $c->selectAs($im, 'company_id_logo_id_%s');
657 $c->id = $this->company_id;
661 $aur = array_merge( $c->toArray(),$aur);
663 if (empty($c->company_id_logo_id_id)) {
665 $im = DB_Dataobject::factory('Images');
666 $im->ontable = DB_DataObject::factory('core_company')->tableName();
668 $im->imgtype = 'LOGO';
671 $im->selectAs($im, 'company_id_logo_id_%s');
672 if ($im->find(true)) {
674 foreach($im->toArray() as $k=>$v) {
675 if (!preg_match('/^company_id_logo_id_/', $k)) {
684 $aur['perms'] = $this->getPerms();
685 $g = DB_DataObject::Factory('core_group_member');
686 $aur['groups'] = $g->listGroupMembership($this, 'name');
689 $aur['dailykey'] = '';
690 $aur['oath_key'] = '';
692 $aur['oath_key_enable'] = !empty($this->oath_key);
693 $aur['require_oath'] = 1;
695 $s = DB_DataObject::Factory('core_setting');
696 $oath_require = $s->lookup('core', 'two_factor_auth_required');
697 $aur['require_oath'] = $oath_require ? $oath_require->val : 0;
699 $aur['core_person_settings'] = array();
701 $core_person_settings = DB_DataObject::factory('core_person_settings');
702 $core_person_settings->setFrom(array(
703 'person_id' => $this->id
706 $aur['core_person_settings'] = $core_person_settings->fetchAll('scope', 'data');
711 // ----------PERMS------ ----------------
714 //DB_DataObject::debugLevel(1);
715 // find out all the groups they are a member of.. + Default..
717 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
719 $g = DB_DataObject::Factory('core_group_right');
725 return $g->adminRights(); // system is not set up - so they get full rights.
727 //DB_DataObject::debugLevel(1);
728 $g = DB_DataObject::Factory('core_group_member');
729 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
731 // add the current user to the admin group..
732 $g = DB_DataObject::Factory('core_group');
733 if ($g->get('name', 'Administrators')) {
734 $gm = DB_DataObject::Factory('core_group_member');
735 $gm->group_id = $g->id;
736 $gm->user_id = $this->id;
742 // ------ STANDARD PERMISSION HANDLING.
743 $isOwner = $this->company()->comptype == 'OWNER';
744 $g = DB_DataObject::Factory('core_group_member');
745 $grps = $g->listGroupMembership($this);
747 $isAdmin = $g->inAdmin; //??? what???
748 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
749 // the load all the perms for those groups, and add them all together..
750 // then load all those
751 $g = DB_DataObject::Factory('core_group_right');
752 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
753 //echo '<PRE>';print_r($ret);
759 *Basic group fetching - probably needs to filter by type eventually.
761 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
764 function groups($what=false)
766 $g = DB_DataObject::Factory('core_group_member');
767 $grps = $g->listGroupMembership($this);
768 $g = DB_DataObject::Factory('core_group');
769 $g->whereAddIn('id', $grps, 'int');
770 return $g->fetchAll($what);
776 function hasPerm($name, $lvl)
778 static $pcache = array();
780 if (!isset($pcache[$this->id])) {
781 $pcache[$this->id] = $this->getPerms();
784 // echo "<PRE>";print_r($pcache[$au->id]);
785 // var_dump($pcache[$au->id]);
786 if (empty($pcache[$this->id][$name])) {
790 return strpos($pcache[$this->id][$name], $lvl) > -1;
794 // ------------ROO HOOKS------------------------------------
795 function applyFilters($q, $au, $roo)
797 //DB_DataObject::DebugLevel(1);
798 if(!empty($q['_to_qr_code'])){
799 $person = DB_DataObject::factory('Core_person');
800 $person->id = $q['id'];
802 if(!$person->find(true)) {
803 $roo->jerr('_invalid_person');
806 $hash = $this->generateOathKey();
808 $_SESSION[__CLASS__] =
809 isset($_SESSION[__CLASS__]) ?
810 $_SESSION[__CLASS__] : array();
811 $_SESSION[__CLASS__]['oath'] =
812 isset($_SESSION[__CLASS__]['oath']) ?
813 $_SESSION[__CLASS__]['oath'] : array();
815 $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
817 $qrcode = $person->generateQRCode($hash);
820 $roo->jerr('Fail to generate QR Code');
826 'issuer' => $person->qrCodeIssuer()
830 if(!empty($q['two_factor_auth_code'])) {
831 $person = DB_DataObject::factory('core_person');
832 $person->get($q['id']);
834 $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
836 if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
838 unset($_SESSION[__CLASS__]['oath'][$person->id]);
842 $roo->jerr('_invalid_auth_code');
845 if(!empty($q['oath_key_disable'])) {
846 $person = DB_DataObject::factory('core_person');
847 $person->get($q['id']);
851 $person->oath_key = '';
857 if (!empty($q['query']['is_owner'])) {
858 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
861 if (!empty($q['query']['person_not_internal'])) {
862 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
865 if (!empty($q['query']['person_internal_only_all'])) {
868 // must be internal and not current user (need for distribution list)
869 // user has a projectdirectory entry and role is not blank.
870 //DB_DataObject::DebugLevel(1);
871 $pd = DB_DataObject::factory('ProjectDirectory');
872 $pd->whereAdd("role != ''");
874 $pd->selectAdd('distinct(person_id) as person_id');
875 $roled = $pd->fetchAll('person_id');
877 {$this->tableName()}.id IN (".implode(',', $roled) . ")
879 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
882 // -- for distribution
883 if (!empty($q['query']['person_internal_only'])) {
884 // must be internal and not current user (need for distribution list)
885 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
887 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
888 // ".id != ".$au->id);
889 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
892 if (!empty($q['query']['comptype_or_company_id'])) {
893 // DB_DataObject::debugLevel(1);
894 $bits = explode(',', $q['query']['comptype_or_company_id']);
895 $id = (int) array_pop($bits);
896 $ct = $this->escape($bits[0]);
898 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
904 if (!empty($q['query']['person_inactive'])) {
905 // DB_Dataobject::debugLevel(1);
908 $tn_p = $this->tableName();
909 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
910 $tn_g = DB_DataObject::Factory('core_group')->tableName();
912 ///---------------- Group views --------
913 if (!empty($q['query']['in_group'])) {
914 // DB_DataObject::debugLevel(1);
915 $ing = (int) $q['query']['in_group'];
916 if ($q['query']['in_group'] == -1) {
918 // list all staff who are not in a group.
919 $this->whereAdd("{$this->tableName()}.id NOT IN (
920 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
921 $tn_g ON $tn_g.id = $tn_gm.group_id)");
925 $this->whereAdd("$tn_p.id IN (
926 SELECT distinct(user_id) FROM $tn_gm
927 WHERE group_id = $ing
933 if(!empty($q['in_group_name'])){
935 $v = $this->escape($q['in_group_name']);
940 DISTINCT(user_id) FROM $tn_gm
944 $tn_g.id = $tn_gm.group_id
951 // #2307 Search Country!!
952 if (!empty($q['query']['in_country'])) {
953 // DB_DataObject::debugLevel(1);
954 $inc = $q['query']['in_country'];
955 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
958 if (!empty($q['query']['not_in_directory'])) {
959 // it's a Person list..
960 // DB_DATaobjecT::debugLevel(1);
962 // specific to project directory which is single comp. login
964 $owncomp = DB_DataObject::Factory('core_company');
965 $owncomp->get('comptype', 'OWNER');
966 if ($q['company_id'] == $owncomp->id) {
972 if ( $q['query']['not_in_directory'] > -1) {
973 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
974 // can list current - so that it does not break!!!
975 $this->whereAdd("$tn_p.id NOT IN
976 ( SELECT distinct person_id FROM $tn_pd WHERE
977 project_id = " . $q['query']['not_in_directory'] . " AND
978 company_id = " . $this->company_id . ')');
982 if (!empty($q['query']['role'])) {
983 // it's a Person list..
984 // DB_DATaobjecT::debugLevel(1);
986 // specific to project directory which is single comp. login
988 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
989 // can list current - so that it does not break!!!
990 $this->whereAdd("$tn_p.id IN
991 ( SELECT distinct person_id FROM $tn_pd WHERE
992 role = '". $this->escape($q['query']['role']) ."'
998 if (!empty($q['query']['project_member_of'])) {
999 // this is also a flag to return if they are a member..
1000 //DB_DataObject::debugLevel(1);
1001 $do = DB_DataObject::factory('ProjectDirectory');
1002 $do->project_id = $q['query']['project_member_of'];
1003 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1004 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
1005 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
1008 if (!empty($q['query']['project_member_filter'])) {
1009 $this->having('is_member !=0');
1015 if(!empty($q['query']['name'])){
1017 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
1020 if(!empty($q['query']['name_starts'])){
1022 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
1026 if (!empty($q['query']['search'])) {
1028 // use our magic search builder...
1030 require_once 'Text/SearchParser.php';
1031 $x = new Text_SearchParser($q['query']['search']);
1039 "join_company_id_id.name"
1041 $tbcols = $this->table();
1042 foreach(array('firstname','lastname') as $k) {
1043 if (isset($tbcols[$k])) {
1044 $props[] = "{$tn_p}.{$k}";
1051 $str = $x->toSQL(array(
1052 'default' => $props,
1054 'company' => 'join_company_id_id.name',
1055 //'country' => 'Clipping.country',
1056 // 'media' => 'Clipping.media_name',
1058 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1063 $this->whereAdd($str); /*
1064 $tn_p.name LIKE '%$s%' OR
1065 $tn_p.email LIKE '%$s%' OR
1066 $tn_p.role LIKE '%$s%' OR
1067 $tn_p.phone LIKE '%$s%' OR
1068 $tn_p.remarks LIKE '%$s%'
1073 // project directory rules -- this may distrupt things.
1074 $p = DB_DataObject::factory('ProjectDirectory');
1075 // if project directories are set up, then we can apply project query rules..
1078 $pids = $p->projects($au);
1079 if (isset($q['query']['project_id'])) {
1080 $pid = (int)$q['query']['project_id'];
1081 if (!in_array($pid, $pids)) {
1082 $roo->jerr("Project not in users valid projects");
1084 $pids = array($pid);
1087 //if (empty($q['_anyrole'])) { // should be project_directry_role
1088 // $p->whereAdd("{$p->tableName()}.role != ''");
1090 if (!empty($q['query']['role'])) { // should be project_directry_role
1091 $role = $this->escape($q['query']['role']);
1093 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1097 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1098 $peps = $p->people($pids);
1099 $this->whereAddIn("{$tn}.id", $peps, 'int');
1103 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1104 if (isset($q['query']['ticket_id'])) {
1105 // find out what state the ticket is in.
1106 $t = DB_DataObject::Factory('mtrack_ticket');
1108 $t->get($q['query']['ticket_id']);
1110 if (!$this->checkPerm('S', $au)) {
1111 $roo->jerr("permssion denied to query state of ticket");
1114 $p = DB_DataObject::factory('ProjectDirectory');
1115 $pids = array($t->project_id);
1117 $peps = $p->people($pids);
1119 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1121 //$this->whereAdd('join_prole != ''");
1126 * Seems we never expose oath_key / passwd, so...
1129 if($this->tableName() == 'core_person'){
1130 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1133 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1134 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1137 if (isset($q['_with_group_membership'])) {
1138 $this->selectAddGroupMemberships();
1143 function selectAddGroupMemberships()
1149 GROUP_CONCAT( core_group.name separator '\n')
1155 core_group.id = core_group_member.group_id
1157 core_group_member.user_id = core_person.id
1158 ), '') as member_of");
1161 function setFromRoo($ar, $roo)
1163 $this->setFrom($ar);
1165 if(!empty($ar['_enable_oath_key'])){
1166 $oath_key = $this->generateOathKey();
1169 if (!empty($ar['passwd1'])) {
1170 $this->setPassword($ar['passwd1']);
1174 ($this->email == $roo->old->email)&&
1175 ($this->company_id == $roo->old->company_id)
1179 if (empty($this->email)) {
1182 // this only applies to our owner company..
1183 $c = $this->company();
1184 if (empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1189 $xx = DB_Dataobject::factory($this->tableName());
1191 'email' => $this->email,
1192 // 'company_id' => $x->company_id
1196 return "Duplicate Email found";
1203 * before Delete - delete significant dependancies..
1204 * this is called after checkPerm..
1207 function beforeDelete($dependants_array, $roo)
1209 //delete group membership except for admin group..
1210 // if they are a member of admin group do not delete anything.
1211 $default_admin = false;
1213 $e = DB_DataObject::Factory('Events');
1214 $e->whereAdd('person_id = ' . $this->id);
1216 $g = DB_DataObject::Factory('core_group');
1217 $g->get('name', 'Administrators'); // select * from core_group where name = 'Administrators'
1219 $p = DB_DataObject::Factory('core_group_member');
1221 'user_id' => $this->id,
1222 'group_id' => $g->id
1226 $roo->jerr("Please remove this user from the Administrator group before deleting");
1230 $p = DB_DataObject::Factory('core_group_member');
1231 $p->user_id = $this->id;
1232 $mem = $p->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1233 $e->logDeletedRecord($mem);
1235 foreach($mem as $p) {
1239 $e = DB_DataObject::Factory('Events');
1240 $e->person_id = $this->id;
1241 $eve = $e->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1243 $e->logDeletedRecord($eve);
1244 foreach($eve as $e) {
1255 * Check if the a user has access to modify this item.
1256 * @param String $lvl Level (eg. Core.Projects)
1257 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1258 * @param boolean $changes alllow changes???
1260 * @return false if no access..
1262 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1265 // do we have an empty system..
1266 if ($au && $au->id == -1) {
1269 // if not authenticated... do not allow in???
1274 // determine if it's staff!!!
1275 $owncomp = DB_DataObject::Factory('core_company');
1276 $owncomp->get('comptype', 'OWNER');
1277 $isStaff = ($au->company_id == $owncomp->id);
1282 // - can not change company!!!
1284 isset($changes['company_id']) &&
1285 $changes['company_id'] != $au->company_id) {
1288 // can only set new emails..
1290 !empty($this->email) &&
1291 isset($changes['email']) &&
1292 $changes['email'] != $this->email) {
1297 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1298 // ???? do we want this?
1300 // edit self... - what about other staff members...
1302 //return $this->company_id == $au->company_id;
1306 // yes, only owner company can mess with this...
1312 // extra case change passwod?
1313 case 'P': //??? password
1314 // standard perms -- for editing + if the user is dowing them selves..
1315 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1316 return $ret || $au->id == $this->id;
1319 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1325 function beforeInsert($req, $roo)
1327 $p = DB_DataObject::factory('core_person');
1328 if ($roo->authUser->id > -1 || $p->count() > 1) {
1331 $c = DB_DataObject::Factory('core_company');
1334 if (!$tc || $tc> 1) {
1335 $roo->jerr("can not create initial user as multiple companies already exist");
1338 $this->company_id = $c->id;
1339 $this->email = trim($this->email);
1343 function onInsert($req, $roo)
1346 $p = DB_DataObject::factory('core_person');
1347 if ($roo->authUser->id < 0 && $p->count() == 1) {
1348 // this seems a bit risky...
1350 $g = DB_DataObject::factory('core_group');
1354 $g->get('name', 'Administrators');
1356 $p = DB_DataObject::factory('core_group_member');
1357 $p->group_id = $g->id;
1358 $p->user_id = $this->id;
1361 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1365 if (!empty($req['project_id_addto'])) {
1366 $pd = DB_DataObject::factory('ProjectDirectory');
1367 $pd->project_id = $req['project_id_addto'];
1368 $pd->person_id = $this->id;
1370 $pd->office_id = $this->office_id;
1371 $pd->company_id = $this->company_id;
1377 function importFromArray($roo, $persons, $opts)
1379 if (empty($opts['prefix'])) {
1380 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1383 if (!is_array($persons) || empty($persons)) {
1384 $roo->jerr("error in the person data. - empty on not valid");
1386 DB_DataObject::factory('core_group')->initGroups();
1388 foreach($persons as $person){
1389 $p = DB_DataObject::factory('core_person');
1390 if($p->get('name', $person['name'])){
1393 $p->setFrom($person);
1395 $companies = DB_DataObject::factory('core_company');
1396 if(!$companies->get('comptype', 'OWNER')){
1397 $roo->jerr("Missing OWNER companies!");
1399 $p->company_id = $companies->pid();
1400 // strip the 'spaces etc.. make lowercase..
1401 $name = strtolower(str_replace(' ', '', $person['name']));
1402 $p->setPassword("{$opts['prefix']}{$name}");
1405 // if $person->groups is set.. then
1406 // add this person to that group eg. groups : [ 'Administrator' ]
1407 if(!empty($person['groups'])){
1408 $groups = DB_DataObject::factory('core_group');
1409 if(!$groups->get('name', $person['groups'])){
1410 $roo->jerr("Missing groups : {$person['groups']}");
1412 $gm = DB_DataObject::factory('core_group_member');
1413 $gm->change($p, $groups, true);
1416 $p->onInsert(array(), $roo);
1420 // this is for the To: "{getEmailName()}" <email@address>
1421 // not good for Dear XXXX, - use {person.firstname} for that.
1422 function getEmailName()
1426 if(!empty($this->honor)){
1427 array_push($name, $this->honor);
1430 if(!empty($this->name)){
1431 array_push($name, $this->name);
1433 return implode(' ', $name);
1436 if(!empty($this->firstname) || !empty($this->lastname)){
1437 array_push($name, $this->firstname);
1438 array_push($name, $this->lastname);
1440 $name = array_filter($name);
1442 return implode(' ', $name);
1445 return $this->email;
1448 function sesPrefix()
1450 $ff= HTML_FlexyFramework::get();
1452 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1454 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1456 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1461 function loginPublic() // used where???
1463 $this->isAuth(); // force session start..
1465 $db = $this->getDatabaseConnection();
1467 $ff = HTML_FlexyFramework::get();
1469 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1473 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1475 $p = DB_DAtaObject::Factory($this->tableName());
1476 $p->get($this->pid());
1478 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1483 function beforeUpdate($old, $q, $roo)
1485 $this->email = trim($this->email);
1488 function generateOathKey()
1490 require 'Base32.php';
1492 $base32 = new Base32();
1494 return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1497 function generateQRCode($hash)
1500 empty($this->email) &&
1506 $issuer = rawurlencode($this->qrCodeIssuer());
1508 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1510 require_once 'Image/QRCode.php';
1512 $qrcode = new Image_QRCode();
1514 $image = $qrcode->makeCode($uri, array(
1515 'output_type' => 'return'
1520 $base64 = base64_encode(ob_get_contents());
1523 return "data:image/png;base64,{$base64}";
1526 function qrCodeIssuer()
1528 $pg= HTML_FlexyFramework::get()->page;
1530 $issuer = (empty($pg->company->name)) ? 'ROOJS' : "{$pg->company->name}";
1535 static function test_ADMIN_PASSWORD_RESET($pg, $to)
1537 $ff = HTML_FlexyFramework::get();
1538 $person = DB_DataObject::Factory('core_person');
1542 'HTTP_HOST' => $_SERVER['SERVER_NAME'],
1543 'person' => $person,
1544 'authFrom' => 'FAKE_LINK',
1545 'authKey' => 'FAKE_KEY',
1547 'rcpts' => $to->email,