6 * - base application setup (variables etc to javascript)
8 * - authentication and permission info about user / application
9 * - json output methods.
10 * - file upload error checking - checkFileUploadError
11 * - logging to event table
12 * - sendTemplate code (normally use the Person version for sending to specific people..)
14 * - doc managment code?? - remarks and tracking??? - MOVEME
15 * - authentication link checking?? MOVEME?
16 * - authentication reset password ?? MOVEME?
17 * ?? arrayClean.. what's it doing here?!? ;)
22 class Pman extends HTML_FlexyFramework_Page
25 var $appShortName= "";
26 var $appVersion = "1.8";
38 * ------------- Standard getAuth/get/post methods of framework.
43 function getAuth() // everyone allowed in!!!!!
45 $this->loadOwnerCompany();
53 if (isset($this->_hasInit)) {
57 $this->_hasInit = true;
59 if (method_exists('HTML_FlexyFramework', 'get')) {
61 $boot = HTML_FlexyFramework::get();
62 // echo'<PRE>';print_R($boot);exit;
63 $this->appName= $boot->appName;
64 $this->appNameShort= $boot->appNameShort;
65 $this->appModules= $boot->enable;
66 $this->isDev = true; //empty($opts['isDev']) ? '' : $opts['isDev'];
67 $this->appDisable = $boot->disable;
68 $this->version = $boot->version;
73 $opts = PEAR::getStaticProperty('Pman', 'options');
75 $this->isDev = true; //empty($opts['isDev']) ? '' : $opts['isDev'];
77 $this->appName= empty($opts['appName']) ? '' : $opts['appName'];
78 $this->appNameShort= empty($opts['appNameShort']) ? '' : $opts['appNameShort'];
79 $this->appModules= $opts['enable'];
80 $this->appDisable = $opts['disable'];
81 $this->version = isset($opts['version']) ? $this->version : $opts['version'];
89 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
90 $bits = explode('/', $base);
92 if ($bits[0] == 'Link') {
93 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
94 header('Content-type: text/html; charset=utf-8');
97 if ($bits[0] == 'PasswordReset') {
98 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
99 header('Content-type: text/html; charset=utf-8');
104 if ($this->getAuthUser()) {
105 $this->addEvent("RELOAD");
110 $this->addEvent("BADURL", false, $base);
111 $this->jerr("invalid url");
114 if (isset($_GET['onloadTrack'])) {
115 $this->onloadTrack = (int)$_GET['onloadTrack'];
117 // getting this to work with xhtml is a nightmare
118 // = nbsp / <img> issues screw everyting up.
120 //header('Content-type: application/xhtml+xml; charset=utf-8');
121 header('Content-type: text/html; charset=utf-8');
124 function post($base) {
125 return $this->get($base);
129 * ------------- Authentication and permission info about logged in user!!!
134 function loadOwnerCompany()
136 $this->company = DB_DataObject::Factory('Companies');
137 if ($this->company) { // non-core pman projects
140 $this->company->get('comptype', 'OWNER');
143 function staticGetAuthUser()
145 $u = DB_DataObject::factory('Person');
149 return $u->getAuthUser();
151 function getAuthUser()
153 if (!empty($this->authUser)) {
154 return $this->authUser;
157 $u = DB_DataObject::factory('Person');
161 $this->authUser =$u->getAuthUser();
162 return $this->authUser ;
164 function hasPerm($name, $lvl) // do we have a permission
166 static $pcache = array();
167 $au = $this->getAuthUser();
168 return $au->hasPerm($name,$lvl);
171 function hasModule($name)
174 if (!strpos( $name,'.') ) {
175 // use enable / disable..
178 $enabled = array('Core') ;
179 $enabled = !empty($this->appModules) ?
180 array_merge($enabled, explode(',', $this->appModules)) :
182 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
186 return in_array($name, $enabled) && !in_array($name, $disabled);
189 $x = DB_DataObject::factory('Group_Rights');
190 $ar = $x->defaultPermData();
191 if (empty($ar[$name]) || empty($ar[$name][0])) {
201 * ---------------- Global Tools ---------------
207 * send a template to the user
208 * rcpts are read from the resulting template.
210 * @arg $templateFile - the file in mail/XXXXXX.txt
211 * @arg $args - variables available to the form as {t.*} over and above 'this'
216 function sendTemplate($templateFile, $args)
221 $content = clone($this);
223 foreach((array)$args as $k=>$v) {
226 $content->msgid = md5(time() . rand());
228 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
229 /* use the regex compiler, as it doesnt parse <tags */
230 require_once 'HTML/Template/Flexy.php';
231 $template = new HTML_Template_Flexy( array(
232 'compiler' => 'Regex',
233 'filters' => array('SimpleTags','Mail'),
237 // this should be done by having multiple template sources...!!!
239 $template->compile('mail/'. $templateFile.'.txt');
241 /* use variables from this object to ouput data. */
242 $mailtext = $template->bufferedOutputObject($content);
243 //echo "<PRE>";print_R($mailtext);
245 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
246 require_once 'Mail/mimeDecode.php';
247 require_once 'Mail.php';
249 $decoder = new Mail_mimeDecode($mailtext);
250 $parts = $decoder->getSendArray();
251 if (PEAR::isError($parts)) {
253 //echo "PROBLEM: {$parts->message}";
256 list($recipents,$headers,$body) = $parts;
257 ///$recipents = array($this->email);
258 $mailOptions = PEAR::getStaticProperty('Mail','options');
259 $mail = Mail::factory("SMTP",$mailOptions);
260 $headers['Date'] = date('r');
261 if (PEAR::isError($mail)) {
264 $oe = error_reporting(E_ALL ^ E_NOTICE);
265 $ret = $mail->send($recipents,$headers,$body);
266 error_reporting($oe);
272 function checkFileUploadError() // check for file upload errors.
275 empty($_FILES['File'])
276 || empty($_FILES['File']['name'])
277 || empty($_FILES['File']['tmp_name'])
278 || empty($_FILES['File']['type'])
279 || !empty($_FILES['File']['error'])
280 || empty($_FILES['File']['size'])
282 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
288 * generate a tempory file with an extension (dont forget to delete it)
291 function tempName($ext)
293 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
295 return $x .'.'. $ext;
298 * ------------- Authentication testing ------ ??? MOVEME?
302 function linkAuth($trid, $trkey)
304 $tr = DB_DataObject::factory('Documents_Tracking');
305 if (!$tr->get($trid)) {
306 return "Invalid URL";
308 if (strtolower($tr->authkey) != strtolower($trkey)) {
309 $this->AddEvent("ERROR-L", false, "Invalid Key");
310 return "Invalid KEY";
313 $this->onloadTrack = (int) $tr->doc_id;
314 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
315 $this->AddEvent("ERROR-L", false, "Key Expired");
316 return "Key Expired";
318 // user logged in and not
319 $au = $this->getAuthUser();
320 if ($au && $au->id && $au->id != $tr->person_id) {
323 return "Logged Out existing Session\n - reload to log in with correct key";
325 if ($au) { // logged in anyway..
326 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
327 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
332 // authenticate the user...
334 $u = DB_DataObject::factory('Person');
336 $u->get($tr->person_id);
338 $this->AddEvent("LOGIN", false, "With Key");
340 // we need to redirect out - otherwise refererer url will include key!
341 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
353 * ------------- Authentication password reset ------ ??? MOVEME?
359 function resetPassword($id,$t, $key)
362 $au = $this->getAuthUser();
364 return "Already Logged in - no need to use Password Reset";
367 $u = DB_DataObject::factory('Person');
368 //$u->company_id = $this->company->id;
370 if (!$u->get($id) || !strlen($u->passwd)) {
375 if ($key != $u->genPassKey($t)) {
376 return "invalid key";
379 $u->no_reset_sent = 0;
382 if ($t < strtotime("NOW - 1 DAY")) {
385 $this->showNewPass = implode("/", array($id,$t,$key));
391 * ---------------- Standard JSON outputers. - used everywhere
394 function jerr($str, $errors=array()) // standard error reporting..
396 require_once 'Services/JSON.php';
397 $json = new Services_JSON();
399 if (!empty($_REQUEST['returnHTML']) ||
400 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
402 header('Content-type: text/html');
403 echo "<HTML><HEAD></HEAD><BODY>";
404 echo $json->encodeUnsafe(array(
407 'message' => $str, // compate with exeption / loadexception.
409 'errors' => $errors ? $errors : true, // used by forms to flag errors.
410 'authFailure' => !empty($errors['authFailure']),
412 echo "</BODY></HTML>";
416 echo $json->encode(array(
420 'message' => $str, // compate with exeption / loadexception.
421 'errors' => $errors ? $errors : true, // used by forms to flag errors.
422 'authFailure' => !empty($errors['authFailure']),
430 require_once 'Services/JSON.php';
431 $json = new Services_JSON();
433 if (!empty($_REQUEST['returnHTML']) ||
434 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
437 header('Content-type: text/html');
438 echo "<HTML><HEAD></HEAD><BODY>";
439 echo $json->encodeUnsafe(array('success'=> true, 'data' => $str));
440 echo "</BODY></HTML>";
445 echo $json->encode(array('success'=> true, 'data' => $str));
449 function jdata($ar,$total=false, $extra=array())
451 // should do mobile checking???
452 if ($total == false) {
455 $extra= $extra ? $extra : array();
456 require_once 'Services/JSON.php';
457 $json = new Services_JSON();
458 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
468 * ---------------- Page output?!?!?
472 function hasBg($fn) // used on front page to check if logos exist..
474 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
477 function outputJavascriptIncludes() // includes on devel version..
480 $mods = explode(',', $this->appModules);
481 array_unshift($mods, 'Core');
482 $mods = array_unique($mods);
484 foreach($mods as $mod) {
485 // add the css file..
487 $files = $this->moduleJavascriptList($mod.'/widgets');
488 foreach($files as $f) {
489 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
492 $files = $this->moduleJavascriptList($mod);
493 foreach($files as $f) {
494 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
501 function outputCSSIncludes() // includes on CSS links.
504 $mods = explode(',', $this->appModules);
505 array_unshift($mods, 'Core');
506 $mods = array_unique($mods);
508 foreach($mods as $mod) {
509 // add the css file..
510 $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
511 if (file_exists( $css)){
512 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
513 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
524 function moduleJavascriptList($mod)
526 $dir = $this->rootDir.'/Pman/'. $mod;
528 $path = $this->rootURL."/Pman/$mod/";
529 $base = dirname($_SERVER['SCRIPT_FILENAME']);
530 $cfile = realpath($base .'/_compiled_/' . $mod . '.js');
531 $lfile = realpath($base .'/_translations_/' . $mod . '.js');
533 if (!file_exists($dir)) {
539 if (file_exists($cfile)) {
540 // $ctime = max(filemtime($cfile), filectime($cfile));
541 // otherwise use compile dfile..
542 $files = array( $this->rootURL."/_compiled_/". basename($cfile));
543 if (file_exists($lfile)) {
544 array_push($files, $this->rootURL."/_translations_/$mod.js");
548 // works out if stuff has been updated..
549 // technically the non-dev version should output compiled only?!!?
550 while (false !== ($f = readdir($dh))) {
551 if (!preg_match('/\.js$/', $f)) {
554 // got the 'module file..'
556 $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
557 $files[] = $path . $f;
559 // var_dump(array($maxtime , $ctime));
560 //if ($maxtime > $ctime) {
561 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
562 usort($files, $lsort);
563 // if (file_exists($lfile)) {
564 // array_unshift($files, $this->rootURL."/_translations_/$mod.js");
574 * ---------------- Logging ---------------
581 function addEvent($act, $obj = false, $remarks = '') {
582 $au = $this->getAuthUser();
583 $e = DB_DataObject::factory('Events');
584 $e->person_name = $au ? $au->name : '';
585 $e->person_id = $au ? $au->id : '';
586 $e->event_when = date('Y-m-d H:i:s');
587 $e->ipaddr = $_SERVER["REMOTE_ADDR"];
589 $e->on_table = $obj ? $obj->tableName() : '';
590 $e->on_id = $obj ? $obj->id : 0;
591 $e->remarks = $remarks;