Exemple #1
0
 function testProxifyUrl()
 {
     $proxy = new ProxyWriter();
     $proxy->setSrcUrl(df_absolute_url(DATAFACE_SITE_URL . '/tests/testsites/site1/'));
     $proxy->setProxyUrl(df_absolute_url(DATAFACE_SITE_URL . '/tests/proxysites/site1/'));
     $expected = df_absolute_urL(DATAFACE_SITE_URL . '/tests/testsites/site1/index.html');
     $src = df_absolute_urL(DATAFACE_SITE_URL . '/tests/proxysites/site1/index.html');
     $this->assertEquals($expected, $proxy->unproxifyUrl($src));
     $proxy = new ProxyWriter();
     $proxy->setSrcUrl('http://www.xataface.com/');
     $proxy->setProxyUrl('http://en.xataface.com/path/en/');
     $strs = array('foo' => 'foo', '/foo' => '/path/en/foo', 'http://www.xataface.com/foo' => 'http://en.xataface.com/path/en/foo', 'http://www.xataface.com/foo?bar=1' => 'http://en.xataface.com/path/en/foo?bar=1', 'https://www.xataface.com/foo' => 'https://www.xataface.com/foo', 'http://www.foo.bar/foo' => 'http://www.foo.bar/foo');
     foreach ($strs as $k => $v) {
         $this->assertEquals($v, $proxy->proxifyUrl($k));
         $this->assertEquals($k, $proxy->unproxifyUrl($v));
     }
     $proxy = new ProxyWriter();
     $proxy->setSrcUrl('http://www.xataface.com/');
     $proxy->setProxyUrl('http://en.xataface.com/path/en/');
     $proxy->addAlias('foo', 'roof');
     $strs = array('foo' => 'roof', '/foo' => '/path/en/roof', 'http://www.xataface.com/foo' => 'http://en.xataface.com/path/en/roof', 'https://www.xataface.com/foo' => 'https://www.xataface.com/foo', 'http://www.foo.bar/foo' => 'http://www.foo.bar/foo', 'foo/overview' => 'roof/overview', '/foo/overview' => '/path/en/roof/overview', 'http://www.xataface.com/foo/overview' => 'http://en.xataface.com/path/en/roof/overview', 'https://www.xataface.com/foo/overview' => 'https://www.xataface.com/foo/overview');
     foreach ($strs as $k => $v) {
         $this->assertEquals($v, $proxy->proxifyUrl($k));
         $this->assertEquals($k, $proxy->unproxifyUrl($v));
     }
     $proxy = new ProxyWriter();
     $proxy->setSrcUrl('http://www.xataface.com/siteroot/');
     $proxy->setProxyUrl('http://en.xataface.com/path/en/');
     $proxy->addAlias('foo', 'roof');
     $strs = array('foo' => 'roof', '/foo' => '/foo', 'http://www.xataface.com/siteroot/foo' => 'http://en.xataface.com/path/en/roof', 'https://www.xataface.com/siteroot/foo' => 'https://www.xataface.com/siteroot/foo', 'http://www.foo.bar/siteroot/foo' => 'http://www.foo.bar/siteroot/foo', 'foo/overview' => 'roof/overview', '/siteroot/foo/overview' => '/path/en/roof/overview', 'http://www.xataface.com/siteroot/foo/overview' => 'http://en.xataface.com/path/en/roof/overview', 'https://www.xataface.com/foo/overview' => 'https://www.xataface.com/foo/overview');
     foreach ($strs as $k => $v) {
         $this->assertEquals($v, $proxy->proxifyUrl($k));
         $this->assertEquals($k, $proxy->unproxifyUrl($v));
     }
 }
Exemple #2
0
 function testRequestToOutputFile()
 {
     $client = new ProxyClient();
     $client->URL = df_absolute_url('tests/test_ProxyClient/test1.html');
     $outputFile = tempnam(sys_get_temp_dir(), 'test_ProxyClient');
     $client->outputFile = $outputFile;
     $client->process();
     $this->assertEquals(null, $client->content, 'Content should be written to output file, not saved to variable.');
     $expected = file_get_contents('tests/test_ProxyClient/test1.html');
     $doc = new DOMDocument();
     @$doc->loadHtml($expected);
     $expected = $doc->saveHtml();
     $actual = file_get_contents($outputFile);
     $actual = '';
     $fh = fopen($outputFile, 'r');
     while (!feof($fh) and trim($line = fgets($fh, 1024))) {
         // We skip the headers
     }
     ob_start();
     fpassthru($fh);
     fclose($fh);
     $actual = ob_get_contents();
     ob_end_clean();
     unset($doc);
     $doc = new DOMDocument();
     @$doc->loadHtml($actual);
     $actual = $doc->saveHtml();
     unset($doc);
     $this->assertEquals($expected, $actual);
 }
Exemple #3
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;
 }
 function handleRSS($results)
 {
     $app =& Dataface_Application::getInstance();
     $record =& $app->getRecord();
     $query =& $app->getQuery();
     import('feedcreator.class.php');
     import('Dataface/FeedTool.php');
     $ft = new Dataface_FeedTool();
     $rss = new UniversalFeedCreator();
     $rss->encoding = $app->_conf['oe'];
     //$rss->useCached(); // use cached version if age<1 hour
     $del =& $record->_table->getDelegate();
     if (!$del or !method_exists($del, 'getSingleRecordSearchFeed')) {
         $del =& $app->getDelegate();
     }
     if ($del and method_exists($del, 'getSingleRecordSearchFeed')) {
         $feedInfo = $del->getSingleRecordSearchFeed($record, $query);
         if (!$feedInfo) {
             $feedInfo = array();
         }
     }
     if (isset($feedInfo['title'])) {
         $rss->title = $feedInfo['title'];
     } else {
         $rss->title = $record->getTitle() . '[ Search for "' . $query['--subsearch'] . '"]';
     }
     if (isset($feedInfo['description'])) {
         $rss->description = $feedInfo['description'];
     } else {
         $rss->description = '';
     }
     if (isset($feedInfo['link'])) {
         $rss->link = $feedInfo['link'];
     } else {
         $rss->link = htmlentities(df_absolute_url($app->url('') . '&--subsearch=' . urlencode($query['--subsearch'])));
     }
     $rss->syndicationURL = $rss->link;
     $records = array();
     foreach ($results as $result) {
         foreach ($result as $rec) {
             $records[] = $rec->toRecord();
         }
     }
     uasort($records, array($this, 'cmp_last_modified'));
     foreach ($records as $rec) {
         if ($rec->checkPermission('view') and $rec->checkPermission('view in rss')) {
             $rss->addItem($ft->createFeedItem($rec));
         }
     }
     if (!$query['--subsearch']) {
         $rss->addItem($ft->createFeedItem($record));
     }
     header("Content-Type: application/xml; charset=" . $app->_conf['oe']);
     echo $rss->createFeed('RSS2.0');
     exit;
 }
Exemple #5
0
    function handle(&$params)
    {
        $cronpath = DATAFACE_PATH . '/modules/Email/cron.php';
        $indexpath = DATAFACE_SITE_PATH . '/' . basename(DATAFACE_SITE_HREF);
        $indexurl = df_absolute_url(DATAFACE_SITE_HREF);
        header('Content-type: text/plain');
        echo <<<END
Please add the following line to your crontab file so that emails will be sent out properly:

* * * * * /usr/bin/php {$cronpath} {$indexpath} {$indexurl} mail

Note that the /usr/bin/php portion should reflect the correct path to your php cli interpreter. 
Yours may be different.
END;
    }
Exemple #6
0
 function testPage()
 {
     $url = DATAFACE_SITE_URL . '/tests/testsites/site1/index.html';
     $site = new Dataface_Record('websites', array());
     $site->setValues(array('website_url' => df_absolute_url(DATAFACE_SITE_URL . '/tests/testsites/site1/'), 'source_language' => 'en', 'target_language' => 'fr', 'website_name' => 'Site 1 French', 'active' => 1, 'base_path' => DATAFACE_SITE_URL . '/proxies/site1/', 'host' => $_SERVER['HTTP_HOST']));
     $site->save();
     df_q("delete from site_text_filters where website_id='" . addslashes($site->val('website_id')) . "'");
     $server = new ProxyServer();
     $server->site = SweteSite::loadSiteById($site->val('website_id'));
     $server->SERVER = array('REQUEST_METHOD' => 'get');
     $server->URL = df_absolute_url(DATAFACE_SITE_URL . '/proxies/site1/index.html');
     $server->buffer = true;
     $server->handleRequest();
     $doc = new DOMDocument();
     $doc->loadHtml(file_get_contents('tests/testsites/site1_output/index.out.html'));
     $expected = $doc->saveHtml();
     //echo $server->contentBuffer;
     $doc2 = new DOMDocument();
     $doc2->loadHtml($server->contentBuffer);
     $actual = $doc2->saveHtml();
     //$this->assertEquals(trim($expected), trim($actual));
     // Cancelled this test because WTF!!!!  Even if I print the actual output, copy it to the file
     // and compare it to itself, it still fails!!!! WTF!!!!
 }
Exemple #7
0
 function pullValue(&$record, &$field, &$form, &$element)
 {
     /*
      * 
      * We don't bother pulling the values of file widgets because it would take too long.
      *
      */
     $widget =& $field['widget'];
     $formFieldName = $element->getName();
     $val = null;
     if ($widget['type'] == 'webcam') {
         $val = $record->getValueAsString($field['name']);
     }
     if ($record->getLength($field['name']) > 0) {
         // there is already a file set, let's add a preview to it
         if ($record->isImage($field['name'])) {
             $element->setProperty('image_preview', df_absolute_url($record->q($field['name'])));
         }
         $element->setProperty('preview', df_absolute_url($record->q($field['name'])));
         //echo "Adding preview for field '$fieldname':".$record->qq($fieldname);
     } else {
         //echo "No data in field '$fieldname'";
     }
     return $val;
 }
/**
 * Smarty {textformat}{/textformat} block plugin
 *
 * Type:     block function<br>
 * Name:     textformat<br>
 * Purpose:  format text a certain way with preset styles
 *           or custom wrap/indent settings<br>
 * @link http://smarty.php.net/manual/en/language.function.textformat.php {textformat}
 *       (Smarty online manual)
 * @param array
 * <pre>
 * Params:   style: string (email)
 *           indent: integer (0)
 *           wrap: integer (80)
 *           wrap_char string ("\n")
 *           indent_char: string (" ")
 *           wrap_boundary: boolean (true)
 * </pre>
 * @param string contents of the block
 * @param Smarty clever simulation of a method
 * @return string string $content re-formatted
 */
function smarty_block_collapsible_sidebar($params, $content, &$smarty)
{
    static $sidebar_index = 0;
    if (is_null($content)) {
        return;
    }
    $treeExpandedURL = df_absolute_url(DATAFACE_URL . '/images/treeExpanded.gif');
    $treeCollapsedURL = df_absolute_url(DATAFACE_URL . '/images/treeCollapsed.gif');
    if (isset($params['javascript_path'])) {
        $jspath = $params['javascript_path'];
    } else {
        if (defined('DATAFACE_URL')) {
            $jspath = DATAFACE_URL . '/js';
        } else {
            $jspath = '';
        }
    }
    $jspath = df_absolute_url($jspath);
    if (!isset($params['heading'])) {
        $heading = '';
    } else {
        $heading = $params['heading'];
    }
    if (!isset($params['class'])) {
        $clazz = $class = 'Dataface_collapsible_sidebar';
    } else {
        $clazz = $class = $params['class'];
    }
    if (isset($params['onexpand'])) {
        $onexpand = $params['onexpand'];
    } else {
        $onexpand = '';
    }
    if (isset($params['oncollapse'])) {
        $oncollapse = $params['oncollapse'];
    } else {
        $oncollapse = '';
    }
    if (isset($params['id'])) {
        $section_name = $id = $params['id'];
    } else {
        $id = null;
    }
    if (isset($params['prefix']) and isset($id)) {
        $id = $params['prefix'] . '_' . $id . '_' . $sidebar_index++;
    } else {
        if (isset($params['prefix'])) {
            $id = $params['prefix'] . '_' . $sidebar_index++;
        } else {
            $id = rand() . '_' . $sidebar_index++;
        }
    }
    $out = '';
    if (!defined('SMARTY_BLOCK_COLLAPSIBLE_SIDEBAR_JS')) {
        define('SMARTY_BLOCK_COLLAPSIBLE_SIDEBAR_JS', 1);
        $js = <<<END
    \t<script> if ( typeof(jQuery) == 'undefined' ){ document.writeln('<'+'script src="{$jspath}/jquery.packed.js"><'+'/script>');}</script>
    \t
    \t<script type="text/javascript"><!--

    \t\tif ( typeof(Xataface) == 'undefined' ) Xataface = {};
    \t\tif ( typeof(Xataface.blocks) == 'undefined' ) Xataface.blocks = {};
    \t\tif ( typeof(Xataface.blocks.collapsible_sidebar) ) Xataface.blocks.collapsible_sidebar = {};
    \t\tXataface.blocks.collapsible_sidebar.toggleCallback = function(){
    \t\t\t// this : dom element
    \t\t\tjQuery(this).toggleClass('{$class}-closed');
    \t\t\tjQuery(this).toggleClass('closed');
    \t\t\tvar img = jQuery(this).prev().find('img').get(0);
    \t\t\tif ( img.src == '{$treeExpandedURL}' ) img.src = '{$treeCollapsedURL}';
    \t\t\telse img.src = '{$treeExpandedURL}';
    \t\t\t
    \t\t\tif ( jQuery(this).hasClass('closed') ){
    \t\t\t\tvar collapseCallback = this.parentNode.getAttribute('oncollapse');
    \t\t\t\t
\t\t\t\t\tthis.parentNode.oncollapse = function(){eval(collapseCallback);};
\t\t\t\t\tthis.parentNode.oncollapse();\t
    \t\t\t} else {
    \t\t\t\tvar expandCallback = this.parentNode.getAttribute('onexpand');
\t\t\t\t\tthis.parentNode.onexpand = function(){ eval(expandCallback);};
\t\t\t\t\tthis.parentNode.onexpand();
    \t\t\t}
    \t\t
    \t\t};
    \t\tjQuery(document).ready(function(\$){
    \t\t\tvar handles = jQuery('.expansion-handle');
    \t\t\tfor ( var i=0; i<handles.length; i++ ){
    \t\t\t\tjQuery(handles[i]).click(function(){
    \t\t\t\t\tjQuery(this).parent().next().slideToggle("slow", Xataface.blocks.collapsible_sidebar.toggleCallback);
    \t\t\t\t});
    \t\t\t}
    \t\t\t
    \t\t});
    \t
    \t//-->
\t\t</script>
    \t
    \t
END;
        if (class_exists('Dataface_Application')) {
            $app =& Dataface_Application::getInstance();
            $app->addHeadContent($js);
        } else {
            $out .= $js;
        }
    }
    $links = '';
    if (isset($params['see_all'])) {
        $links .= '<a href="' . $params['see_all'] . '">see all</a>';
    }
    if (!@empty($params['edit_url'])) {
        $links .= '<a href="' . $params['edit_url'] . '">edit</a>';
    }
    if (@$params['display'] == 'collapsed') {
        $expandImage = $treeCollapsedURL;
    } else {
        $expandImage = $treeExpandedURL;
    }
    $expansionImage = "<img src=\"{$expandImage}\" style=\"cursor: pointer\" class=\"expansion-handle\" alt=\"Click to minimize this section\"> ";
    if (isset($section_name)) {
        $section_name = 'df:section_name="' . df_escape($section_name) . '"';
    }
    if (isset($params['movable'])) {
        $class .= ' movable-handle';
        $out .= '<div class="movable" id="' . df_escape($id) . '" ' . $section_name . ' oncollapse="' . df_escape($oncollapse) . '" onexpand="' . df_escape($onexpand) . '">';
    }
    if (@$params['display'] == 'collapsed') {
        $class .= " {$clazz}-closed";
    }
    if (@$params['hide_heading']) {
        $headingstyle = 'display: none';
    } else {
        $headingstyle = '';
    }
    $out .= "<h3 class=\"{$class}\" style=\"padding-left:0; width:100%; {$headingstyle}\">{$links}" . "{$expansionImage} {$heading}</h3>";
    if (@$params['display'] == 'collapsed') {
        $style = 'style="display:none"';
        $class = 'class="closed"';
    } else {
        $style = '';
        $class = '';
    }
    $out .= "<div {$class} {$style}>{$content}</div>";
    if (isset($params['movable'])) {
        $out .= '</div>';
    }
    return $out;
}
 /**
  * Displays the login prompt for an application.
  * @param $msg Optional error message to display.  e.g. 'Incorrect password'
  */
 function showLoginPrompt($msg = '')
 {
     if (!$this->authEnabled) {
         return true;
     }
     $app =& Dataface_Application::getInstance();
     $query =& $app->getQuery();
     if (@$query['--no-prompt']) {
         header("HTTP/1.0 401 Please Log In");
         echo "<html><body>Please Log In</body></html>";
         exit;
     }
     if (isset($this->delegate) and method_exists($this->delegate, 'showLoginPrompt')) {
         return $this->delegate->showLoginPrompt($msg);
     }
     header("HTTP/1.1 401 Please Log In");
     $url = $app->url('-action=login_prompt');
     if ($msg) {
         $msgarray = array($msg);
     } else {
         $msgarray = array();
     }
     if (isset($query['--msg'])) {
         $msgarray[] = $query['--msg'];
     }
     $msg = trim(implode('<br>', $msgarray));
     if ($msg) {
         $url .= '&--msg=' . urlencode($msg);
     }
     if ($query['-action'] != 'login' and $query['-action'] != 'login_prompt') {
         $_SESSION['-redirect'] = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $app->url('');
     } else {
         $referer = @$_SERVER['HTTP_REFERER'];
         if (!@$_SESSION['-redirect'] and $referer and strpos($referer, df_absolute_url(DATAFACE_SITE_URL)) === 0) {
             $_SESSION['-redirect'] = $referer;
         }
     }
     header("Location: {$url}");
     exit;
     //df_display(array('msg'=>$msg, 'redirect'=>@$_REQUEST['-redirect']), 'Dataface_Login_Prompt.html');
 }
Exemple #10
0
function get_post_photo_url($o)
{
    if (!$o->photo) {
        return null;
    }
    return df_absolute_url('uploads/' . sha1($o->username) . '/' . rawurlencode(basename($o->photo)));
}
Exemple #11
0
 function abs($params, $url, &$smarty)
 {
     return df_absolute_url($url);
 }
Exemple #12
0
    /**
     * Sends the email specified by $emailId to all recipients.
     * @param integer $emailId The id of the email message.
     * @param string $emailTable Optional the name of the table containing the email messages.
     * @param string $joinTable Optional the name of the table corresponding to a single recipient of the given email.
     * @param string $recipientsTable The name of the table where the recipients originated from.
     * @param string $emailColumn The name of the column that stored the email address.
     */
    function sendMail($emailId, $emailTable = null, $joinTable = null, $recipientsTable = null, $emailColumn = null)
    {
        require_once dirname(__FILE__) . '/../lib/XPM/MIME.php';
        if (isset($emailTable)) {
            $this->emailTable = $emailTable;
        }
        if (isset($joinTable)) {
            $this->joinTable = $joinTable;
        }
        if (isset($recipientsTable)) {
            $this->recipientsTable = $recipientsTable;
        }
        if (isset($emailColumn)) {
            $this->emailColumn = $emailColumn;
        }
        $app =& Dataface_Application::getInstance();
        $conf =& $app->_conf;
        if (@$conf['_mail']['func']) {
            $mail_func = $conf['_mail']['func'];
        } else {
            $mail_func = 'mail';
        }
        $emailTableObj =& Dataface_Table::loadTable($this->emailTable);
        $emailTableObj->addRelationship('recipients', array('__sql__' => 'select * from `' . $this->recipientsTable . '` r inner join `' . $this->joinTable . '` j on `r`.`' . $this->emailColumn . '` = j.recipient_email inner join `' . $this->emailTable . '` e on e.id = j.messageid where e.id=\'' . addslashes($emailId) . '\''));
        $email = df_get_record($this->emailTable, array('id' => $emailId));
        if (!$email) {
            return PEAR::raiseError("Failed to send email because no message with id {$emailId} could be found.", DATAFACE_E_ERROR);
        }
        $recipients = $email->getRelatedRecordObjects('recipients', 0, 500, 'sent=0');
        foreach ($recipients as $recipient) {
            $values = $recipient->strvals();
            $keys = array();
            foreach ($values as $key => $val) {
                $keys[] = '/%' . $key . '%/';
            }
            $values = array_values($values);
            $content = preg_replace($keys, $values, $recipient->strval('content'));
            $opt_out_url = df_absolute_url(DATAFACE_SITE_HREF . '?-action=email_opt_out&email=' . urlencode($recipient->val('recipient_email')));
            $html_content = $content .= <<<END
\t\t\t<hr />
<p>If you don't want to receive email updates from us, you can opt out of our mailing list by clicking <a href="{$opt_out_url}">here</a> .</p>
END;
            $content .= <<<END

------------------------------------------------------------------
If you don't want to receive email updates from us, you can opt out of our mailing list by going to {$opt_out_url} .
END;
            $headers = array();
            if ($email->strval('from')) {
                $headers[] = "From: " . $email->strval('from');
                $headers[] = "Reply-to: " . $email->strval('from');
            }
            if (@$app->_conf['mail_host']) {
                $headers[] = 'Message-ID: <' . md5(uniqid(time())) . '@' . $app->_conf['mail_host'] . '>';
            }
            //$headers[] = "Content-Type: text/plain; charset=".$app->_conf['oe'];
            $joinRecord = $recipient->toRecord($this->joinTable);
            if (!trim($recipient->val('recipient_email'))) {
                $joinRecord->setValue('success', 0);
                $joinRecord->setValue('sent', 1);
                $joinRecord->save();
                unset($joinRecord);
                unset($recipient);
                continue;
            }
            // path to 'MIME.php' file from XPM4 package
            // get ID value (random) for the embed image
            $id = MIME::unique();
            // set text/plain version of message
            $text = MIME::message(htmlspecialchars_decode(strip_tags(preg_replace(array('/<br[^>]*>/i', '/<div[^>]*>/i', '/<p[^>]*>/i', '/<table[^>]*>/i'), array("\r\n", "\r\n", "\r\n", "\r\n"), $content))), 'text/plain');
            // set text/html version of message
            $html = MIME::message($html_content, 'text/html');
            // add attachment with name 'file.txt'
            //$at[] = MIME::message('source file', 'text/plain', 'file.txt', 'ISO-8859-1', 'base64', 'attachment');
            //$file = 'xpertmailer.gif';
            // add inline attachment '$file' with name 'XPM.gif' and ID '$id'
            //$at[] = MIME::message(file_get_contents($file), FUNC::mime_type($file), 'XPM.gif', null, 'base64', 'inline', $id);
            // compose mail message in MIME format
            $mess = MIME::compose($text, $html);
            if (!$email->val('ignore_blacklist') and $this->isBlackListed($recipient->val('recipient_email'))) {
                echo "\nEmail address '" . $recipient->val('recipient_email') . "' is black listed so we do not send email to this address...";
                $joinRecord->setValue('success', 0);
                $joinRecord->setValue('sent', 1);
            } else {
                if ($mail_func($recipient->strval('recipient_email'), $email->strval('subject'), $mess['content'], implode("\r\n", $headers) . "\r\n" . $mess['header'])) {
                    $joinRecord->setValue('success', 1);
                    $joinRecord->setValue('sent', 1);
                    echo "Successfully sent email to " . $recipient->val('recipient_email');
                    //echo "Successfully sent email to {$recipient->strval('recipient_email')}" ;
                    //exit;
                } else {
                    $joinRecord->setValue('success', 0);
                    $joinRecord->setValue('sent', 1);
                    $this->messages[] = "Failed to send email to " . $email->val('recipient_email');
                    //echo "Failed to send";
                    //exit;
                }
            }
            $joinRecord->setValue('date_sent', date('Y-m-d H:i:s'));
            $joinRecord->save();
            unset($joinRecord);
            unset($recipient);
        }
    }
 function block__after_left_column()
 {
     //add info here when the user has an uncompiled job (or jobs).
     $app = Dataface_Application::getInstance();
     if ($app->_conf['enable_jobs']) {
         $jobs = SweteTools::uncompiledJobs();
         if (isset($jobs) && !empty($jobs)) {
             $url = df_absolute_url(DATAFACE_SITE_HREF . '?-table=jobs&-action=list&compiled=0&posted_by==' . SweteTools::getUser()->val('username'));
             echo '<div class="uncompiled-jobs">There are <a href="' . $url . '">' . count($jobs) . ' jobs ' . '</a>' . 'waiting to be compiled.</div>';
         }
     }
 }
 function handle($params)
 {
     global $ORIG_POST, $ORIG_REQUEST, $ORIG_GET;
     $_GET = $ORIG_GET;
     $_POST = $ORIG_POST;
     $_REQUEST = $ORIG_REQUEST;
     @session_write_close();
     $app = Dataface_Application::getInstance();
     $query = $app->getQuery();
     //print_r($_SERVER);
     $url = implode('/', array_map('rawurlencode', explode('/', $_SERVER['REDIRECT_URL'])));
     $url = str_replace("%3A", ":", $url);
     if (isset($_SERVER['REQUEST_URI'])) {
         if (strpos($_SERVER['REQUEST_URI'], '?') !== false) {
             list($junk, $_SERVER['REDIRECT_QUERY_STRING']) = explode('?', $_SERVER['REQUEST_URI']);
         } else {
             $_SERVER['REDIRECT_QUERY_STRING'] = '';
         }
     }
     $sweteDirectives = array();
     if (@$_SERVER['REDIRECT_QUERY_STRING']) {
         $qstr = $_SERVER['REDIRECT_QUERY_STRING'];
         $parts = explode('&', $qstr);
         $qstrout = array();
         foreach ($parts as $pt) {
             if (preg_match('/^swete\\:/', $pt)) {
                 list($d1, $d2) = explode('=', $pt);
                 $sweteDirectives[urldecode($d1)] = urldecode($d2);
             } else {
                 $qstrout[] = $pt;
             }
         }
         $url .= '?' . implode('&', $qstrout);
     }
     $url = df_absolute_url($url);
     //echo "The URL: ".$url;
     //echo "$url";exit;
     $site = SweteSite::loadSiteByUrl($url);
     if (!$site and $url and $url[strlen($url) - 1] != '/') {
         $url .= '/';
         $site = SweteSite::loadSiteByUrl($url);
         if ($site) {
             header('Location: ' . $url);
             exit;
         }
     }
     if (!$site) {
         die("[ERROR] No site found");
     }
     $server = new ProxyServer();
     if (defined('SWETE_USE_HTML5_PARSER') and SWETE_USE_HTML5_PARSER) {
         $server->useHtml5Parser = true;
     }
     if (@$_POST['swete:input']) {
         if (@$_POST['swete:key'] and @$_POST['swete:salt']) {
             if (is_numeric($_POST['swete:salt'])) {
                 $salt = intval($_POST['swete:salt']);
                 if (abs($salt - time()) < 3600) {
                     $password = $site->getRecord()->val('webservice_secret_key');
                     if ($password) {
                         $key = sha1($_POST['swete:salt'] . $password);
                         //if ( $key === $_POST['swete:key'] ){
                         if (strcasecmp($key, $_POST['swete:key']) === 0) {
                             $server->inputContent = $_POST['swete:input'];
                             if (@$_POST['swete:content-type']) {
                                 $server->inputContentType = $_POST['swete:content-type'];
                             }
                         } else {
                             die("[ERROR] Incorrect Key");
                         }
                     } else {
                         die("[ERROR] No secret key set in the website settings.");
                     }
                 } else {
                     die("[ERROR] Invalid salt value");
                 }
             } else {
                 die("[ERROR] Invalid salt value.  Salt must be an integer");
             }
         } else {
             die("[ERROR] Both swete:key and swete:salt must be provided");
         }
     }
     //$server->buffer = true;
     $server->logTranslationMisses = true;
     $server->site = $site;
     if ($site->getRecord()->val('log_requests')) {
         if (isset($server->logger)) {
             $server->logger->requestLoggingEnabled = true;
         }
     } else {
         if (isset($server->logger)) {
             $server->logger->requestLoggingEnabled = false;
         }
     }
     if ($site->getRecord()->val('log_translation_misses')) {
         $server->logTranslationMisses = true;
         if (isset($server->logger)) {
             // If we are logging translation misses we also need to log requests
             $server->logger->requestLoggingEnabled = true;
         }
     } else {
         $server->logTranslationMisses = false;
     }
     $server->URL = $url;
     // Deal with live cache
     // The first time a page is requested, it won't yet have a livecache
     // descriptor, so we needed to wait until we had loaded the
     // site so we can calculate the unproxified url.
     // Then we will try to flush it again.
     $isPost = strtolower($server->SERVER['REQUEST_METHOD']) === 'post';
     if (class_exists('LiveCache')) {
         $server->liveCache = LiveCache::getCurrentPage();
         if (!$isPost and !isset($server->liveCache->unproxifiedUrl)) {
             $server->liveCache->unproxifiedUrl = $server->site->getProxyWriter()->unproxifyUrl($server->URL);
             $server->liveCache->logger = $server->logger;
             $server->liveCache->flush();
         }
     }
     //
     $server->handleRequest();
     //print_r($server->headerBuffer);
     //$site = SweteSite::loadSiteByUrl(
 }
Exemple #15
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;
        }
    }
Exemple #16
0
    function toHtml()
    {
        $app =& Dataface_Application::getInstance();
        $query =& $app->getQuery();
        if (isset($query['-sort'])) {
            $sortcols = explode(',', trim($query['-sort']));
            $sort_columns = array();
            foreach ($sortcols as $sortcol) {
                $sortcol = trim($sortcol);
                if (strlen($sortcol) === 0) {
                    continue;
                }
                $sortcol = explode(' ', $sortcol);
                if (count($sortcol) > 1) {
                    $sort_columns[$sortcol[0]] = strtolower($sortcol[1]);
                } else {
                    $sort_columns[$sortcol[0]] = 'asc';
                }
                break;
            }
            unset($sortcols);
            // this was just a temp array so we get rid of it here
        } else {
            $sort_columns = array();
        }
        // $sort_columns should now be of the form [ColumnName] -> [Direction]
        // where Direction is "asc" or "desc"
        if ($this->_resultSet->found() > 0) {
            if (@$app->prefs['use_old_resultlist_controller']) {
                ob_start();
                df_display(array(), 'Dataface_ResultListController.html');
                $controller = ob_get_contents();
                ob_end_clean();
            }
            ob_start();
            //echo '<div style="clear: both"/>';
            if (!defined('Dataface_ResultList_Javascript')) {
                define('Dataface_ResultList_Javascript', true);
                echo '<script language="javascript" type="text/javascript" src="' . DATAFACE_URL . '/js/Dataface/ResultList.js"></script>';
            }
            if (!@$app->prefs['hide_result_filters'] and count($this->_filterCols) > 0) {
                echo $this->getResultFilters();
            }
            unset($query);
            if (@$app->prefs['use_old_resultlist_controller']) {
                echo '<div class="resultlist-controller" id="resultlist-controller-top">';
                echo $controller;
                echo "</div>";
            }
            $canSelect = false;
            if (!@$app->prefs['disable_select_rows']) {
                $canSelect = Dataface_PermissionsTool::checkPermission('select_rows', Dataface_PermissionsTool::getPermissions($this->_table));
            }
            echo '<table  id="result_list" class="listing">
				<thead>
				<tr>';
            if ($canSelect) {
                echo '<th><input type="checkbox" onchange="toggleSelectedRows(this,\'result_list\');"></th>';
            }
            if (!@$app->prefs['disable_ajax_record_details']) {
                echo '	<th><!-- Expand record column --></th>
				';
            }
            $results =& $this->getResults();
            $perms = array();
            $numCols = 0;
            $rowHeaderHtml = $this->renderRowHeader();
            if (isset($rowHeaderHtml)) {
                echo $rowHeaderHtml;
            } else {
                foreach ($this->_columns as $key) {
                    if (in_array($key, $this->_columns)) {
                        if (!($perms[$key] = Dataface_PermissionsTool::checkPermission('list', $this->_table, array('field' => $key)))) {
                            continue;
                        }
                        if (isset($sort_columns[$key])) {
                            $class = 'sorted-column-' . $sort_columns[$key];
                            $query = array();
                            $qs_columns = $sort_columns;
                            unset($qs_columns[$key]);
                            $sort_query = $key . ' ' . ($sort_columns[$key] == 'desc' ? 'asc' : 'desc');
                            foreach ($qs_columns as $qcolkey => $qcolvalue) {
                                $sort_query .= ', ' . $qcolkey . ' ' . $qcolvalue;
                            }
                        } else {
                            $class = 'unsorted-column';
                            $sort_query = $key . ' asc';
                            foreach ($sort_columns as $scolkey => $scolvalue) {
                                $sort_query .= ', ' . $scolkey . ' ' . $scolvalue;
                            }
                        }
                        $sq = array('-sort' => $sort_query);
                        $link = Dataface_LinkTool::buildLink($sq);
                        $numCols++;
                        $label = $this->_table->getFieldProperty('column:label', $key);
                        $legend = $this->_table->getFieldProperty('column:legend', $key);
                        if ($legend) {
                            $legend = '<span class="column-legend">' . htmlspecialchars($legend) . '</span>';
                        }
                        if (!$label) {
                            $label = $this->_table->getFieldProperty('widget:label', $key);
                        }
                        echo "<th class=\"{$class}\"><a href=\"{$link}\">" . htmlspecialchars($label) . "</a> {$legend}</th>";
                    }
                }
            }
            echo "</tr>\n\t\t\t\t</thead>\n\t\t\t\t<tbody>\n\t\t\t\t";
            $cursor = $this->_resultSet->start();
            $results->reset();
            $baseQuery = array();
            foreach ($_GET as $key => $value) {
                if (strpos($key, '-') !== 0) {
                    $baseQuery[$key] = $value;
                }
            }
            $evenRow = false;
            while ($results->hasNext()) {
                $rowClass = $evenRow ? 'even' : 'odd';
                $evenRow = !$evenRow;
                $record =& $results->next();
                if (!$record->checkPermission('view')) {
                    $cursor++;
                    unset($record);
                    continue;
                }
                $rowClass .= ' ' . $this->getRowClass($record);
                $query = array_merge($baseQuery, array("-action" => "browse", "-relationship" => null, "-cursor" => $cursor++));
                if ($record->checkPermission('link')) {
                    if (@$app->prefs['result_list_use_geturl']) {
                        $link = $record->getURL('-action=view');
                    } else {
                        $link = Dataface_LinkTool::buildLink($query) . '&-recordid=' . urlencode($record->getId());
                    }
                } else {
                    $del =& $record->_table->getDelegate();
                    if ($del and method_exists($del, 'no_access_link')) {
                        $link = $del->no_access_link($record);
                    } else {
                        $link = null;
                    }
                }
                $recordid = $record->getId();
                echo "<tr class=\"listing {$rowClass}\">";
                if ($canSelect) {
                    echo '<td><input class="rowSelectorCheckbox" id="rowSelectorCheckbox:' . $record->getId() . '" type="checkbox"></td>';
                }
                if (!@$app->prefs['disable_ajax_record_details']) {
                    echo '<td>';
                    echo '<script language="javascript" type="text/javascript"><!--
							registerRecord(\'' . addslashes($recordid) . '\',  ' . $record->toJS(array()) . ');
							//--></script>
							<img src="' . DATAFACE_URL . '/images/treeCollapsed.gif" onclick="resultList.showRecordDetails(this, \'' . addslashes($recordid) . '\')"/>';
                    $at =& Dataface_ActionTool::getInstance();
                    $actions = $at->getActions(array('category' => 'list_row_actions', 'record' => &$record));
                    //print_r($actions);
                    if (count($actions) > 0) {
                        echo ' <span class="row-actions">';
                        foreach ($actions as $action) {
                            echo '<a href="' . htmlspecialchars($action['url']) . '" class="' . htmlspecialchars($action['class']) . ' ' . (@$action['icon'] ? 'with-icon' : '') . '" ' . (@$action['icon'] ? ' style="' . htmlspecialchars('background-image: url(' . $action['icon'] . ')') . '"' : '') . (@$action['target'] ? ' target="' . htmlspecialchars($action['target']) . '"' : '') . ' title="' . htmlspecialchars(@$action['description'] ? $action['description'] : $action['label']) . '"><span>' . htmlspecialchars($action['label']) . '</span></a> ';
                        }
                        echo '</span>';
                    }
                    echo '</td>';
                    unset($at, $actions);
                }
                $rowContentHtml = $this->renderRow($record);
                if (isset($rowContentHtml)) {
                    echo $rowContentHtml;
                } else {
                    //$expandTree=false; // flag to indicate when we added the expandTree button
                    //if ( @$app->prefs['enable_ajax_record_details'] === 0 ){
                    //	$expandTree = true;
                    //}
                    foreach ($this->_columns as $key) {
                        $thisField =& $record->_table->getField($key);
                        if (!$perms[$key]) {
                            continue;
                        }
                        $val = $this->renderCell($record, $key);
                        if ($record->checkPermission('edit', array('field' => $key)) and !$record->_table->isMetaField($key)) {
                            $editable_class = 'df__editable_wrapper';
                        } else {
                            $editable_class = '';
                        }
                        if (!@$thisField['noLinkFromListView'] and $link and $val) {
                            $val = "<a href=\"{$link}\" class=\"unmarked_link\">" . $val . "</a>";
                            $editable_class = '';
                        } else {
                        }
                        if (@$thisField['noEditInListView']) {
                            $editable_class = '';
                        }
                        echo "<td id=\"td-" . rand() . "\" class=\"{$rowClass} {$editable_class}\">&nbsp;{$val}</td>";
                        unset($thisField);
                    }
                }
                echo "</tr>";
                echo "<tr class=\"listing {$rowClass}\" style=\"display:none\" id=\"{$recordid}-row\">";
                if ($canSelect) {
                    echo "<td><!--placeholder for checkbox col --></td>";
                }
                echo "<td colspan=\"" . ($numCols + 1) . "\" id=\"{$recordid}-cell\"></td>\n\t\t\t\t\t  </tr>";
                unset($record);
            }
            if (@$app->prefs['enable_resultlist_add_row']) {
                echo "<tr id=\"add-new-row\" df:table=\"" . htmlspecialchars($this->_table->tablename) . "\">";
                if ($canSelect) {
                    $colspan = 2;
                } else {
                    $colspan = 1;
                }
                echo "<td colspan=\"{$colspan}\"><script language=\"javascript\">require(DATAFACE_URL+'/js/addable.js')</script><a href=\"#\" onclick=\"df_addNew('add-new-row');return false;\">" . df_translate('scripts.GLOBAL.LABEL_ADD_ROW', "Add Row") . "</a></td>";
                foreach ($this->_columns as $key) {
                    echo "<td><span df:field=\"" . htmlspecialchars($key) . "\"></span></td>";
                }
                echo "</tr>";
            }
            echo "</tbody>\n\t\t\t\t</table>";
            if ($canSelect) {
                echo '<form id="result_list_selected_items_form" method="post" action="' . df_absolute_url(DATAFACE_SITE_HREF) . '">';
                $app =& Dataface_Application::getInstance();
                $q =& $app->getQuery();
                foreach ($q as $key => $val) {
                    if (strlen($key) > 1 and $key[0] == '-' and $key[1] == '-') {
                        continue;
                    }
                    echo '<input type="hidden" name="' . urlencode($key) . '" value="' . htmlspecialchars($val) . '" />';
                }
                echo '<input type="hidden" name="--selected-ids" id="--selected-ids" />';
                echo '<input type="hidden" name="-from" id="-from" value="' . $q['-action'] . '" />';
                echo '<input type="hidden" name="--redirect" value="' . base64_encode($app->url('')) . '" />';
                echo '</form>';
                import('Dataface/ActionTool.php');
                $at =& Dataface_ActionTool::getInstance();
                $actions = $at->getActions(array('category' => 'selected_result_actions'));
                if (count($actions) > 0) {
                    echo '<div id="selected-actions">' . df_translate('scripts.Dataface_ResultList.MESSAGE_WITH_SELECTED', "With Selected") . ': <ul class="selectedActionsMenu" id="result_list-selectedActionsMenu">';
                    foreach ($actions as $action) {
                        $img = '';
                        if (@$action['icon']) {
                            $img = '<img src="' . $action['icon'] . '"/>';
                        }
                        if (!@$action['onclick'] and !$action['url']) {
                            $action['onclick'] = "return actOnSelected('result_list', '" . @$action['name'] . "'" . (@$action['confirm'] ? ", function(){return confirm('" . addslashes($action['confirm']) . "');}" : "") . ")";
                        }
                        echo <<<END
\t\t\t\t\t\t<li id="action-{$action['id']}"><a href="{$action['url']}" onclick="{$action['onclick']}" title="{$action['description']}">{$img}{$action['label']}</a></li>
END;
                    }
                    echo '</ul></div>';
                }
            }
            if (@$app->prefs['use_old_resultlist_controller']) {
                echo '<div class="resultlist-controller" id="resultlist-controller-bottom">';
                echo $controller;
                echo '</div>';
            }
            $out = ob_get_contents();
            ob_end_clean();
        } else {
            if (@$app->prefs['use_old_resultlist_controller']) {
                ob_start();
                df_display(array(), 'Dataface_ResultListController.html');
                $out = ob_get_contents();
                ob_end_clean();
            } else {
                $out = '';
            }
            $out .= "<p style=\"clear:both\">" . df_translate('scripts.GLOBAL.MESSAGE_NO_MATCH', "No records matched your request.") . "</p>";
        }
        return $out;
    }
Exemple #17
0
 /**
  * Builds a link based on the given query.
  * @param Associative array of the query.  (also accepts a query string e.g.: 'Name=Steve&LastName=Hannah').
  * @param useContext If true, this query will use the existing REQUEST parameters as a base.
  */
 public static function buildLink($query, $useContext = true, $forceContext = false, $stripRecordId = false)
 {
     $app =& Dataface_Application::getInstance();
     $appQuery =& $app->getQuery();
     if ($stripRecordId and isset($query['-recordid'])) {
         unset($query['-recordid']);
     }
     if (is_string($query)) {
         $terms = explode('&', $query);
         $query = array();
         foreach ($terms as $term) {
             $key = urldecode(substr($term, 0, strpos($term, '=')));
             $value = urldecode(substr($term, strpos($term, '=') + 1));
             if (strlen($value) == 0) {
                 $query[$key] = null;
             } else {
                 $query[$key] = $value;
             }
         }
     }
     if (!isset($query['-table'])) {
         $query['-table'] = $appQuery['-table'];
     }
     if (!$forceContext and $useContext) {
         // We check if the query parameters have changed.  If they have, then it doesn't
         // make a whole lot of sense to maintain context.
         foreach ($query as $key => $val) {
             if (!$key) {
                 continue;
             }
             if ($key[0] != '-' and $query[$key] != @$appQuery[$key]) {
                 $useContext = false;
                 break;
             }
         }
     }
     if ($useContext) {
         $request = Dataface_LinkTool::getMask();
         if ($stripRecordId and isset($request['-recordid'])) {
             unset($request['-recordid']);
         }
         if (isset($query['-relationship'])) {
             if ($query['-relationship'] != @$appQuery['-relationship']) {
                 foreach ($request as $qkey => $qval) {
                     if (strstr($qkey, '-related:') == $qkey) {
                         unset($request[$qkey]);
                     }
                 }
             }
         }
         if (isset($request['-sort']) and $request['-table'] != $appQuery['-table']) {
             unset($request['-sort']);
         }
         //print_r($query);
         $query = array_merge($request, $query);
     }
     if (!isset($query['-search'])) {
         $query['-search'] = null;
     }
     if (isset($_REQUEST['-search']) and strlen($_REQUEST['-search']) > 0 and $query['-search'] !== null) {
         $query['-search'] = $_REQUEST['-search'];
     }
     foreach ($query as $key => $value) {
         if ($value === null || strpos($key, '--') === 0) {
             unset($query[$key]);
         }
     }
     $str = '';
     foreach ($query as $key => $value) {
         if (is_array($value)) {
             foreach ($value as $vkey => $vval) {
                 $str .= urlencode($key . '[' . $vkey . ']') . '=' . urlencode($vval) . '&';
             }
         } else {
             $str .= urlencode($key) . '=' . urlencode($value) . '&';
         }
     }
     $str = substr($str, 0, strlen($str) - 1);
     $url = DATAFACE_SITE_HREF;
     if (strpos('?', $url) !== false) {
         $url .= '&' . $str;
     } else {
         $url .= '?' . $str;
     }
     $url = $app->filterUrl($url);
     return df_absolute_url($url);
 }
Exemple #18
0
 /**
  * This method sits above "display" on the output stack for a field.
  * I.e. it wraps "display()" and adds some extra filtering to make the
  * output directly appropriate to be displayed as HTML.  In text fields
  * this will convert newlines to breaks, and in blob fields, this will output
  * either the full a-href tag or img tag depending on the type of content that
  * is stored.
  * 
  * @param $fieldname The name of the field to output
  * @param $params Associative array of html parameters that can optionally
  * be supplied.
  * Returns HTML string.
  */
 function htmlValue($fieldname, $index = 0, $where = 0, $sort = 0, $params = array())
 {
     $recid = $this->getId();
     $uri = $recid . '#' . $fieldname;
     $domid = $uri . '-' . rand();
     $delegate =& $this->_table->getDelegate();
     if (isset($delegate) && method_exists($delegate, $fieldname . '__htmlValue')) {
         $methodname = $fieldname . '__htmlValue';
         $res = $delegate->{$methodname}($this);
         //$res = call_user_func(array(&$delegate, $fieldname.'__htmlValue'), $this);
         if (is_string($res) and DATAFACE_USAGE_MODE == 'edit' and $this->checkPermission('edit', array('field' => $fieldname)) and !$this->_table->isMetaField($fieldname)) {
             $res = '<span id="' . $domid . '" df:id="' . $uri . '" class="df__editable">' . $res . '</span>';
         }
         return $res;
     }
     $parent =& $this->getParentRecord();
     if (isset($parent) and $parent->_table->hasField($fieldname)) {
         return $parent->htmlValue($fieldname, $index, $where, $sort, $params);
     }
     $val = $this->display($fieldname, $index, $where, $sort);
     if ($this->secureDisplay and !Dataface_PermissionsTool::view($this, array('field' => $fieldname))) {
         $del =& $this->_table->getDelegate();
         if ($del and method_exists($del, 'no_access_link')) {
             $link = $del->no_access_link($this, array('field' => $fieldname));
             return '<a href="' . htmlspecialchars($link) . '">' . $val . '</a>';
         }
     }
     $field = $this->_table->getField($fieldname);
     //if ( $field['widget']['type'] != 'htmlarea' ) $val = htmlentities($val,ENT_COMPAT, 'UTF-8');
     if ($this->_table->isText($fieldname) and $field['widget']['type'] != 'htmlarea') {
         $val = nl2br($val);
     }
     if ($this->_table->isBlob($fieldname) or $this->_table->isContainer($fieldname)) {
         if ($this->getLength($fieldname, $index, $where, $sort) > 0) {
             if ($this->isImage($fieldname, $index, $where, $sort)) {
                 $val = '<img src="' . $val . '"';
                 if (!isset($params['width']) and isset($field['width'])) {
                     $params['width'] = $field['width'];
                 }
                 foreach ($params as $pkey => $pval) {
                     $val .= ' ' . $pkey . '="' . $pval . '"';
                 }
                 $val .= '/>';
             } else {
                 $file_icon = df_translate($this->getMimetype($fieldname, $index, $where, $sort) . ' file icon', df_absolute_url(DATAFACE_URL) . '/images/document_icon.gif');
                 $val = '<img src="' . $file_icon . '"/><a href="' . $val . '" target="_blank"';
                 foreach ($params as $pkey => $pval) {
                     $val .= ' ' . $pkey . '="' . $pval . '"';
                 }
                 $val .= '>View Field Content In New Window (' . $this->getMimetype($fieldname, $index, $where, $sort) . ')</a>';
             }
         } else {
             $val = "(Empty)";
         }
     }
     if (is_string($val) and DATAFACE_USAGE_MODE == 'edit' and $this->checkPermission('edit', array('field' => $fieldname)) and !$this->_table->isMetaField($fieldname)) {
         $val = '<span id="' . $domid . '" df:id="' . $uri . '" class="df__editable">' . $val . '</span>';
     }
     return $val;
 }
Exemple #19
0
 /**
  * @brief Returns an HTML-friendly value of a field.
  *
  * @param string $fieldname The name of the field to return.
  * @param int $index For related fields indicates the index within the related list of the record to retrieve.
  * @param string $where Optional where clause to filter related list when retrieving a related field.
  * @param string $sort Optional sort clause when retrieving a related field.  Used to sort related list before 
  *  selecting the related record from which the value is to be returned.
  * @param array $params Optional additional parameters to customize the HTML output.  This may be passed to 
  *		include HTML attributes width and height to blob fields containing an image.
  *
  * @return string The HTML string result.
  *
  * @since 0.5
  *
  * @section Synopsis
  * 
  * This method sits above "display" on the output stack for a field.
  * I.e. it wraps display() and adds some extra filtering to make the
  * output directly appropriate to be displayed as HTML.  In text fields
  * this will convert newlines to breaks, and in blob fields, this will output
  * either the full a-href tag or img tag depending on the type of content that
  * is stored.
  *
  * 
  * @see display()
  * @see getValue()
  * @see getValueAsString()
  * 
  */
 function htmlValue($fieldname, $index = 0, $where = 0, $sort = 0, $params = array())
 {
     $recid = $this->getId();
     $uri = $recid . '#' . $fieldname;
     $domid = $uri . '-' . rand();
     $delegate =& $this->_table->getDelegate();
     if (isset($delegate) && method_exists($delegate, $fieldname . '__htmlValue')) {
         $methodname = $fieldname . '__htmlValue';
         $res = $delegate->{$methodname}($this);
         //$res = call_user_func(array(&$delegate, $fieldname.'__htmlValue'), $this);
         if (is_string($res) and DATAFACE_USAGE_MODE == 'edit' and $this->checkPermission('edit', array('field' => $fieldname)) and !$this->_table->isMetaField($fieldname)) {
             $res = '<span id="' . df_escape($domid) . '" df:id="' . df_escape($uri) . '" class="df__editable">' . $res . '</span>';
         }
         return $res;
     }
     $event = new StdClass();
     $event->record = $this;
     $event->fieldname = $fieldname;
     $event->index = $index;
     $event->where = $where;
     $event->sort = $sort;
     $event->params = $params;
     $event->out = null;
     Dataface_Application::getInstance()->fireEvent('Dataface_Record__htmlValue', $event);
     if (isset($event->out)) {
         return $event->out;
     }
     $parent =& $this->getParentRecord();
     if (isset($parent) and $parent->_table->hasField($fieldname)) {
         return $parent->htmlValue($fieldname, $index, $where, $sort, $params);
     }
     $val = $this->display($fieldname, $index, $where, $sort);
     $strval = $this->strval($fieldname, $index, $where, $sort);
     $field = $this->_table->getField($fieldname);
     if (!@$field['passthru'] and $this->escapeOutput) {
         $val = nl2br(df_escape($val));
     }
     if ($this->secureDisplay and !Dataface_PermissionsTool::view($this, array('field' => $fieldname))) {
         $del =& $this->_table->getDelegate();
         if ($del and method_exists($del, 'no_access_link')) {
             $link = $del->no_access_link($this, array('field' => $fieldname));
             return '<a href="' . df_escape($link) . '">' . $val . '</a>';
         }
     }
     //if ( $field['widget']['type'] != 'htmlarea' ) $val = htmlentities($val,ENT_COMPAT, 'UTF-8');
     //if ( $this->_table->isText($fieldname) and $field['widget']['type'] != 'htmlarea' and $field['contenttype'] != 'text/html' ) $val = nl2br($val);
     if ($this->_table->isBlob($fieldname) or $this->_table->isContainer($fieldname)) {
         if ($this->getLength($fieldname, $index, $where, $sort) > 0) {
             if ($this->isImage($fieldname, $index, $where, $sort)) {
                 $val = '<img src="' . $val . '"';
                 if (!isset($parmas['alt'])) {
                     $params['alt'] = $strval;
                 }
                 if (!isset($params['width']) and isset($field['width'])) {
                     $params['width'] = $field['width'];
                 }
                 foreach ($params as $pkey => $pval) {
                     $val .= ' ' . df_escape($pkey) . '="' . df_escape($pval) . '"';
                 }
                 $val .= '/>';
             } else {
                 $file_icon = df_translate($this->getMimetype($fieldname, $index, $where, $sort) . ' file icon', df_absolute_url(DATAFACE_URL) . '/images/document_icon.gif');
                 $val = '<img src="' . df_escape($file_icon) . '"/><a href="' . $val . '" target="_blank"';
                 foreach ($params as $pkey => $pval) {
                     $val .= ' ' . df_escape($pkey) . '="' . df_escape($pval) . '"';
                 }
                 $val .= '>' . df_escape($strval) . ' (' . df_escape($this->getMimetype($fieldname, $index, $where, $sort)) . ')</a>';
             }
         } else {
             $val = "(Empty)";
         }
     }
     if (is_string($val) and DATAFACE_USAGE_MODE == 'edit' and $this->checkPermission('edit', array('field' => $fieldname)) and !$this->_table->isMetaField($fieldname)) {
         $val = '<span id="' . df_escape($domid) . '" df:id="' . df_escape($uri) . '" class="df__editable">' . $val . '</span>';
     }
     return $val;
 }
Exemple #20
-1
 /**
  * @param $tablename The name of the table upon which this form is based. - or a Dataface_Record object to edit.
  * @type string | Dataface_Record
  *
  * @param $db DB handle for the current database connection.
  * @type resource
  *
  * @param $query Associative array of query parameters to dictate which record is loaded for editing.
  * @type array([String]->[String])
  *
  * @param $new Flag to indicate whether this form is creating a new record or editing an existing one.
  * @type boolean
  *
  * @param $fieldnames An optional array of field names to include in the form.
  * @type array(string)
  *
  */
 function Dataface_QuickForm($tablename, $db = '', $query = '', $formname = '', $new = false, $fieldnames = null, $lang = null)
 {
     $app =& Dataface_Application::getInstance();
     $this->app =& $app;
     $appQuery =& $app->getQuery();
     if (!isset($lang) && !isset($this->_lang)) {
         $this->_lang = $app->_conf['lang'];
     } else {
         if (isset($lang)) {
             $this->_lang = $lang;
         }
     }
     if (is_a($tablename, 'Dataface_Record')) {
         if (!$this->formSubmitted()) {
             $this->_record =& $tablename;
             $this->tablename = $this->_record->_table->tablename;
             $this->_table =& $this->_record->_table;
             unset($tablename);
             $tablename = $this->tablename;
         } else {
             $this->_record =& Dataface_QuickForm::getRecord();
             $this->tablename = $tablename;
             $this->_table =& Dataface_Table::loadTable($this->tablename);
         }
     } else {
         if (!$new) {
             if ($tablename == $appQuery['-table']) {
                 $this->_record =& Dataface_QuickForm::getRecord();
             } else {
                 if ($query) {
                     $this->_record =& df_get_record($tablename, $query);
                 }
             }
             if (!$this->_record) {
                 $this->_record = new Dataface_Record($tablename, array());
             }
             $this->tablename = $tablename;
             $this->_table =& Dataface_Table::loadTable($this->tablename);
             //$tablename = $this->tablename;
         } else {
             $this->tablename = $tablename;
             $this->_table =& Dataface_Table::loadTable($this->tablename, $this->db);
             $this->_record = new Dataface_Record($this->tablename, array());
         }
     }
     $this->_new = $new;
     if (!$formname) {
         if ($new) {
             $formname = "new_" . $tablename . "_record_form";
         } else {
             $formname = "existing_" . $tablename . "_record_form";
         }
     }
     if (!$db) {
         $db = $app->db();
     }
     $this->db = $db;
     $this->_query = is_array($query) ? $query : array();
     // The cursor tells us which record in the dataset we will be editing.
     if (!isset($this->_query['-cursor'])) {
         $this->_query['-cursor'] = 0;
     }
     // Load the results of the query.
     $this->_resultSet =& Dataface_QueryTool::loadResult($tablename, $db, $this->_query);
     parent::HTML_QuickForm($formname, 'post', df_absolute_url($_SERVER['PHP_SELF']), '', array('accept-charset' => $app->_conf['ie']), self::$TRACK_SUBMIT);
     $this->setJsWarnings(df_translate('quickform.warning.prefix', $this->_jsPrefix), df_translate('quickform.warning.postfix', $this->_jsPostfix));
     //$this->_fields =& $this->_table->fields(false,false,true);
     $this->_fields =& $this->_table->formFields(false, true);
     if (@$appQuery['-xf-hide-fields']) {
         $hiddenFields = explode(' ', $appQuery['-xf-hide-fields']);
         $css = array();
         foreach ($hiddenFields as $f) {
             if (isset($this->_fields[$f])) {
                 $css[] = "#{$f}_form_row { display:none;}";
                 //    $this->_fields[$f]['widget']['type'] = 'hidden';
                 //    $fieldDef =& Dataface_Table::loadTable($this->_fields[$f]['tablename'])->getField($f);
                 //    $fieldDef['widget']['type'] = 'hidden';
                 //    unset($fieldDef);
                 //    //$field =&
             }
         }
         if ($css) {
             $app->addHeadContent('<style type="text/css">' . implode('', $css) . '</style>');
         }
     }
     //$this->_record = new Dataface_Record($this->_table->tablename, array());
     $this->_renderer = new HTML_QuickForm_Renderer_Dataface($this);
     //$this->defaultRenderer();
     $this->_renderer->setFormTemplate($this->getFormTemplate());
     $this->_requiredNote = '';
     if (is_array($fieldnames)) {
         /*
          * $fieldnames were specified in the parameters.  We will use the provided
          * field names but we must make sure that the fields exist.
          */
         $this->_fieldnames = array();
         foreach ($fieldnames as $fieldname) {
             if (isset($this->_fields[$fieldname])) {
                 $this->_fieldnames[] = $fieldname;
             }
         }
     }
     //$this->_build();
 }
Exemple #21
-1
 /**
  * @param $tablename The name of the table upon which this form is based. - or a Dataface_Record object to edit.
  * @type string | Dataface_Record
  *
  * @param $db DB handle for the current database connection.
  * @type resource
  *
  * @param $query Associative array of query parameters to dictate which record is loaded for editing.
  * @type array([String]->[String])
  *
  * @param $new Flag to indicate whether this form is creating a new record or editing an existing one.
  * @type boolean
  *
  * @param $fieldnames An optional array of field names to include in the form.
  * @type array(string)
  *
  */
 function Dataface_QuickForm($tablename, $db = '', $query = '', $formname = '', $new = false, $fieldnames = null, $lang = null)
 {
     $app =& Dataface_Application::getInstance();
     $this->app =& $app;
     $appQuery =& $app->getQuery();
     if (!isset($lang) && !isset($this->_lang)) {
         $this->_lang = $app->_conf['lang'];
     } else {
         if (isset($lang)) {
             $this->_lang = $lang;
         }
     }
     if (is_a($tablename, 'Dataface_Record')) {
         if (!$this->formSubmitted()) {
             $this->_record =& $tablename;
             $this->tablename = $this->_record->_table->tablename;
             $this->_table =& $this->_record->_table;
             unset($tablename);
             $tablename = $this->tablename;
         } else {
             $this->_record =& Dataface_QuickForm::getRecord();
             $this->tablename = $tablename;
             $this->_table =& Dataface_Table::loadTable($this->tablename);
         }
     } else {
         if (!$new) {
             if ($tablename == $appQuery['-table']) {
                 $this->_record =& Dataface_QuickForm::getRecord();
             } else {
                 if ($query) {
                     $this->_record =& df_get_record($tablename, $query);
                 }
             }
             if (!$this->_record) {
                 $this->_record = new Dataface_Record($tablename, array());
             }
             $this->tablename = $tablename;
             $this->_table =& Dataface_Table::loadTable($this->tablename);
             //$tablename = $this->tablename;
         } else {
             $this->tablename = $tablename;
             $this->_table =& Dataface_Table::loadTable($this->tablename, $this->db);
             $this->_record = new Dataface_Record($this->tablename, array());
         }
     }
     $this->_new = $new;
     if (!$formname) {
         if ($new) {
             $formname = "new_" . $tablename . "_record_form";
         } else {
             $formname = "existing_" . $tablename . "_record_form";
         }
     }
     if (!$db and defined('DATAFACE_DB_HANDLE')) {
         $db = DATAFACE_DB_HANDLE;
     } else {
         $db = $app->_db;
     }
     $this->db = $db;
     $this->_query = is_array($query) ? $query : array();
     // The cursor tells us which record in the dataset we will be editing.
     if (!isset($this->_query['-cursor'])) {
         $this->_query['-cursor'] = 0;
     }
     // Load the results of the query.
     $this->_resultSet =& Dataface_QueryTool::loadResult($tablename, $db, $this->_query);
     parent::HTML_QuickForm($formname, 'post', df_absolute_url($_SERVER['PHP_SELF']), '', array('accept-charset' => $app->_conf['ie']), true);
     //$this->_fields =& $this->_table->fields(false,false,true);
     $this->_fields =& $this->_table->formFields(false, true);
     //$this->_record = new Dataface_Record($this->_table->tablename, array());
     $this->_renderer = new HTML_QuickForm_Renderer_Dataface($this);
     //$this->defaultRenderer();
     $this->_renderer->setFormTemplate($this->getFormTemplate());
     $this->_requiredNote = '';
     if (is_array($fieldnames)) {
         /*
          * $fieldnames were specified in the parameters.  We will use the provided
          * field names but we must make sure that the fields exist.
          */
         $this->_fieldnames = array();
         foreach ($fieldnames as $fieldname) {
             if (isset($this->_fields[$fieldname])) {
                 $this->_fieldnames[] = $fieldname;
             }
         }
     }
     //$this->_build();
 }