Exemplo n.º 1
0
    /**
     * A block that is inserted into the "before_submit_button" slot in QuickForms.
     * If the use is not logged in, this displays the recaptcha image just before the 
     * submit button.
     *
     * @return void
     */
    function block__before_submit_button()
    {
        if (class_exists('Dataface_AuthenticationTool')) {
            $auth =& Dataface_AuthenticationTool::getInstance();
            $user =& $auth->getLoggedInUser();
            if ($user) {
                return null;
            }
        }
        if ($this->fieldAdded) {
            return;
        }
        require_once dirname(__FILE__) . '/recaptcha-php/recaptchalib.php';
        $app =& Dataface_Application::getInstance();
        if (!isset($app->_conf['reCAPTCHA']) or !isset($app->_conf['reCAPTCHA']['public_key'])) {
            trigger_error('No public key set for reCAPTCHA.  You need to add a section to your conf.ini file as follows:<br/>
[reCAPTCHA]
    public_key=xxxxxx
    private_key=xxxxxx
    ', E_USER_ERROR);
        }
        $public_key = $app->_conf['reCAPTCHA']['public_key'];
        //echo $public_key; echo "here";exit;
        echo '<div>' . recaptcha_get_html($public_key) . '</div>';
        $this->fieldAdded = true;
    }
Exemplo n.º 2
0
 function handle(&$params)
 {
     // mark the message as read, if hasn't been read yet -job_note_id
     try {
         $app = Dataface_Application::getInstance();
         $query = $app->getQuery();
         $auth =& Dataface_AuthenticationTool::getInstance();
         $user =& $auth->getLoggedInUser();
         $note_id = $query['-job_note_id'];
         $jobNote =& df_get_record("job_notes", array('JobNoteId' => $note_id));
         $job =& df_get_record("jobs", array('job_id' => $jobNote->val('job_id')));
         if (!$job->checkPermission('read message')) {
             throw new Exception("You do not have permission to read this note", E_USER_ERROR);
         }
         require_once 'inc/SweteDb.class.php';
         require_once 'inc/SweteJobInbox.class.php';
         SweteJobInbox::setReadStatic($note_id, $user->val('username'));
     } catch (Exception $e) {
         if ($e->getCode() == E_USER_ERROR) {
             echo $e->getMessage();
         } else {
             throw $e;
         }
     }
 }
Exemplo n.º 3
0
 function handle(&$params)
 {
     try {
         // add a new message to the current job record
         //-content is the new message content
         $app = Dataface_Application::getInstance();
         $query = $app->getQuery();
         $auth =& Dataface_AuthenticationTool::getInstance();
         $user =& $auth->getLoggedInUser();
         $content = trim(htmlspecialchars($query['-content']));
         if (!$content) {
             throw new Exception("No message contents entered.", E_USER_ERROR);
         }
         $job_id = $query['-job_id'];
         $job_rec =& df_get_record("jobs", array('job_id' => $job_id));
         if (!$job_rec->checkPermission('add new related record')) {
             throw new Exception("You do not have permission to add a note to this job.", E_USER_ERROR);
         }
         require_once 'inc/SweteDb.class.php';
         require_once 'inc/SweteJob.class.php';
         require_once 'inc/SweteJobInbox.class.php';
         $job = new SweteJob($job_rec);
         $inbox = $job->getInbox($user->val('username'));
         $noteRec = $inbox->addMessage($content);
     } catch (Exception $e) {
         if ($e->getCode() == E_USER_ERROR) {
             echo $e->getMessage();
         } else {
             throw $e;
         }
     }
 }
Exemplo n.º 4
0
 function handle(&$params)
 {
     try {
         $app =& Dataface_Application::getInstance();
         $query =& $app->getQuery();
         $auth =& Dataface_AuthenticationTool::getInstance();
         $user =& $auth->getLoggedInUser();
         if (!isset($query['-site-id'])) {
             throw new Exception("No site id specified");
         }
         if (isset($query['-compiled'])) {
             if ($query['-compiled'] == 'true' || $query['-compiled'] == 1) {
                 $compiled = 1;
             } else {
                 $compiled = 0;
             }
             $jobs = df_get_records_array('jobs', array('website_id' => $query['-site-id'], 'posted_by' => $user->val('username'), 'compiled' => $compiled));
         } else {
             $jobs = df_get_records_array('jobs', array('website_id' => $query['-site-id'], 'posted_by' => $user->val('username')));
         }
         //array of job ids and job titles to present to user
         $results = array();
         foreach ($jobs as $job) {
             $results[] = array('job_id' => $job->val('job_id'), 'title' => $job->getTitle());
         }
         echo json_encode($results);
     } catch (Exception $e) {
         if ($e->getCode() == E_USER_ERROR) {
             echo $e->getMessage();
         } else {
             throw $e;
         }
     }
 }
Exemplo n.º 5
0
 function setUp()
 {
     SweteDb::q("delete from jobs");
     SweteDb::q("delete from websites");
     $siteRec = new Dataface_Record('websites', array());
     $siteRec->setValues(array('website_name' => 'Live site', 'website_url' => df_absolute_url(DATAFACE_SITE_URL . '/tests/testsites/site2/'), 'source_language' => 'en', 'target_language' => 'fr', 'host' => $_SERVER['HTTP_HOST'], 'base_path' => dirname(DATAFACE_SITE_URL) . '/site2/', 'active' => 1, 'locked' => 0, 'enable_live_translation' => 1));
     $res = $siteRec->save();
     if (PEAR::isError($res)) {
         throw new Exception($res->getMessage(), $res->getCode());
     }
     df_q("delete from site_text_filters where website_id='" . addslashes($siteRec->val('website_id')) . "'");
     $liveSite = new SweteSite($siteRec);
     $this->liveSite = $liveSite;
     $staticSiteRec = new Dataface_Record('websites', array());
     $staticSiteRec->setValues(array('website_name' => 'Static site', 'website_url' => df_absolute_url(DATAFACE_SITE_URL . '/tests/testsites/site1/'), 'source_language' => 'en', 'target_language' => 'fr', 'host' => $_SERVER['HTTP_HOST'], 'base_path' => dirname(DATAFACE_SITE_URL) . '/site1/', 'active' => 1, 'locked' => 0, 'enable_live_translation' => 0));
     $res = $staticSiteRec->save();
     if (PEAR::isError($res)) {
         throw new Exception($res->getMessage(), $res->getCode());
     }
     df_q("delete from site_text_filters where website_id='" . addslashes($staticSiteRec->val('website_id')) . "'");
     $staticSite = new SweteSite($staticSiteRec);
     $this->staticSite = $staticSite;
     $cuser = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
     SweteDb::q("delete from users");
     $cuser->save();
     if (!isset($cuser)) {
         die("You need to be logged in as an admin user for the tests to work");
     }
     $user = new Dataface_Record('users', array());
     $user->setValues(array('username' => 'test_user', 'email' => '*****@*****.**', 'password' => 'foo', 'role_id' => 3));
     $res = $user->save();
     if (PEAR::isError($res)) {
         throw new Exception($res->getMessage(), $res->getCode());
     }
     $this->mainUser = $user;
     $user = new Dataface_Record('users', array());
     $user->setValues(array('username' => 'test_user2', 'email' => '*****@*****.**', 'password' => 'foo', 'role_id' => 3));
     $res = $user->save();
     if (PEAR::isError($res)) {
         throw new Exception($res->getMessage(), $res->getCode());
     }
     $siteRec = $this->liveSite;
     $job = SweteJob::createJob($this->liveSite);
     // Create a translation miss
     $server = new ProxyServer();
     $server->logger->saveBodies = true;
     $server->site = $this->liveSite;
     $server->SERVER = array('REQUEST_METHOD' => 'get');
     $server->URL = $server->site->getProxyUrl() . 'index.html';
     $server->buffer = true;
     $server->logTranslationMisses = true;
     SweteDb::q('commit');
     $server->handleRequest();
     $misses = df_get_records_array('translation_miss_log', array('website_id' => '=' . $siteRec->getRecord()->val('website_id')));
     foreach ($misses as $miss) {
         $job->addTranslationMiss($miss->val('translation_miss_log_id'));
     }
     $this->jobWithTM = $job;
 }
Exemplo n.º 6
0
/**
 * @brief Gets the currently logged in user.
 * @returns {Dataface_Record} Dataface_Record object encapsulating the row from the users
 * table of the currently logged-in user.  If no user is logged in, then this will return
 * null.
 */
function getUser()
{
    static $user = -1;
    if (is_int($user) and $user == -1) {
        $user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
    }
    return $user;
}
Exemplo n.º 7
0
 /**
  * Trigger that is called after new records are inserted.  We will use it to
  * forward to the correct page.
  */
 function after_action_new()
 {
     $auth =& Dataface_AuthenticationTool::getInstance();
     $user =& $auth->getLoggedInUser();
     if (!$user) {
         // The user is not logged in so we forward to a success page.
         header('Location: success.php');
         exit;
     }
 }
Exemplo n.º 8
0
 function getPreferences()
 {
     $auth =& Dataface_AuthenticationTool::getInstance();
     $user =& $auth->getLoggedInUser();
     if (isset($user)) {
         return array('show_tables_menu' => 1);
     } else {
         return array('show_tables_menu' => 0);
     }
 }
Exemplo n.º 9
0
 function getPreferences()
 {
     $app =& Dataface_Application::getInstance();
     $auth =& Dataface_AuthenticationTool::getInstance();
     $user =& $auth->getLoggedInUser();
     if ($user && isAdmin($user->val('role'))) {
         return array();
     } else {
         return array('show_result_stats' => 0, 'show_jump_menu' => 0, 'show_result_controller' => 0, 'show_table_tabs' => 0, 'show_actions_menu' => 0, 'show_tables_menu' => 0, 'show_search' => 0, 'show_record_actions' => 0, 'show_recent_records_menu' => 0, 'show_record_tabs' => 0, 'show_record_tree' => 0, 'show_bread_crumbs' => 0);
     }
 }
Exemplo n.º 10
0
 function beforeHandleRequest()
 {
     $user =& Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
     if ($user and $user->val('role') !== 'ADMIN' or !isset($user)) {
         $app =& Dataface_Application::getInstance();
         // Makes sure that the NavMenu cannot see these tables
         unset($app->_conf['_tables']['users']);
         // Makes sure that a non-admin user cannot access the tables
         // from the browser.
         $app->_conf['_disallowed_tables']['hide_admin4'] = 'users';
     }
 }
Exemplo n.º 11
0
 function handle(&$params)
 {
     $app =& Dataface_Application::getInstance();
     $auth =& Dataface_AuthenticationTool::getInstance();
     if ($auth->isLoggedIn()) {
         // forward to the user's profile
         $user =& $auth->getLoggedInUser();
         $app->redirect($user->getURL());
         exit;
     } else {
         $app->redirect($app->url('-action=login_prompt') . '&--msg=' . urlencode('Sorry, this action is only available to logged in users'));
     }
 }
Exemplo n.º 12
0
 function handle(&$params)
 {
     // retrieve the message contents for -job_note_id
     $app = Dataface_Application::getInstance();
     $query = $app->getQuery();
     $auth =& Dataface_AuthenticationTool::getInstance();
     $user =& $auth->getLoggedInUser();
     $note_id = $query['-job_note_id'];
     require_once 'inc/SweteDb.class.php';
     require_once 'inc/SweteJobInbox.class.php';
     $message = SweteJobInbox::getMessageStatic($note_id, $user->val('username'));
     echo nl2br($message->note_content);
 }
Exemplo n.º 13
0
 function handle($params)
 {
     $app = Dataface_Application::getInstance();
     $user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
     $username = Dataface_AuthenticationTool::getInstance()->getLoggedInUserName();
     if (!isset($user)) {
         header('HTTP/1.0 401 Please Login');
         header('Content-type: text/json; charset="' . $app->_conf['oe'] . '"');
         echo json_encode(array('code' => 401, 'message' => 'You are not logged in'));
         exit;
     } else {
         header('Content-type: text/json; charset="' . $app->_conf['oe'] . '"');
         echo json_encode(array('code' => 200, 'message' => 'You are not logged in as ' . $username, 'username' => $username));
         exit;
     }
 }
Exemplo n.º 14
0
function getPermissions($record)
{
    $user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
    // If user is an admin defer to the application delegate class for
    // permissions
    if ($user and $user->val('role') == 'ADMIN') {
        return null;
    } elseif ($user and $user->val('role') == 'REGULAR') {
        return Dataface_PermissionsTool::getRolePermissions('REGULAR');
    }
    if ($user) {
        // User is logged in
        return Dataface_PermissionsTool::READ_ONLY();
    }
    // Defer to the application delegate class for all other users
    return null;
}
Exemplo n.º 15
0
 function handle(&$params)
 {
     // returns html for a table with all the messages for -job_id
     $app = Dataface_Application::getInstance();
     $query = $app->getQuery();
     $auth =& Dataface_AuthenticationTool::getInstance();
     $user =& $auth->getLoggedInUser();
     $job_id = $query['-job_id'];
     $job =& df_get_record("jobs", array('job_id' => $job_id));
     require_once 'inc/SweteDb.class.php';
     require_once 'inc/SweteJob.class.php';
     require_once 'inc/SweteJobInbox.class.php';
     require_once 'inc/SweteJobInboxPresentation.php';
     $sweteJob = new SweteJob($job);
     $messageList = $sweteJob->getInbox($user->val('username'))->getMessageList();
     echo SweteJobInboxPresentation::tableContent($messageList);
 }
Exemplo n.º 16
0
 function handle(&$params)
 {
     import('Dataface/XMLTool.php');
     $xml = new Dataface_XMLTool();
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     $table =& Dataface_Table::loadTable($query['-table']);
     echo $xml->header();
     $auth =& Dataface_AuthenticationTool::getInstance();
     echo "<![CDATA[";
     print_r($_SESSION);
     echo "]]>";
     echo "<user>" . $auth->getLoggedInUsername() . "</user>";
     echo $xml->toXML($table);
     //echo $xml->toXML($app->getRecord());
     echo $xml->toXML($app->getResultSet());
     echo $xml->footer();
     exit;
 }
Exemplo n.º 17
0
    function handle($params)
    {
        $app = Dataface_Application::getInstance();
        $auth = Dataface_AuthenticationTool::getInstance();
        $user = $auth->getLoggedInUser();
        $username = $auth->getLoggedInUsername();
        if (!$user or !$username) {
            return Dataface_Error::permissionDenied('You must be logged in to change your password');
        }
        if ($_POST) {
            try {
                if (!@$_POST['--password1'] || !@$_POST['--password2']) {
                    throw new Exception("Please enter your new password in both fields provided.");
                }
                if (!@$_POST['--current-password']) {
                    throw new Exception("Please enter your current password in the field provided.");
                }
                $_REQUEST['UserName'] = $username;
                $_REQUEST['Password'] = $_POST['--current-password'];
                if (!$auth->checkCredentials()) {
                    throw new Exception("The password you entered is incorrect.  Please try again.");
                }
                if (strcmp($_POST['--password1'], $_POST['--password2']) !== 0) {
                    throw new Exception("Your new passwords don't match.  Please ensure that you retype your new password correctly.");
                }
                $res = $auth->setPassword($_POST['--password1']);
                $this->out(array('code' => 200, 'message' => 'Your password has been successfully changed'));
                exit;
            } catch (Exception $ex) {
                $this->out(array('code' => $ex->getCode(), 'message' => $ex->getMessage()));
                exit;
            }
        } else {
            $app->addHeadContent(sprintf('<link rel="stylesheet" type="text/css" href="%s"/>
				<script src="%s"></script>
				<script src="%s"></script>', htmlspecialchars(DATAFACE_URL . '/css/change_password.css'), htmlspecialchars(DATAFACE_URL . '/js/jquery.packed.js'), htmlspecialchars(DATAFACE_URL . '/js/change_password.js')));
            df_display(array(), 'change_password.html');
        }
    }
Exemplo n.º 18
0
 function handle($params)
 {
     $app = Dataface_Application::getInstance();
     $auth = Dataface_AuthenticationTool::getInstance();
     $user = $auth->getLoggedInUser();
     $username = $auth->getLoggedInUsername();
     if (!$user or !$username) {
         return Dataface_Error::permissionDenied('You must be logged in to change your password');
     }
     if ($_POST) {
         try {
             if (!@$_POST['--password1'] || !@$_POST['--password2']) {
                 throw new Exception("Please enter your new password in both fields provided.");
             }
             if (!@$_POST['--current-password']) {
                 throw new Exception("Please enter your current password in the field provided.");
             }
             $_REQUEST['UserName'] = $username;
             $_REQUEST['Password'] = $_POST['--current-password'];
             if (!$auth->checkCredentials()) {
                 throw new Exception("The password you entered is incorrect.  Please try again.");
             }
             if (strcmp($_POST['--password1'], $_POST['--password2']) !== 0) {
                 throw new Exception("Your new passwords don't match.  Please ensure that you retype your new password correctly.");
             }
             $res = $auth->setPassword($_POST['--password1']);
             $this->out(array('code' => 200, 'message' => 'Your password has been successfully changed'));
             exit;
         } catch (Exception $ex) {
             $this->out(array('code' => $ex->getCode(), 'message' => $ex->getMessage()));
             exit;
         }
     } else {
         $jt = Dataface_JavascriptTool::getInstance();
         $jt->import('change_password.js');
         df_display(array(), 'change_password.html');
     }
 }
Exemplo n.º 19
0
 function handle(&$params)
 {
     //echo "Hello World from the controller class!!";
     //to do interesting stuff here we get info from the Dataface_Application object
     $app =& Dataface_Application::getInstance();
     // reference to Dataface_Application object
     $auth =& Dataface_AuthenticationTool::getInstance();
     // reference to Dataface_Authentication object
     //if ( !isset($_POST['--bid-amount']) ) {
     //$request =& $app->getQuery();  // Request vars:  e.g. [-table]=>'Students', [-action]=>'hello'
     $records =& df_get_records('detail', $query);
     $user =& $auth->getLoggedInUser();
     // Dataface_Record object of currently logged in user.
     $current_tablename =& $request['-table'];
     $current_record =& $app->getRecord();
     // Currently selected record (Dataface_Record object)
     $results =& $app->getResultSet();
     // Current found set (Dataface_QueryTool object).
     // Iterating through the results
     $it =& $results->iterator();
     while ($it->hasNext()) {
         $record =& $it->next();
         // $record is a Dataface_Record object
         print_r($record->strvals());
         unset($record);
         // necessary so that PHP doesn't just keep overwriting the same object.
     }
     // Perform a custom SQL Query:
     //$res = mysql_query("select * from foo inner join bar on foo.x=bar.y", $app->db());
     // .. etc ...
     // Obtain parameters from the actions.ini file for this action:
     $template_name = $params['action']['template'];
     // The value of the template parameter
     //df_display(array(), $template_name);  // this form allows you to change the template to use by modifying the actions.ini file.
     df_display(array(), 'JobWorld.html');
 }
Exemplo n.º 20
0
 function memcache_get_key($sql, $lang)
 {
     $app =& Dataface_Application::getInstance();
     $auth =& Dataface_AuthenticationTool::getInstance();
     $dbname = $app->_conf['_database']['name'];
     if (!isset($lang)) {
         $lang = $app->_conf['lang'];
     }
     $key = urlencode($dbname) . '?-query=' . urlencode($sql) . '&-lang=' . urlencode($lang);
     return md5($key);
 }
Exemplo n.º 21
0
    public function reset_password_with_uuid($uuid)
    {
        $auth = Dataface_AuthenticationTool::getInstance();
        $app = Dataface_Application::getInstance();
        $del = $app->getDelegate();
        $this->create_reset_password_table();
        $this->clear_expired();
        $table = self::$TABLE_RESET_PASSWORD;
        $res = xf_db_query("select * from `{$table}` where request_uuid='" . addslashes($uuid) . "' limit 1", df_db());
        if (!$res) {
            throw new Exception(xf_db_error(df_db()));
        }
        $row = xf_db_fetch_assoc($res);
        if (!$row) {
            throw new Exception(df_translate('actions.forgot_password.no_such_reset_request_found', "No such reset request could be found"), self::$EX_NO_SUCH_UUID);
        }
        if (!$row['username']) {
            throw new Exception(df_translate('actions.forgot_password.attempt_to_reset_for_null_username', "Attempt to reset password for user with null username"), self::$EX_NO_USERNAME_FOR_USER);
        }
        $username = $row['username'];
        @xf_db_free_result($res);
        // now that we have the username, let's reset the password.
        //$rand = strval(rand())."".$uuid;
        $rand = md5($uuid);
        error_log("Rand is " . $rand);
        $pw = '';
        for ($i = 0; $i <= 16; $i += 2) {
            $pw .= $rand[$i];
        }
        $password = $pw;
        if (isset($del) and method_exists($del, 'generateTemporaryPassword')) {
            $pw = $del->generateTemporaryPassword();
            if ($pw) {
                $password = $pw;
            }
        }
        //error_log("Password is $password");
        $user = df_get_record($auth->usersTable, array($auth->usernameColumn => '=' . $username));
        if (!$user) {
            throw new Exception(df_translate('actions.forgot_password.no_account_for_username', "No user account found with that username"), self::$EX_USER_NOT_FOUND);
        }
        $emailColumn = $auth->getEmailColumn();
        if (!$emailColumn) {
            throw new Exception(df_translate('actions.forgot_password.no_email_column_found_short', "No email column found in the users table"), self::$EX_NO_EMAIL_COLUMN_FOUND);
        }
        $email = $user->val($emailColumn);
        if (!$email) {
            throw new Exception(df_translate('actions.forgot_password.user_without_email_long', "User has account has no email address on record.  Please contact support to reset the password"), self::$EX_NO_EMAIL_FOR_USER);
        }
        $user->setValue($auth->passwordColumn, $password);
        $res = $user->save();
        if (PEAR::isError($res)) {
            throw new Exception($res->getMessage());
        }
        // Let's delete this request from the password reset requests.
        $this->delete_request_with_uuid($uuid);
        // Now let's send the email.
        $del = $app->getDelegate();
        $info = array();
        if (isset($del) and method_exists($del, 'getPasswordChangedEmailInfo')) {
            $info = $del->getPasswordChangedEmailInfo($user, $password);
        }
        $subject = df_translate('actions.forgot_password.password_changed', "Password Changed");
        if (isset($info['subject'])) {
            $subject = $info['subject'];
        }
        $site_url = df_absolute_url(DATAFACE_SITE_HREF);
        $msg = df_translate('actions.forgot_password.new_temporary_password_email_body', <<<END
Your new temporary password is
{$password}

You can change your password as follows:

1. Log in with your temporary password at <{$site_url}?-action=login>
2. Click on the "My Profile" link in the upper right of the page
3. Click on the "Edit" tab.
4. Change your password in the edit form and click "Save" when done.
END
, array('password' => $password, 'site_url' => $site_url));
        if (isset($info['message'])) {
            $msg = $info['message'];
        }
        $parameters = null;
        if (isset($info['parameters'])) {
            $parameters = $info['parameters'];
        }
        $site_title = $app->getSiteTitle();
        $support_email = $_SERVER['SERVER_ADMIN'];
        if (isset($app->_conf['admin_email'])) {
            $support_email = $app->_conf['admin_email'];
        }
        if (isset($app->_conf['support_email'])) {
            $support_email = $app->_conf['support_email'];
        }
        $headers = 'From: ' . $site_title . ' <' . $support_email . '>' . "\r\nReply-to: " . $site_title . " <" . $support_email . ">" . "\r\nContent-type: text/plain; charset=" . $app->_conf['oe'];
        if (isset($info['headers'])) {
            $headers = $info['headers'];
        }
        if (@$app->_conf['_mail']['func']) {
            $func = $app->_conf['_mail']['func'];
        } else {
            $func = 'mail';
        }
        $res = $func($email, $subject, $msg, $headers, $parameters);
        if (!$res) {
            return PEAR::raiseError(df_translate('actions.forgot_password.failed_send_activation', "Failed to send activation email.  Please try again later."), DATAFACE_E_ERROR);
        } else {
            return true;
        }
    }
Exemplo n.º 22
0
 /**
  * Obtains reference to the authentication tool.
  */
 function &getAuthenticationTool()
 {
     $null = null;
     if (!isset($this->authenticationTool)) {
         if (isset($this->_conf['_auth'])) {
             import('Dataface/AuthenticationTool.php');
             $this->authenticationTool = Dataface_AuthenticationTool::getInstance($this->_conf['_auth']);
         } else {
             return $null;
         }
     }
     return $this->authenticationTool;
 }
Exemplo n.º 23
0
 /**
  * Saves a page into the database.  This will save both the raw text and
  * a gzipped version (if the zlib extension is present).
  *
  * @param $params An associative array of parameters:
  *		@param id 	The Page id to store this data as.  This is a required field
  *				  	It is stored as a VARCHAR(64) so it can be any string not
  *					longer than 64 characters.
  *		@param data The content of the page to be cached.   Required.
  *		@param lang	The language of the content. Optional.  Will default to 
  *					the currently selected language ($app->_conf['lang']).
  *		@param user The username of the user that this page is cached for.
  *					Defaults to currently logged in user.
  *		@param expires	The unix timestamp when this page will expire. Optional.
  *						Defaults to NOW + $this->lifeTime (usually 3600 seconds).
  *		@param tables	An array or comma-delimited list of table names that
  *						This page depends on.  If these tables have been updated
  *						after the cache is created then the cache is invalidated.
  *		@randomize		An optional integer number of versions of this page
  *						that should stay on random rotation.
  */
 function cachePage($params = array())
 {
     $PageID = $this->getPageID($params);
     if (!isset($params['data'])) {
         trigger_error('Missing parameter "data": ' . Dataface_Error::printStackTrace(), E_USER_ERROR);
     }
     $Data = $params['data'];
     $Language = isset($params['lang']) ? $params['lang'] : $this->app->_conf['lang'];
     if (class_exists('Dataface_AuthenticationTool')) {
         $auth =& Dataface_AuthenticationTool::getInstance();
         $UserID = isset($params['user']) ? $params['user'] : $auth->getLoggedInUsername();
     } else {
         $UserID = null;
     }
     $Expires = isset($params['expires']) ? $params['expires'] : time() + $this->lifeTime;
     $tables = isset($params['tables']) ? $params['tables'] : '';
     $Dependencies = is_array($tables) ? implode(',', $tables) : $tables;
     if ($this->useGzipCompression && extension_loaded('zlib')) {
         // If we are using GZIP compression then we will use zlib library
         // functions (gzcompress) to compress the data also for storage
         // in the database.
         // Apparently we have to play with the headers and footers of the
         // gzip file for it to work properly with the web browsers.
         // see http://ca.php.net/gzcompress user comments.
         $size = strlen($Data);
         $crc = crc32($Data);
         /*
         $Data_gz = "\x1f\x8b\x08\x00\x00\x00\x00\x00".
         			substr(gzcompress($Data,9),0, $size-4).
         			$this->_gzipGetFourChars($crc).
         			$this->_gzipGetFourChars($size);
         */
         /* Fix for IE compatibility .. seems to work for mozilla too. */
         $Data_gz = "‹" . substr(gzcompress($Data, 9), 0, $size);
     }
     if (isset($params['randomize']) and $params['randomize']) {
         // We are keeping multiple versions of this page so that we can
         // show them on a random rotation.  This is to simulate dynamicism
         // while still caching pages.
         // Basically the following query will delete existing cached versions
         // of this page except for the most recent X versions - where X
         // is the number specified in the $randomize parameter.  The
         // $randomize parameter is the number of versions of this page
         // that should be used on random rotation.
         $res = mysql_query("\n\t\t\t\tDELETE FROM `" . addslashes($this->tableName) . "`\n\t\t\t\tWHERE \n\t\t\t\t\t`PageID`='" . addslashes($PageID) . "' AND\n\t\t\t\t\t`Language`='" . addslashes($Language) . "' AND\n\t\t\t\t\t`UserID`='" . addslashes($UserID) . "' AND\n\t\t\t\t\t`GenID` NOT IN (\n\t\t\t\t\t\tSELECT `GenID` FROM `" . addslashes($this->tableName) . "`\n\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t`PageID`='" . addslashes($PageID) . "' AND\n\t\t\t\t\t\t\t`Language`='" . addslashes($Language) . "' AND\n\t\t\t\t\t\t\t`UserID`='" . addslashes($UserID) . "'\n\t\t\t\t\t\tORDER BY\n\t\t\t\t\t\t\t`LastModified` desc\n\t\t\t\t\t\tLIMIT " . (intval($params['randomize']) - 1) . "\n\t\t\t\t)", $this->app->db());
         if (!$res) {
             trigger_error(mysql_error($this->app->db()), E_USER_ERROR);
         }
     } else {
         // We are not randomizing.  We delete any existing pages.
         $res = mysql_query("\n\t\t\t\tDELETE FROM `" . addslashes($this->tableName) . "`\n\t\t\t\tWHERE\n\t\t\t\t\t`PageID`='" . addslashes($PageID) . "' AND\n\t\t\t\t\t`Language`='" . addslashes($Language) . "' AND\n\t\t\t\t\t`UserID`='" . addslashes($UserID) . "'", $this->app->db());
         if (!$res) {
             trigger_error(mysql_error($this->app->db()), E_USER_ERROR);
         }
     }
     // Get the headers so we can reproduce them properly.
     if (function_exists('headers_list')) {
         //$headers = serialize(headers_list());
         $headers = headers_list();
         $hout = array();
         foreach ($headers as $h) {
             if (preg_match('/^(?:Content-Type|Content-Language|Content-Location|Content-Disposition|P3P):/i', $h)) {
                 $hout[] = $h;
             }
         }
         $headers = $hout;
     } else {
         $headers = array();
     }
     // Now we can insert the cached page.
     $sql = "\n\t\t\tINSERT INTO `" . addslashes($this->tableName) . "`\n\t\t\t(`PageID`,`Language`,`UserID`,`Dependencies`,`Expires`,`Data`,`Data_gz`, `Headers`)\n\t\t\tVALUES\n\t\t\t('" . addslashes($PageID) . "',\n\t\t\t '" . addslashes($Language) . "',\n\t\t\t '" . addslashes($UserID) . "',\n\t\t\t '" . addslashes($Dependencies) . "',\n\t\t\t FROM_UNIXTIME('" . addslashes($Expires) . "'),\n\t\t\t '" . addslashes($Data) . "',\n\t\t\t '" . addslashes($Data_gz) . "',\n\t\t\t '" . addslashes(serialize($headers)) . "'\n\t\t\t)";
     //file_put_contents('/tmp/dump.sql',$sql);
     $res = mysql_query($sql, $this->app->db());
     if (!$res) {
         trigger_error(mysql_error($this->app->db()), E_USER_ERROR);
     }
     if (@$this->app->_conf['_output_cache']['cachedir']) {
         $filename = DATAFACE_SITE_PATH . '/' . $this->app->_conf['_output_cache']['cachedir'];
         $dir = $PageID[0];
         $filename = $filename . '/' . $dir;
         if (!file_exists($filename)) {
             mkdir($filename, 0777);
         }
         $filename .= '/' . $PageID . '-' . md5($Language . '-' . $UserID);
         if (file_exists($filename)) {
             @unlink($filename);
         }
         //echo "Opening $filename";
         $fh = fopen($filename, 'w');
         if ($fh) {
             fwrite($fh, $Data);
             fclose($fh);
         }
         $fh = fopen($filename . '.gz', 'w');
         if ($fh) {
             fwrite($fh, $Data_gz);
             fclose($fh);
         }
     }
 }
Exemplo n.º 24
0
 function handle(&$params)
 {
     $this->params =& $params['action'];
     unset($params);
     $params =& $this->params;
     Dataface_PermissionsTool::getInstance()->setDelegate(new dataface_actions_register_permissions_delegate());
     $app =& Dataface_Application::getInstance();
     $auth =& Dataface_AuthenticationTool::getInstance();
     import('Dataface/Ontology.php');
     Dataface_Ontology::registerType('Person', 'Dataface/Ontology/Person.php', 'Dataface_Ontology_Person');
     $this->ontology =& Dataface_Ontology::newOntology('Person', $app->_conf['_auth']['users_table']);
     $atts =& $this->ontology->getAttributes();
     $query =& $app->getQuery();
     if (!is_array(@$app->_conf['_auth'])) {
         return PEAR::raiseError("Cannot register when authentication is not enabled.", DATAFACE_E_ERROR);
     }
     if (isset($app->_conf['_auth']['email_column'])) {
         $atts['email'] =& $this->ontology->table->getField($app->_conf['_auth']['email_column']);
         $this->fieldnames['email'] = $app->_conf['_auth']['email_column'];
     }
     if ($auth->isLoggedIn()) {
         return Dataface_Error::permissionDenied("Sorry you cannot register once you are logged in.  If you want to register, you must first log out.");
     }
     if (!@$app->_conf['_auth']['allow_register']) {
         return PEAR::raiseError("Sorry, registration is not allowed.  Please contact the administrator for an account.", DATAFACE_E_ERROR);
     }
     $pt =& Dataface_PermissionsTool::getInstance();
     // Create a new record form on the users table
     $this->form =& df_create_new_record_form($app->_conf['_auth']['users_table']);
     // add the -action element so that the form will direct us back here.
     $this->form->addElement('hidden', '-action');
     $this->form->setDefaults(array('-action' => $query['-action']));
     // Check to make sure that there isn't another user with the same
     // username already.
     $validationResults = $this->validateRegistrationForm($_POST);
     if (count($_POST) > 0 and PEAR::isError($validationResults)) {
         $app->addMessage($validationResults->getMessage());
         $this->form->_errors[$app->_conf['_auth']['username_column']] = $validationResults->getMessage();
     }
     if (!PEAR::isError($validationResults) and $this->form->validate()) {
         // The form input seems OK.  Let's process the form
         // Since we will be using our own form processing for this action,
         // we need to manually push the field inputs into the Dataface_Record
         // object.
         $this->form->push();
         // Now we obtain the Dataface_Record object that is to be added.
         $rec =& $this->form->_record;
         $delegate =& $rec->_table->getDelegate();
         // Give the delegate classes an opportunity to have some fun
         if (isset($delegate) and method_exists($delegate, 'beforeRegister')) {
             $res = $delegate->beforeRegister($rec);
             if (PEAR::isError($res)) {
                 return $res;
             }
         }
         $appdel =& $app->getDelegate();
         if (isset($appdel) and method_exists($appdel, 'beforeRegister')) {
             $res = $appdel->beforeRegister($rec);
             if (PEAR::isError($res)) {
                 return $res;
             }
         }
         // This is where we actually do the processing.  This passes control
         // to the processRegistrationForm method in this class.
         $res = $this->form->process(array(&$this, 'processRegistrationForm'), true);
         // If there was an error in processing mark the error, and show the
         // form again.  Otherwise we just redirect to the next page and
         // let the user know that he was successful.
         if (PEAR::isError($res)) {
             $app->addError($res);
         } else {
             // Let the delegate classes perform their victory lap..
             if (isset($delegate) and method_exists($delegate, 'afterRegister')) {
                 $res = $delegate->afterRegister($rec);
                 if (PEAR::isError($res)) {
                     return $res;
                 }
             }
             if (isset($appdel) and method_exists($appdel, 'afterRegister')) {
                 $res = $appdel->afterRegister($rec);
                 if (PEAR::isError($res)) {
                     return $res;
                 }
             }
             // We accept --redirect markers to specify which page to redirect
             // to after we're done.  This will usually be the page that the
             // user was on before they went to the login page.
             if (isset($_SESSION['--redirect'])) {
                 $url = $_SESSION['--redirect'];
             } else {
                 if (isset($_SESSION['-redirect'])) {
                     $url = $_SESSION['-redirect'];
                 } else {
                     if (isset($_REQUEST['--redirect'])) {
                         $url = $_REQUEST['--redirect'];
                     } else {
                         if (isset($_REQUEST['-redirect'])) {
                             $url = $_REQUEST['-redirect'];
                         } else {
                             $url = $app->url('-action=' . $app->_conf['default_action']);
                         }
                     }
                 }
             }
             if (@$params['email_validation']) {
                 $individual = $this->ontology->newIndividual($this->form->_record);
                 $msg = df_translate('actions.register.MESSAGE_THANKYOU_PLEASE_VALIDATE', 'Thank you. An email has been sent to ' . $individual->strval('email') . ' with instructions on how to complete the registration process.', array('email' => $individual->strval('email')));
             } else {
                 // To save the user from having to log in after he has just filled
                 // in the registration form, we will just log him in right here.
                 $_SESSION['UserName'] = $this->form->exportValue($app->_conf['_auth']['username_column']);
                 $msg = df_translate('actions.register.MESSAGE_REGISTRATION_SUCCESSFUL', "Registration successful.  You are now logged in.");
             }
             // Now we actually forward to the success page along with a success message
             if (strpos($url, '?') === false) {
                 $url .= '?';
             }
             $app->redirect($url . '&--msg=' . urlencode($msg));
         }
     }
     // We want to display the form, but not yet so we will use an output buffer
     // to store the form HTML in a variable and pass it to our template.
     ob_start();
     $this->form->display();
     $out = ob_get_contents();
     ob_end_clean();
     $context = array('registration_form' => $out);
     // We don't want to keep the registration page in history, because we want to
     // be able to redirect the user back to where he came from before registering.
     $app->prefs['no_history'] = true;
     df_display($context, 'Dataface_Registration.html');
 }
Exemplo n.º 25
0
 /**
  * Backs up a record to the history table. This will automatically happen
  * when using Dataface_IO::save() if the [history] section exists in the 
  * conf.ini file.
  *
  * @param Dataface_Record &$record The record that is being backed up.
  * @param string $comments  Comments about this version to be stored.
  * @param string $lang The 2-digit language code of which language
  * 				 to use to back up this record.  If none is specified
  *				 then the current language of the system will be used.
  * @param integer $state Unused as yet.  Was intended to store state/workflow
  *				 information.. but ..
  * @returns integer The history id of the resulting history record.
  */
 function logRecord(&$record, $comments = '', $lang = null, $state = null)
 {
     $app =& Dataface_Application::getInstance();
     if (!isset($lang)) {
         $lang = $app->_conf['lang'];
     }
     if (!isset($state)) {
         $state = 0;
     }
     $fieldnames = array_keys($record->_table->fields());
     $sql = 'select `' . implode('`,`', $fieldnames) . '` from `' . $record->_table->tablename . '` where';
     $keynames = array_keys($record->_table->keys());
     $where_clauses = array();
     foreach ($keynames as $keyname) {
         $where_clauses[] = '`' . $keyname . '`=\'' . addslashes($record->strval($keyname)) . '\'';
     }
     $sql .= ' ' . implode(' and ', $where_clauses);
     if (@$app->_conf['multilingual_content']) {
         $db =& Dataface_DB::getInstance();
         $sql = $db->translate_query($sql, $lang);
         $sql = $sql[0];
     }
     $auth =& Dataface_AuthenticationTool::getInstance();
     $userRecord =& $auth->getLoggedInUser();
     if (!isset($userRecord)) {
         $user = null;
     } else {
         $user = $auth->getLoggedInUsername();
     }
     $insertsql = "insert into `" . $this->logTableName($record->_table->tablename) . "` \n\t\t\t(`" . implode('`,`', $fieldnames) . "`, `history__language`,`history__comments`,`history__user`,`history__state`,`history__modified`) \n\t\t\tselect *, '" . addslashes($lang) . "','" . addslashes($comments) . "','" . addslashes($user) . "','" . addslashes($state) . "', NOW() \n\t\t\tfrom (" . $sql . ") as t";
     $res = xf_db_query($insertsql, $app->db());
     if (!$res) {
         $this->updateHistoryTable($record->_table->tablename);
         $res = xf_db_query($insertsql, $app->db());
     }
     if (!$res) {
         echo $insertsql;
         trigger_error(xf_db_error($app->db()), E_USER_ERROR);
     }
     // Now for the individual fields
     $hid = xf_db_insert_id($app->db());
     foreach ($fieldnames as $fieldname) {
         $this->logField($record, $fieldname, $hid);
     }
     return $hid;
 }
Exemplo n.º 26
0
 function df_is_logged_in()
 {
     return class_exists('Dataface_AuthenticationTool') and $auth = Dataface_AuthenticationTool::getInstance() and $auth->isLoggedIn();
 }
Exemplo n.º 27
0
 function parse_ini_file($path, $sections = false)
 {
     static $config = 0;
     if (!is_array($config)) {
         $config = array();
     }
     $app =& Dataface_Application::getInstance();
     //echo "Checking for $path";
     if (strstr($path, 'db:') == $path) {
         $path = substr($path, 3);
         if (!is_array($config)) {
             $config = array();
             if (class_exists('Dataface_AuthenticationTool')) {
                 $auth =& Dataface_AuthenticationTool::getInstance();
                 $username = $auth->getLoggedInUsername();
             } else {
                 $username = null;
             }
             $sql = $this->buildConfigQuery($path, $username, $app->_conf['lang']);
             $res = @xf_db_query($sql, $app->db());
             if (!$res) {
                 $this->createConfigTable();
                 $res = xf_db_query($sql, $app->db());
             }
             if (!$res) {
                 return $config;
             }
             while ($row = xf_db_fetch_assoc($res)) {
                 if (!$row['section']) {
                     $config[$row['file']][$row['key']] = $row['value'];
                 } else {
                     $config[$row['file']][$row['section']][$row['key']] = $row['value'];
                 }
             }
             @xf_db_free_result($res);
         }
         if (!@$config[$path]) {
             return array();
         }
         return $config[$path];
     } else {
         if (@$_GET['--refresh-apc'] or !(DATAFACE_EXTENSION_LOADED_APC && filemtime($path) < apc_fetch($this->apc_hash() . $path . '__mtime') && ($config[$path] = apc_fetch($this->apc_hash() . $path)))) {
             //$config[$path] =  parse_ini_file($path, $sections);
             $config[$path] = INIParser::parse_ini_file($path, $sections);
             if (DATAFACE_EXTENSION_LOADED_APC) {
                 apc_store($this->apc_hash() . $path, $config[$path]);
                 apc_store($this->apc_hash() . $path . '__mtime', time());
             }
         } else {
             //
         }
         return $config[$path];
     }
 }
Exemplo n.º 28
0
 function savePreference($uri, $key, $value, $username = null)
 {
     // First let's find out the username of the user who is currently logged
     // in because we may want to do some clever cacheing/clearing of caches
     // if we are setting the preferences for the currently logged in user.
     $loggedInUsername = null;
     if (class_exists('Dataface_AuthenticationTool')) {
         $auth =& Dataface_AuthenticationTool::getInstance();
         if ($auth->isLoggedIn()) {
             $loggedInUsername = $auth->getLoggedInUsername();
         }
     }
     // If no user was specified, we will set the preferences for the
     // currently logged in user.
     if (!isset($username)) {
         $username = $loggedInUsername;
     }
     // If we are setting preferences for the currently logged in user,
     // then we will update the caches as well.
     // We also do this for users who aren't logged in.
     if ($username == $loggedInUsername or !isset($username)) {
         //$prefs =& $this->getPreferences($uri);
         //$prefs[$key] = $value;
         $this->cachedPrefs[$uri][$key] = $value;
         $this->prefs[$uri][$key] = $value;
     }
     $parts = df_parse_uri($uri);
     if ($username == '*') {
         // If we are making changes to all users, we should clear our
         // own preference caches for this table.
         unset($this->cachedPrefs[$uri]);
         unset($this->prefs[$parts['table']]);
         unset($this->prefs['*']);
     }
     if ($uri == '*' and isset($username)) {
         // If we are updating preferences on ALL records, then we should
         // need to clear all caches.
         $this->prefs = array();
         $this->cachedPrefs = array();
         $this->refreshTimes = array();
     }
     if (isset($username)) {
         // First we have to delete conflicts.
         // If we are setting a global value (ie a value for all tables)
         // we will clear out all previous values.
         $sql = "delete from `dataface__preferences` where `key` = '" . addslashes($key) . "' ";
         if ($uri != '*') {
             if ($parts['table'] != $uri) {
                 $sql .= " and `record_id` = '" . addslashes($uri) . "'";
             } else {
                 $sql .= " and `table` = '" . addslashes($parts['table']) . "'";
             }
         }
         if ($username != '*') {
             $sql .= " and `username` = '" . addslashes($username) . "'";
         }
         $res = mysql_query($sql, df_db());
         if (!$res) {
             $this->_createPreferencesTable();
             $res = mysql_query($sql, df_db());
             if (!$res) {
                 trigger_error(mysql_error(df_db()), E_USER_ERROR);
             }
         }
         $sql = "insert into `dataface__preferences` \n\t\t\t\t(`table`,`record_id`,`username`,`key`,`value`) values\n\t\t\t\t('" . addslashes($parts['table']) . "','" . addslashes($uri) . "','" . addslashes($username) . "','" . addslashes($key) . "','" . addslashes($value) . "')";
         $res = mysql_query($sql, df_db());
         if (!$res) {
             $this->createPreferencesTable();
             $res = mysql_query($sql, df_db());
             if (!$res) {
                 trigger_error(mysql_error(df_db()), E_USER_ERROR);
             }
         }
     }
 }
Exemplo n.º 29
0
 /**
  * Sets a security filter on the table.  A security filter is an array of
  * key/value pairs that are automatically added to any query of this table
  * to limit the results.
  *
  * @example
  * <code>
  * $table->setSecurityFilter(array('schoolID'=>10));
  *		// Will only show results where schoolID is 10
  * </code>
  */
 function setSecurityFilter($filter = null)
 {
     if (!isset($filter)) {
         $filter = array();
         $app =& Dataface_Application::getInstance();
         $query =& $app->getQuery();
         if (class_exists('Dataface_AuthenticationTool')) {
             $auth =& Dataface_AuthenticationTool::getInstance();
             $user =& $auth->getLoggedInUser();
         } else {
             $auth = null;
             $user = null;
         }
         foreach ($this->_filters as $key => $value) {
             if (isset($this->_securityFilter[$key])) {
                 continue;
             }
             if ($value[0] == '$') {
                 if (!$user and strpos($value, '$user') !== false) {
                     continue;
                 }
                 eval('$filter[$key] = "=".' . $value . ';');
             } else {
                 if (substr($value, 0, 4) == 'php:') {
                     if (!$user and strpos($value, '$user') !== false) {
                         continue;
                     }
                     eval('$filter[$key] = "=".' . substr($value, 4) . ';');
                 } else {
                     $filter[$key] = "=" . $value;
                 }
             }
         }
     }
     $this->_securityFilter = $filter;
 }
Exemplo n.º 30
0
 /**
  * @brief Gets the roles that are assigned to the currently logged-in
  * user using the group_permissions module.
  * @return String[] An array of role names assigned to this user.
  */
 function getGroupRoles()
 {
     if (isset($this->pouch['__roles__'])) {
         return $this->pouch['__roles__'];
     }
     if (!$this->table()->hasField('__roles__')) {
         return null;
     }
     $perms = $this->_metaDataValues['__roles__'];
     if (!trim($perms)) {
         $this->pouch['__roles__'] = array();
         return null;
     }
     $perms = json_decode($perms);
     if (!$perms) {
         $this->pouch['__roles__'] = array();
         return null;
     }
     if (!class_exists('Dataface_AuthenticationTool')) {
         $this->pouch['__roles__'] = array();
         return null;
     }
     $authTool = Dataface_AuthenticationTool::getInstance();
     // Todo get user groups
     $groups = $authTool->getUserGroupNames();
     $userName = $authTool->getLoggedInUserName();
     if (!$userName) {
         $userName = '******';
     }
     $roles = array();
     foreach ($groups as $group) {
         if (isset($perms->groups) and is_array(@$perms->groups->{$group})) {
             foreach ($perms->groups->{$group} as $groupRole) {
                 $roles[] = $groupRole;
             }
         }
     }
     if (isset($perms->users) and is_array(@$perms->users->{$userName})) {
         foreach ($perms->users->{$userName} as $userRole) {
             $roles[] = $userRole;
         }
     }
     $this->pouch['__roles__'] = $roles;
     return $roles;
 }