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 function applyFilters($q, $au, $roo)
56 $cg = DB_DataObject::Factory('core_group')->tableName();
57 $cgm = DB_DataObject::Factory('core_group_member')->tableName();
60 * make this conditional
64 SELECT GROUP_CONCAT(CONCAT_WS('\', ${cgm}.group_id))
70 {$this->tableName()}.id = {$cgm}.user_id
73 ) AS group_membership_list
82 $p = DB_DataObject::Factory($this->tableName());
83 $p->get($this->owner_id);
92 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
98 function buildMail($templateFile, $args)
101 $args = (array) $args;
102 $content = clone($this);
104 foreach((array)$args as $k=>$v) {
108 $ff = HTML_FlexyFramework::get();
111 //?? is this really the place for this???
114 empty($args['no_auth']) &&
115 !in_array($templateFile, array(
116 // templates that can be sent without authentication.
122 $content->authUser = $this->getAuthUser();
123 if (!$content->authUser) {
124 return PEAR::raiseError("Not authenticated");
128 // should handle x-forwarded...
130 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
131 $_SERVER["HTTP_HOST"] :
132 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
134 /* use the regex compiler, as it doesnt parse <tags */
137 'compiler' => 'Flexy',
139 'filters' => array('SimpleTags','Mail'),
145 if (!empty($args['templateDir'])) {
146 $tops['templateDir'] = $args['templateDir'];
151 require_once 'HTML/Template/Flexy.php';
152 $template = new HTML_Template_Flexy( $tops );
153 $template->compile("mail/$templateFile.txt");
155 /* use variables from this object to ouput data. */
156 $mailtext = $template->bufferedOutputObject($content);
159 // if a html file with the same name exists, use that as the body
160 // I've no idea where this code went, it was here before..
161 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
162 $tops['nonHTML'] = false;
163 $template = new HTML_Template_Flexy( $tops );
164 $template->compile("mail/$templateFile.html");
165 $htmlbody = $template->bufferedOutputObject($content);
171 //echo "<PRE>";print_R($mailtext);
172 //print_R($mailtext);exit;
173 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
174 require_once 'Mail/mimeDecode.php';
175 require_once 'Mail.php';
177 $decoder = new Mail_mimeDecode($mailtext);
178 $parts = $decoder->getSendArray();
180 if (is_a($parts,'PEAR_Error')) {
182 //echo "PROBLEM: {$parts->message}";
185 list($recipents,$headers,$body) = $parts;
186 $recipents = array($this->email);
187 if (!empty($content->bcc) && is_array($content->bcc)) {
188 $recipents =array_merge($recipents, $content->bcc);
190 $headers['Date'] = date('r');
192 if ($htmlbody !== false) {
193 require_once 'Mail/mime.php';
194 $mime = new Mail_mime(array('eol' => "\n"));
195 $mime->setTXTBody($body);
196 $mime->setHTMLBody($htmlbody);
197 // I think there might be code in mediaoutreach toEmail somewhere
198 // h embeds images here..
199 $body = $mime->get();
200 $headers = $mime->headers($headers);
207 'recipients' => $recipents,
208 'headers' => $headers,
218 * - user must be authenticate or args[no_auth] = true
219 * or template = password_[reset|welcome]
222 function sendTemplate($templateFile, $args)
225 $ar = $this->buildMail($templateFile, $args);
228 //print_r($recipents);exit;
229 $mailOptions = PEAR::getStaticProperty('Mail','options');
230 $mail = Mail::factory("SMTP",$mailOptions);
232 if (PEAR::isError($mail)) {
235 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
236 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
237 error_reporting($oe);
246 function getEmailFrom()
248 if (empty($this->name)) {
252 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
255 function toEventString()
257 return empty($this->name) ? $this->email : $this->name;
260 function verifyAuth()
262 $ff= HTML_FlexyFramework::get();
263 if (!empty($ff->Pman['auth_comptype']) &&
264 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
267 $sesPrefix = $this->sesPrefix();
269 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
273 //$ff->page->jerr("Login not permited to outside companies");
280 // ---------------- authentication / passwords and keys stuff ----------------
285 $ff= HTML_FlexyFramework::get();
287 $sesPrefix = $this->sesPrefix();
289 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
291 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
293 $u = DB_DataObject::factory($this->tableName());
294 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
296 return $u->verifyAuth(); // got authentication...
301 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
302 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
303 setcookie('Pman.timeout', -1, time() + (30*60), '/');
308 $u = DB_DataObject::factory($this->tableName());
310 if (!empty($_SERVER['PHP_AUTH_USER'])
312 !empty($_SERVER['PHP_AUTH_PW'])
314 $u->get('email', $_SERVER['PHP_AUTH_USER'])
316 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
318 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
322 if (!$this->canInitializeSystem()) {
323 // die("can not init");
329 $default_admin = false;
330 if (!empty($ff->Pman['local_autoauth']) &&
331 ($ff->Pman['local_autoauth'] === true) &&
332 (!empty($_SERVER['SERVER_ADDR'])) &&
335 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
336 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
340 $_SERVER['SERVER_ADDR'] == '::1' &&
341 $_SERVER['REMOTE_ADDR'] == '::1'
345 $group = DB_DataObject::factory('core_group');
346 $group->get('name', 'Administrators');
348 $member = DB_DataObject::factory('core_group_member');
350 $member->group_id = $group->id;
352 join_user_id_id.id IS NOT NULL
354 if($member->find(true)){
355 $default_admin = DB_DataObject::factory($this->tableName());
356 if(!$default_admin->get($member->user_id)){
357 $default_admin = false;
362 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
363 $u = DB_DataObject::factory($this->tableName());
364 $ff = HTML_FlexyFramework::get();
366 if (!empty($ff->Pman['local_autoauth']) &&
367 (!empty($_SERVER['SERVER_ADDR'])) &&
370 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
371 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
375 $_SERVER['SERVER_ADDR'] == '::1' &&
376 $_SERVER['REMOTE_ADDR'] == '::1'
379 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
382 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
384 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
388 //var_dump(session_id());
389 //var_dump($_SESSION[__CLASS__]);
391 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
394 //die("got this far?");
395 // not in session or not matched...
396 $u = DB_DataObject::factory($this->tableName());
397 $u->whereAdd(' LENGTH(passwd) > 0');
399 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
400 if (class_exists('PEAR')) {
401 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
403 die($error->toString()); // not really a good thing to do...
406 if (!$n){ // authenticated as there are no users in the system...
414 function canInitializeSystem()
417 return !strcasecmp(get_class($this) , __CLASS__);
420 function getAuthUser()
422 if (!$this->isAuth()) {
426 $ff= HTML_FlexyFramework::get();
428 $sesPrefix = $this->sesPrefix();
430 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
432 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
433 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
435 $u = DB_DataObject::factory($this->tableName()); // allow extending this ...
437 if ($u->get($a->id)) { /// && strlen($u->passwd)) { // should work out the pid .. really..
439 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
440 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
446 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
447 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
448 setcookie('Pman.timeout', -1, time() + (30*60), '/');
454 if (!$this->canInitializeSystem()) {
460 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
461 $u = DB_DataObject::factory($this->tableName());
462 $u->whereAdd(' LENGTH(passwd) > 0');
463 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
467 if (isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) && $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1) {
469 // fake person - open system..
470 //$ce = DB_DataObject::factory('core_enum');
474 $u = DB_DataObject::factory($this->tableName());
477 // if a company has been created fill that in in company_id_id
478 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
480 $u->company_id_id = $c->pid();
481 $u->company_id = $c->pid();
491 $this->isAuth(); // force session start..
492 if (!$this->verifyAuth()) { // check for company valid..
496 // open up iptables at login..
497 $dbname = $this->databaseNickname();
498 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
500 // refresh admin group if we are logged in as one..
501 //DB_DataObject::debugLevel(1);
502 $g = DB_DataObject::factory('core_group');
504 $g->get('name', 'Administrators');
505 $gm = DB_DataObject::Factory('core_group_member');
506 if (in_array($g->id,$gm->listGroupMembership($this))) {
507 // refresh admin groups.
508 $gr = DB_DataObject::Factory('core_group_right');
509 $gr->applyDefs($g, 0);
512 $sesPrefix = $this->sesPrefix();
514 // we should not store the whole data in the session - otherwise it get's huge.
515 $p = DB_DAtaObject::Factory($this->tableName());
516 $p->get($this->pid());
520 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
521 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
523 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
524 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
525 // ensure it's written so that ajax calls can fetch it..
532 $this->isAuth(); // force session start..
534 $sesPrefix = $this->sesPrefix();
536 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
538 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
541 function genPassKey ($t)
543 return md5($this->email . $t. $this->passwd);
545 function simpleAuthKey($m = 0)
547 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
549 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
552 function checkTwoFactorAuthentication($val)
554 require_once 'System.php';
556 $oathtool = System::which('oathtool');
562 $cmd = "{$oathtool} --totp --base32 {$this->oath_key}";
564 $password = exec($cmd);
566 return ($password == $val) ? true : false;
569 function checkPassword($val)
571 if (substr($this->passwd,0,1) == '$') {
572 if (function_exists('pasword_verify')) {
573 return password_verify($val, $this->passwd);
575 return crypt($val,$this->passwd) == $this->passwd ;
577 // old style md5 passwords...- cant be used with courier....
578 return md5($val) == $this->passwd;
581 function setPassword($value)
583 if (function_exists('pasword_hash')) {
584 return password_hash($value);
588 while(strlen($salt)<9) {
589 $salt.=chr(rand(64,126));
590 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
592 $this->passwd = crypt($value, '$1$'. $salt. '$');
597 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
599 require_once 'Text/Password.php';
600 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
601 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
602 $this->setPassword($this->rawPasswd);
603 return $this->rawPasswd;
608 $x = DB_DataObject::factory('core_company');
610 $x->get($this->company_id);
613 function loadCompany()
615 $this->company = $this->company();
620 return $this->active;
622 function authUserName($n) // set username prior to acheck user exists query.
625 $this->whereAdd('LENGTH(passwd) > 1');
630 if (!func_num_args()) {
633 $val = array_shift(func_get_args());
634 if ($val == $this->lang) {
644 function authUserArray()
647 $aur = $this->toArray();
654 //DB_DataObject::debugLevel(1);
655 $c = DB_Dataobject::factory('core_company');
656 $im = DB_Dataobject::factory('Images');
657 $c->joinAdd($im, 'LEFT');
659 $c->selectAs($c, 'company_id_%s');
660 $c->selectAs($im, 'company_id_logo_id_%s');
661 $c->id = $this->company_id;
665 $aur = array_merge( $c->toArray(),$aur);
667 if (empty($c->company_id_logo_id_id)) {
669 $im = DB_Dataobject::factory('Images');
670 $im->ontable = DB_DataObject::factory('core_company')->tableName();
672 $im->imgtype = 'LOGO';
675 $im->selectAs($im, 'company_id_logo_id_%s');
676 if ($im->find(true)) {
678 foreach($im->toArray() as $k=>$v) {
679 if (!preg_match('/^company_id_logo_id_/', $k)) {
688 $aur['perms'] = $this->getPerms();
689 $g = DB_DataObject::Factory('core_group_member');
690 $aur['groups'] = $g->listGroupMembership($this, 'name');
693 $aur['dailykey'] = '';
694 $aur['oath_key'] = '';
700 // ----------PERMS------ ----------------
703 //DB_DataObject::debugLevel(1);
704 // find out all the groups they are a member of.. + Default..
706 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
708 $g = DB_DataObject::Factory('core_group_right');
714 return $g->adminRights(); // system is not set up - so they get full rights.
716 //DB_DataObject::debugLevel(1);
717 $g = DB_DataObject::Factory('core_group_member');
718 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
720 // add the current user to the admin group..
721 $g = DB_DataObject::Factory('core_group');
722 if ($g->get('name', 'Administrators')) {
723 $gm = DB_DataObject::Factory('core_group_member');
724 $gm->group_id = $g->id;
725 $gm->user_id = $this->id;
731 // ------ STANDARD PERMISSION HANDLING.
732 $isOwner = $this->company()->comptype == 'OWNER';
733 $g = DB_DataObject::Factory('core_group_member');
734 $grps = $g->listGroupMembership($this);
736 $isAdmin = $g->inAdmin; //??? what???
737 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
738 // the load all the perms for those groups, and add them all together..
739 // then load all those
740 $g = DB_DataObject::Factory('core_group_right');
741 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
742 //echo '<PRE>';print_r($ret);
748 *Basic group fetching - probably needs to filter by type eventually.
750 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
753 function groups($what=false)
755 $g = DB_DataObject::Factory('core_group_member');
756 $grps = $g->listGroupMembership($this);
757 $g = DB_DataObject::Factory('core_group');
758 $g->whereAddIn('id', $grps, 'int');
759 return $g->fetchAll($what);
765 function hasPerm($name, $lvl)
767 static $pcache = array();
769 if (!isset($pcache[$this->id])) {
770 $pcache[$this->id] = $this->getPerms();
773 // echo "<PRE>";print_r($pcache[$au->id]);
774 // var_dump($pcache[$au->id]);
775 if (empty($pcache[$this->id][$name])) {
779 return strpos($pcache[$this->id][$name], $lvl) > -1;
783 // ------------ROO HOOKS------------------------------------
784 function applyFilters($q, $au, $roo)
786 //DB_DataObject::DebugLevel(1);
788 if (!empty($q['query']['is_owner'])) {
789 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
792 if (!empty($q['query']['person_not_internal'])) {
793 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
796 if (!empty($q['query']['person_internal_only_all'])) {
799 // must be internal and not current user (need for distribution list)
800 // user has a projectdirectory entry and role is not blank.
801 //DB_DataObject::DebugLevel(1);
802 $pd = DB_DataObject::factory('ProjectDirectory');
803 $pd->whereAdd("role != ''");
805 $pd->selectAdd('distinct(person_id) as person_id');
806 $roled = $pd->fetchAll('person_id');
808 {$this->tableName()}.id IN (".implode(',', $roled) . ")
810 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
813 // -- for distribution
814 if (!empty($q['query']['person_internal_only'])) {
815 // must be internal and not current user (need for distribution list)
816 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
818 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
819 // ".id != ".$au->id);
820 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
823 if (!empty($q['query']['comptype_or_company_id'])) {
824 // DB_DataObject::debugLevel(1);
825 $bits = explode(',', $q['query']['comptype_or_company_id']);
826 $id = (int) array_pop($bits);
827 $ct = $this->escape($bits[0]);
829 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
835 if (!empty($q['query']['person_inactive'])) {
836 // DB_Dataobject::debugLevel(1);
839 $tn_p = $this->tableName();
840 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
841 $tn_g = DB_DataObject::Factory('core_group')->tableName();
843 ///---------------- Group views --------
844 if (!empty($q['query']['in_group'])) {
845 // DB_DataObject::debugLevel(1);
846 $ing = (int) $q['query']['in_group'];
847 if ($q['query']['in_group'] == -1) {
849 // list all staff who are not in a group.
850 $this->whereAdd("{$this->tableName()}.id NOT IN (
851 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
852 $tn_g ON $tn_g.id = $tn_gm.group_id
853 WHERE $tn_g.type = ".$q['query']['type']."
859 $this->whereAdd("$tn_p.id IN (
860 SELECT distinct(user_id) FROM $tn_gm
861 WHERE group_id = $ing
867 if(!empty($q['in_group_name'])){
869 $v = $this->escape($q['in_group_name']);
874 DISTINCT(user_id) FROM $tn_gm
878 $tn_g.id = $tn_gm.group_id
885 // #2307 Search Country!!
886 if (!empty($q['query']['in_country'])) {
887 // DB_DataObject::debugLevel(1);
888 $inc = $q['query']['in_country'];
889 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
892 if (!empty($q['query']['not_in_directory'])) {
893 // it's a Person list..
894 // DB_DATaobjecT::debugLevel(1);
896 // specific to project directory which is single comp. login
898 $owncomp = DB_DataObject::Factory('core_company');
899 $owncomp->get('comptype', 'OWNER');
900 if ($q['company_id'] == $owncomp->id) {
906 if ( $q['query']['not_in_directory'] > -1) {
907 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
908 // can list current - so that it does not break!!!
909 $this->whereAdd("$tn_p.id NOT IN
910 ( SELECT distinct person_id FROM $tn_pd WHERE
911 project_id = " . $q['query']['not_in_directory'] . " AND
912 company_id = " . $this->company_id . ')');
916 if (!empty($q['query']['role'])) {
917 // it's a Person list..
918 // DB_DATaobjecT::debugLevel(1);
920 // specific to project directory which is single comp. login
922 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
923 // can list current - so that it does not break!!!
924 $this->whereAdd("$tn_p.id IN
925 ( SELECT distinct person_id FROM $tn_pd WHERE
926 role = '". $this->escape($q['query']['role']) ."'
932 if (!empty($q['query']['project_member_of'])) {
933 // this is also a flag to return if they are a member..
934 //DB_DataObject::debugLevel(1);
935 $do = DB_DataObject::factory('ProjectDirectory');
936 $do->project_id = $q['query']['project_member_of'];
937 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
938 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
939 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
942 if (!empty($q['query']['project_member_filter'])) {
943 $this->having('is_member !=0');
949 if(!empty($q['query']['name'])){
951 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
954 if(!empty($q['query']['name_starts'])){
956 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
960 if (!empty($q['query']['search'])) {
962 // use our magic search builder...
964 require_once 'Text/SearchParser.php';
965 $x = new Text_SearchParser($q['query']['search']);
973 "join_company_id_id.name"
975 $tbcols = $this->table();
976 foreach(array('firstname','lastname') as $k) {
977 if (isset($tbcols[$k])) {
978 $props[] = "{$tn_p}.{$k}";
985 $str = $x->toSQL(array(
988 'company' => 'join_company_id_id.name',
989 //'country' => 'Clipping.country',
990 // 'media' => 'Clipping.media_name',
992 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
997 $this->whereAdd($str); /*
998 $tn_p.name LIKE '%$s%' OR
999 $tn_p.email LIKE '%$s%' OR
1000 $tn_p.role LIKE '%$s%' OR
1001 $tn_p.phone LIKE '%$s%' OR
1002 $tn_p.remarks LIKE '%$s%'
1007 // project directory rules -- this may distrupt things.
1008 $p = DB_DataObject::factory('ProjectDirectory');
1009 // if project directories are set up, then we can apply project query rules..
1012 $pids = $p->projects($au);
1013 if (isset($q['query']['project_id'])) {
1014 $pid = (int)$q['query']['project_id'];
1015 if (!in_array($pid, $pids)) {
1016 $roo->jerr("Project not in users valid projects");
1018 $pids = array($pid);
1021 //if (empty($q['_anyrole'])) { // should be project_directry_role
1022 // $p->whereAdd("{$p->tableName()}.role != ''");
1024 if (!empty($q['query']['role'])) { // should be project_directry_role
1025 $role = $this->escape($q['query']['role']);
1027 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1031 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1032 $peps = $p->people($pids);
1033 $this->whereAddIn("{$tn}.id", $peps, 'int');
1037 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1038 if (isset($q['query']['ticket_id'])) {
1039 // find out what state the ticket is in.
1040 $t = DB_DataObject::Factory('mtrack_ticket');
1042 $t->get($q['query']['ticket_id']);
1044 if (!$this->checkPerm('S', $au)) {
1045 $roo->jerr("permssion denied to query state of ticket");
1048 $p = DB_DataObject::factory('ProjectDirectory');
1049 $pids = array($t->project_id);
1051 $peps = $p->people($pids);
1053 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1055 //$this->whereAdd('join_prole != ''");
1060 * Seems we never expose oath_key / passwd, so...
1063 if($this->tableName() == 'core_person'){
1064 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1067 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1068 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1075 function setFromRoo($ar, $roo)
1077 $this->setFrom($ar);
1079 if(!empty($ar['_enable_oath_key'])){
1080 $this->generateOathKey();
1083 if (!empty($ar['passwd1'])) {
1084 $this->setPassword($ar['passwd1']);
1088 ($this->email == $roo->old->email)&&
1089 ($this->company_id == $roo->old->company_id)
1093 if (empty($this->email)) {
1096 // this only applies to our owner company..
1097 $c = $this->company();
1098 if (empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1103 $xx = DB_Dataobject::factory($this->tableName());
1105 'email' => $this->email,
1106 // 'company_id' => $x->company_id
1110 return "Duplicate Email found";
1117 * before Delete - delete significant dependancies..
1118 * this is called after checkPerm..
1121 function beforeDelete($dependants_array, $roo)
1123 //delete group membership except for admin group..
1124 // if they are a member of admin group do not delete anything.
1125 $default_admin = false;
1127 $e = DB_DataObject::Factory('Events');
1128 $e->whereAdd('person_id = ' . $this->id);
1130 $g = DB_DataObject::Factory('core_group');
1131 $g->get('name', 'Administrators'); // select * from core_group where name = 'Administrators'
1133 $p = DB_DataObject::Factory('core_group_member');
1135 'user_id' => $this->id,
1136 'group_id' => $g->id
1140 $roo->jerr("Please remove this user from the Administrator group before deleting");
1144 $p = DB_DataObject::Factory('core_group_member');
1145 $p->user_id = $this->id;
1146 $mem = $p->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1148 $e->logDeletedRecord($p);
1150 foreach($mem as $p) {
1154 $e = DB_DataObject::Factory('events');
1155 $e->person_id = $this->id;
1156 $eve = $e->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1158 foreach($eve as $e) {
1170 * Check if the a user has access to modify this item.
1171 * @param String $lvl Level (eg. Core.Projects)
1172 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1173 * @param boolean $changes alllow changes???
1175 * @return false if no access..
1177 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1180 // do we have an empty system..
1181 if ($au && $au->id == -1) {
1184 // if not authenticated... do not allow in???
1189 // determine if it's staff!!!
1190 $owncomp = DB_DataObject::Factory('core_company');
1191 $owncomp->get('comptype', 'OWNER');
1192 $isStaff = ($au->company_id == $owncomp->id);
1197 // - can not change company!!!
1199 isset($changes['company_id']) &&
1200 $changes['company_id'] != $au->company_id) {
1203 // can only set new emails..
1205 !empty($this->email) &&
1206 isset($changes['email']) &&
1207 $changes['email'] != $this->email) {
1212 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1213 // ???? do we want this?
1215 // edit self... - what about other staff members...
1217 //return $this->company_id == $au->company_id;
1221 // yes, only owner company can mess with this...
1227 // extra case change passwod?
1228 case 'P': //??? password
1229 // standard perms -- for editing + if the user is dowing them selves..
1230 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1231 return $ret || $au->id == $this->id;
1234 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1240 function beforeInsert($req, $roo)
1242 $p = DB_DataObject::factory('core_person');
1243 if ($roo->authUser->id > -1 || $p->count() > 1) {
1246 $c = DB_DataObject::Factory('core_company');
1249 if (!$tc || $tc> 1) {
1250 $roo->jerr("can not create initial user as multiple companies already exist");
1253 $this->company_id = $c->id;
1257 function onInsert($req, $roo)
1260 $p = DB_DataObject::factory('core_person');
1261 if ($roo->authUser->id < 0 && $p->count() == 1) {
1262 // this seems a bit risky...
1264 $g = DB_DataObject::factory('core_group');
1268 $g->get('name', 'Administrators');
1270 $p = DB_DataObject::factory('core_group_member');
1271 $p->group_id = $g->id;
1272 $p->user_id = $this->id;
1275 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1279 if (!empty($req['project_id_addto'])) {
1280 $pd = DB_DataObject::factory('ProjectDirectory');
1281 $pd->project_id = $req['project_id_addto'];
1282 $pd->person_id = $this->id;
1284 $pd->office_id = $this->office_id;
1285 $pd->company_id = $this->company_id;
1291 function importFromArray($roo, $persons, $opts)
1293 if (empty($opts['prefix'])) {
1294 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1297 if (!is_array($persons) || empty($persons)) {
1298 $roo->jerr("error in the person data. - empty on not valid");
1300 DB_DataObject::factory('core_group')->initGroups();
1302 foreach($persons as $person){
1303 $p = DB_DataObject::factory('core_person');
1304 if($p->get('name', $person['name'])){
1307 $p->setFrom($person);
1309 $companies = DB_DataObject::factory('core_company');
1310 if(!$companies->get('comptype', 'OWNER')){
1311 $roo->jerr("Missing OWNER companies!");
1313 $p->company_id = $companies->pid();
1314 // strip the 'spaces etc.. make lowercase..
1315 $name = strtolower(str_replace(' ', '', $person['name']));
1316 $p->setPassword("{$opts['prefix']}{$name}");
1319 // if $person->groups is set.. then
1320 // add this person to that group eg. groups : [ 'Administrator' ]
1321 if(!empty($person['groups'])){
1322 $groups = DB_DataObject::factory('core_group');
1323 if(!$groups->get('name', $person['groups'])){
1324 $roo->jerr("Missing groups : {$person['groups']}");
1326 $gm = DB_DataObject::factory('core_group_member');
1327 $gm->change($p, $groups, true);
1330 $p->onInsert(array(), $roo);
1334 // this is for the To: "{getEmailName()}" <email@address>
1335 // not good for Dear XXXX, - use {person.firstname} for that.
1336 function getEmailName()
1340 if(!empty($this->honor)){
1341 array_push($name, $this->honor);
1344 if(!empty($this->name)){
1345 array_push($name, $this->name);
1347 return implode(' ', $name);
1350 if(!empty($this->firstname) || !empty($this->lastname)){
1351 array_push($name, $this->firstname);
1352 array_push($name, $this->lastname);
1354 $name = array_filter($name);
1356 return implode(' ', $name);
1359 return $this->email;
1362 function sesPrefix()
1364 $ff= HTML_FlexyFramework::get();
1366 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1368 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1370 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1375 function loginPublic()
1377 $this->isAuth(); // force session start..
1379 $db = $this->getDatabaseConnection();
1381 $ff = HTML_FlexyFramework::get();
1383 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1387 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1389 $p = DB_DAtaObject::Factory($this->tableName());
1390 $p->get($this->pid());
1392 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1397 function beforeUpdate($old, $q, $roo)
1399 if(!empty($q['_generate_oath_key'])){
1401 $this->generateOathKey();
1406 if(!empty($q['_to_qr_code'])){
1407 $qrcode = $this->generateQRCode();
1410 $roo->jerr('Fail to generate QR Code');
1415 // handle group_id here..
1416 if(!empty($q['group_id'])){
1418 // insert data into core_person_member...
1424 function generateOathKey()
1426 $hex = bin2hex(openssl_random_pseudo_bytes(10));
1428 require 'Base32.php';
1430 $base32 = new Base32();
1432 $this->oath_key = $base32->base32_encode($hex);
1434 return $this->oath_key;
1438 function generateQRCode()
1440 if(empty($this->oath_key)){
1444 $issuer = (empty($this->name)) ? rawurlencode('ROOJS') : rawurlencode($this->name);
1446 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$this->oath_key}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1448 require_once 'Image/QRCode.php';
1450 $qrcode = new Image_QRCode();
1452 $image = $qrcode->makeCode($uri, array(
1453 'output_type' => 'return'
1458 $base64 = base64_encode(ob_get_contents());
1461 return "data:image/png;base64,{$base64}";