Exemplo n.º 1
0
 /**
  * Encodes mixed params before they are sent to the database.
  *
  * @param mixed $data The unencoded object/array/string/etc
  * @return mixed The encoded version
  */
 static function encode(&$data)
 {
     if (is_object($data) || is_array($data)) {
         // skip the ilp_flexible_table
         if (!is_a($data, 'ilp_flexible_table')) {
             foreach ($data as $index => &$datum) {
                 //we will skip any index with the prefix binary
                 if (substr($index, 0, 7) != 'binary_') {
                     $datum = ilp_db::encode($datum);
                 }
             }
         }
         return $data;
     } else {
         // decode any special characters prevent malicious code slipping through
         $data = ilp_db::decode_htmlchars($data, ENT_QUOTES);
         // purify all data (e.g. validate html, remove js and other bad stuff)
         //I have had to remove the purify call as it was causing pages to timeout in 1.9
         //this should be put back in once the ilp is moodle 2.0 only
         $data = purify_html($data);
         // encode the purified string
         $data = trim(preg_replace('/\\\\/', '\', htmlentities($data, ENT_QUOTES, 'utf-8', false)));
         // convert the empty string into null as such values break nullable FK fields
         return $data == '' ? null : $data;
     }
 }
Exemplo n.º 2
0
 public static function toArray($pin)
 {
     $result = array();
     $result['link'] = purify_url($pin['link']);
     $result['title'] = purify_html($pin['title']);
     $result['created_on'] = strtotime($pin['created_on']);
     return $result;
 }
Exemplo n.º 3
0
 /**
  * Tests the installation of event handlers from file
  */
 function test_our_tags()
 {
     $text = '<nolink>xxx<em>xx</em><div>xxx</div></nolink>';
     $this->assertIdentical($text, purify_html($text));
     $text = '<tex>xxxxxx</tex>';
     $this->assertIdentical($text, purify_html($text));
     $text = '<algebra>xxxxxx</algebra>';
     $this->assertIdentical($text, purify_html($text));
     $text = '<span lang="de_DU" class="multilang">asas</span>';
     $this->assertIdentical($text, purify_html($text));
     $text = '<lang lang="de_DU">xxxxxx</lang>';
     $this->assertIdentical($text, purify_html($text));
     $text = "\n\raa\rsss\nsss\r";
     $this->assertIdentical($text, purify_html($text));
 }
Exemplo n.º 4
0
    public function test_getfeed()
    {
        $feed = new moodle_simplepie($this->getExternalTestFileUrl('/rsstest.xml'), self::TIMEOUT);
        $this->assertInstanceOf('moodle_simplepie', $feed);
        $this->assertNull($feed->error(), "Failed to load the sample RSS file. Please check your proxy settings in Moodle. %s");
        $this->assertSame('Moodle News', $feed->get_title());
        $this->assertSame('http://moodle.org/mod/forum/view.php?f=1', $feed->get_link());
        $this->assertSame("General news about Moodle.\n\nMoodle is a leading open-source course management system (CMS) - a software package designed to help educators create quality online courses. Such e-learning systems are sometimes also called Learning Management Systems (LMS) or Virtual Learning Environments (VLE). One of the main advantages of Moodle over other systems is a strong grounding in social constructionist pedagogy.", $feed->get_description());
        $this->assertSame('&amp;#169; 2007 moodle', $feed->get_copyright());
        $this->assertSame('http://moodle.org/pix/i/rsssitelogo.gif', $feed->get_image_url());
        $this->assertSame('moodle', $feed->get_image_title());
        $this->assertSame('http://moodle.org/', $feed->get_image_link());
        $this->assertEquals('140', $feed->get_image_width());
        $this->assertEquals('35', $feed->get_image_height());
        $this->assertNotEmpty($items = $feed->get_items());
        $this->assertCount(15, $items);
        $this->assertNotEmpty($itemone = $feed->get_item(0));
        $this->assertSame('Google HOP contest encourages pre-University students to work on Moodle', $itemone->get_title());
        $this->assertSame('http://moodle.org/mod/forum/discuss.php?d=85629', $itemone->get_link());
        $this->assertSame('http://moodle.org/mod/forum/discuss.php?d=85629', $itemone->get_id());
        $description = <<<EOD
by Martin Dougiamas. &nbsp;<p><p><img src="http://code.google.com/opensource/ghop/2007-8/images/ghoplogosm.jpg" align="right" style="margin:10px" />After their very successful <a href="http://code.google.com/soc/2007/">Summer of Code</a> program for University students, Google just announced their new <a href="http://code.google.com/opensource/ghop/2007-8/">Highly Open Participation contest</a>, designed to encourage pre-University students to get involved with open source projects via much smaller and diverse contributions.<br />
<br />
I'm very proud that Moodle has been selected as one of only <a href="http://code.google.com/opensource/ghop/2007-8/projects.html">ten open source projects</a> to take part in the inaugural year of this new contest.<br />
<br />
We have a <a href="http://code.google.com/p/google-highly-open-participation-moodle/issues/list">long list of small tasks</a> prepared already for students, but we would definitely like to see the Moodle community come up with more - so if you have any ideas for things you want to see done, please <a href="http://code.google.com/p/google-highly-open-participation-moodle/">send them to us</a>!  Just remember they can't take more than five days.<br />
<br />
Google will pay students US\$100 for every three tasks they successfully complete, plus send a cool T-shirt.  There are also grand prizes including an all-expenses-paid trip to Google HQ in Mountain View, California.  If you are (or know) a young student with an interest in Moodle then give it a go! <br />
<br />
You can find out all the details on the <a href="http://code.google.com/p/google-highly-open-participation-moodle/">Moodle/GHOP contest site</a>.</p></p>
EOD;
        $description = purify_html($description);
        $this->assertSame($description, $itemone->get_description());
        // TODO fix this so it uses $CFG by default.
        $this->assertSame(1196412453, $itemone->get_date('U'));
        // Last item.
        $this->assertNotEmpty($feed->get_item(14));
        // Past last item.
        $this->assertEmpty($feed->get_item(15));
    }
Exemplo n.º 5
0
	static function getArrayInfo($raw_data, $full = false){
		if(config_option("wysiwyg_tasks")){
			if($raw_data['type_content'] == "text"){
				$desc = nl2br(htmlspecialchars($raw_data['text']));
			}else{
				$desc = purify_html(nl2br($raw_data['text']));
			}
		}else{
			if($raw_data['type_content'] == "text"){
				$desc = htmlspecialchars($raw_data['text']);
			}else{
				$desc = html_to_text(html_entity_decode(nl2br($raw_data['text']), null, "UTF-8"));
			}
		}

		$member_ids = ObjectMembers::instance()->getCachedObjectMembers($raw_data['id']);
		$tmp_task = new ProjectTask();
		$tmp_task->setObjectId($raw_data['id']);
		$tmp_task->setId($raw_data['id']);
		$tmp_task->setAssignedToContactId($raw_data['assigned_to_contact_id']);
		
		$result = array(
			'id' => $raw_data['id'],
			't' => $raw_data['name'],
			'desc' => $desc,
			'members' => $member_ids,
			'c' => strtotime($raw_data['created_on']),
			'cid' => (int)$raw_data['created_by_id'],
			'otype' => $raw_data['object_subtype'],
			'pc' => (int)$raw_data['percent_completed'],
			'memPath' => str_replace('"',"'", str_replace("'", "\'", json_encode($tmp_task->getMembersToDisplayPath($member_ids))))
		);

		if ($full) {
			$result['description'] = $raw_data['text'];
		}

		$result['mas'] = (int)array_var($raw_data, 'multi_assignment');
			
		if ($raw_data['completed_by_id'] > 0) {
			$result['s'] = 1;
		}
			
		if ($raw_data['parent_id'] > 0) {
			$result['pid'] = (int)$raw_data['parent_id'];
		}
		//if ($this->getPriority() != 200)
		$result['pr'] = (int)$raw_data['priority'];

		if ($raw_data['milestone_id'] > 0) {
			$result['mid'] = (int)$raw_data['milestone_id'];
		}
			
		if ($raw_data['assigned_to_contact_id'] > 0) {
			$result['atid'] = (int)$raw_data['assigned_to_contact_id'];
		}
		$result['atName'] = $tmp_task->getAssignedToName();

		if ($raw_data['completed_by_id'] > 0) {
			$result['cbid'] = (int)$raw_data['completed_by_id'];
			$result['con'] = strtotime($raw_data['completed_on']);;
		}
			
		if ($raw_data['due_date'] != EMPTY_DATETIME) {
			$result['dd'] = strtotime($raw_data['due_date']) + logged_user()->getTimezone() * 3600;
			$result['udt'] = $raw_data['use_due_time'] ? 1 : 0;
		}
		if ($raw_data['start_date'] != EMPTY_DATETIME) {
			$result['sd'] = strtotime($raw_data['start_date']) + logged_user()->getTimezone() * 3600;
			$result['ust'] = $raw_data['use_start_time'] ? 1 : 0;
		}

		$time_estimate = $raw_data['time_estimate'];
		$result['te'] = $raw_data['time_estimate'];
		if ($time_estimate > 0) $result['et'] = DateTimeValue::FormatTimeDiff(new DateTimeValue(0), new DateTimeValue($time_estimate * 60), 'hm', 60) ;


		$result['tz'] = logged_user()->getTimezone() * 3600;

		$ot = $tmp_task->getOpenTimeslots();

		if ($ot){
			$users = array();
			$time = array();
			$paused = array();
			foreach ($ot as $t){
				if (!$t instanceof Timeslot) continue;
				$time[] = $t->getSeconds();
				$users[] = $t->getContactId();
				$paused[] = $t->isPaused()?1:0;
				if ($t->isPaused() && $t->getContactId() == logged_user()->getId()) {
					$result['wpt'] = $t->getPausedOn()->getTimestamp();
				}
			}
			$result['wt'] = $time;
			$result['wid'] = $users;
			$result['wp'] = $paused;
		}

		if ($raw_data['repeat_forever'] > 0 || $raw_data['repeat_num'] > 0 || $raw_data['repeat_end'] != EMPTY_DATETIME) {
			$result['rep'] = 1;
		}
		
		return $result;
	}
Exemplo n.º 6
0
			}
			echo render_object_link_form($task, $pre_linked_objects)
		
		?>
	</fieldset>	
	</div>
	<?php } // if ?>
		
   	
	<div>
                <?php 
                    if(config_option("wysiwyg_tasks")){
                        if(array_var($task_data, 'type_content') == "text"){
                            $ckEditorContent = purify_html(nl2br(array_var($task_data, 'text')));
                        }else{
                            $ckEditorContent = purify_html(nl2br(array_var($task_data, 'text')));
                        }                        
                ?>
		<?php echo label_tag(lang('description'), $genid . 'taskListFormDescription') ?>
                <div id="<?php echo $genid ?>ckcontainer" style="height: 100%">
                    <textarea cols="80" id="<?php echo $genid ?>ckeditor" name="task[text]" rows="10"><?php echo clean($ckEditorContent) ?></textarea>
                </div>
                <script>
                    var h = document.getElementById("<?php echo $genid ?>ckcontainer").offsetHeight;
                    if (h > 300) {
                        h = 280;
                        $("#<?php echo $genid ?>ckcontainer").css('height', (h+20)+'px'); 
                    }
                    var editor = CKEDITOR.replace('<?php echo $genid ?>ckeditor', {
                        height: h,
                        enterMode: CKEDITOR.ENTER_DIV,
Exemplo n.º 7
0
/**
 * @param object $feed
 * @param array $item
 * @param[out] array $author
 * @return multitype:multitype: string NULL number Ambigous <NULL, string, number> Ambigous <mixed, string> Ambigous <multitype:multitype:string Ambigous <NULL, string>  , multitype:multitype:string unknown  > multitype:NULL unknown
 */
function get_atom_elements($feed, $item, &$author)
{
    //$best_photo = array();
    $res = array();
    $found_author = $item->get_author();
    if ($found_author) {
        $author['author_name'] = unxmlify($found_author->get_name());
        $author['author_link'] = unxmlify($found_author->get_link());
        $author['author_is_feed'] = false;
    } else {
        $author['author_name'] = unxmlify($feed->get_title());
        $author['author_link'] = unxmlify($feed->get_permalink());
        $author['author_is_feed'] = true;
    }
    if (substr($author['author_link'], -1, 1) == '/') {
        $author['author_link'] = substr($author['author_link'], 0, -1);
    }
    $res['mid'] = base64url_encode(unxmlify($item->get_id()));
    $res['title'] = unxmlify($item->get_title());
    $res['body'] = unxmlify($item->get_content());
    $res['plink'] = unxmlify($item->get_link(0));
    $res['item_flags'] = ITEM_RSS;
    // removing the content of the title if its identically to the body
    // This helps with auto generated titles e.g. from tumblr
    if (title_is_body($res["title"], $res["body"])) {
        $res['title'] = "";
    }
    if ($res['plink']) {
        $base_url = implode('/', array_slice(explode('/', $res['plink']), 0, 3));
    } else {
        $base_url = '';
    }
    // look for a photo. We should check media size and find the best one,
    // but for now let's just find any author photo
    $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
    if ($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
        $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
        foreach ($base as $link) {
            if (!x($author, 'author_photo') || !$author['author_photo']) {
                if ($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar') {
                    $author['author_photo'] = unxmlify($link['attribs']['']['href']);
                }
            }
        }
    }
    $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
    if ($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['obj_type'][0]['data'], ACTIVITY_OBJ_PERSON)) {
        $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
        if ($base && count($base)) {
            foreach ($base as $link) {
                if ($link['attribs']['']['rel'] === 'alternate' && !$res['author_link']) {
                    $author['author_link'] = unxmlify($link['attribs']['']['href']);
                }
                if (!x($author, 'author_photo') || !$author['author_photo']) {
                    if ($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo') {
                        $author['author_photo'] = unxmlify($link['attribs']['']['href']);
                    }
                }
            }
        }
    }
    // check for a yahoo media element (github etc.)
    if (!$author['author_photo']) {
        $rawmedia = $item->get_item_tags(NAMESPACE_YMEDIA, 'thumbnail');
        if ($rawmedia && $rawmedia[0]['attribs']['']['url']) {
            $author['author_photo'] = strip_tags(unxmlify($rawmedia[0]['attribs']['']['url']));
        }
    }
    // No photo/profile-link on the item - look at the feed level
    if (!x($author, 'author_link') || !x($author, 'author_photo')) {
        $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
        if ($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
            $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
            foreach ($base as $link) {
                if ($link['attribs']['']['rel'] === 'alternate' && !$author['author_link']) {
                    $author['author_link'] = unxmlify($link['attribs']['']['href']);
                    $author['author_is_feed'] = true;
                }
                if (!$author['author_photo']) {
                    if ($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar') {
                        $author['author_photo'] = unxmlify($link['attribs']['']['href']);
                    }
                }
            }
        }
        $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
        if ($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['obj_type'][0]['data'], ACTIVITY_OBJ_PERSON)) {
            $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
            if ($base && count($base)) {
                foreach ($base as $link) {
                    if ($link['attribs']['']['rel'] === 'alternate' && !$res['author_link']) {
                        $author['author_link'] = unxmlify($link['attribs']['']['href']);
                    }
                    if (!x($author, 'author_photo')) {
                        if ($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo') {
                            $author['author_photo'] = unxmlify($link['attribs']['']['href']);
                        }
                    }
                }
            }
        }
    }
    $apps = $item->get_item_tags(NAMESPACE_STATUSNET, 'notice_info');
    if ($apps && $apps[0]['attribs']['']['source']) {
        $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
    }
    /*
     * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
     */
    $have_real_body = false;
    $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
    if ($rawenv) {
        $have_real_body = true;
        $res['body'] = $rawenv[0]['data'];
        $res['body'] = str_replace(array(' ', "\t", "\r", "\n"), array('', '', '', ''), $res['body']);
        // make sure nobody is trying to sneak some html tags by us
        $res['body'] = notags(base64url_decode($res['body']));
        // We could probably turn these old Friendica bbcode bookmarks into bookmark tags but we'd have to
        // create a term table item for them. For now just make sure they stay as links.
        $res['body'] = preg_replace('/\\[bookmark(.*?)\\](.*?)\\[\\/bookmark\\]/', '[url$1]$2[/url]', $res['body']);
    }
    $res['body'] = limit_body_size($res['body']);
    // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
    // the content type. Our own network only emits text normally, though it might have been converted to
    // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
    // have to assume it is all html and needs to be purified.
    // It doesn't matter all that much security wise - because before this content is used anywhere, we are
    // going to escape any tags we find regardless, but this lets us import a limited subset of html from
    // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
    // html.
    if (strpos($res['body'], '<') !== false && strpos($res['body'], '>') !== false) {
        $res['body'] = reltoabs($res['body'], $base_url);
        $res['body'] = html2bb_video($res['body']);
        $res['body'] = oembed_html2bbcode($res['body']);
        $res['body'] = purify_html($res['body']);
        $res['body'] = @html2bbcode($res['body']);
    } elseif (!$have_real_body) {
        // it's not one of our messages and it has no tags
        // so it's probably just text. We'll escape it just to be safe.
        $res['body'] = escape_tags($res['body']);
    }
    if ($res['plink'] && $res['title']) {
        $res['body'] = '#^[url=' . $res['plink'] . ']' . $res['title'] . '[/url]' . "\n\n" . $res['body'];
        $terms = array();
        $terms[] = array('otype' => TERM_OBJ_POST, 'type' => TERM_BOOKMARK, 'url' => $res['plink'], 'term' => $res['title']);
    } elseif ($res['plink']) {
        $res['body'] = '#^[url]' . $res['plink'] . '[/url]' . "\n\n" . $res['body'];
        $terms = array();
        $terms[] = array('otype' => TERM_OBJ_POST, 'type' => TERM_BOOKMARK, 'url' => $res['plink'], 'term' => $res['plink']);
    }
    $private = $item->get_item_tags(NAMESPACE_DFRN, 'private');
    if ($private && intval($private[0]['data']) > 0) {
        $res['item_private'] = intval($private[0]['data']) ? 1 : 0;
    } else {
        $res['item_private'] = 0;
    }
    $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
    if ($rawlocation) {
        $res['location'] = unxmlify($rawlocation[0]['data']);
    }
    $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'published');
    if ($rawcreated) {
        $res['created'] = unxmlify($rawcreated[0]['data']);
    }
    $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'updated');
    if ($rawedited) {
        $res['edited'] = unxmlify($rawedited[0]['data']);
    }
    if (x($res, 'edited') && !x($res, 'created')) {
        $res['created'] = $res['edited'];
    }
    if (!$res['created']) {
        $res['created'] = $item->get_date('c');
    }
    if (!$res['edited']) {
        $res['edited'] = $item->get_date('c');
    }
    // Disallow time travelling posts
    $d1 = strtotime($res['created']);
    $d2 = strtotime($res['edited']);
    $d3 = strtotime('now');
    if ($d1 > $d3) {
        $res['created'] = datetime_convert();
    }
    if ($d2 > $d3) {
        $res['edited'] = datetime_convert();
    }
    $res['created'] = datetime_convert('UTC', 'UTC', $res['created']);
    $res['edited'] = datetime_convert('UTC', 'UTC', $res['edited']);
    $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
    if (!$rawowner) {
        $rawowner = $item->get_item_tags(NAMESPACE_ZOT, 'owner');
    }
    if ($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']) {
        $author['owner_name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
    } elseif ($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']) {
        $author['owner_name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
    }
    if ($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']) {
        $author['owner_link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
    } elseif ($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']) {
        $author['owner_link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
    }
    if ($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
        $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
        foreach ($base as $link) {
            if (!x($author, 'owner_photo') || !$author['owner_photo']) {
                if ($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar') {
                    $author['owner_photo'] = unxmlify($link['attribs']['']['href']);
                }
            }
        }
    }
    $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS, 'point');
    if ($rawgeo) {
        $res['coord'] = unxmlify($rawgeo[0]['data']);
    }
    $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
    // select between supported verbs
    if ($rawverb) {
        $res['verb'] = unxmlify($rawverb[0]['data']);
    }
    // translate OStatus unfollow to activity streams if it happened to get selected
    if (x($res, 'verb') && $res['verb'] === 'http://ostatus.org/schema/1.0/unfollow') {
        $res['verb'] = ACTIVITY_UNFOLLOW;
    }
    $cats = $item->get_categories();
    if ($cats) {
        if (is_null($terms)) {
            $terms = array();
        }
        foreach ($cats as $cat) {
            $term = $cat->get_term();
            if (!$term) {
                $term = $cat->get_label();
            }
            $scheme = $cat->get_scheme();
            $termurl = '';
            if ($scheme && $term && stristr($scheme, 'X-DFRN:')) {
                $termtype = substr($scheme, 7, 1) === '#' ? TERM_HASHTAG : TERM_MENTION;
                $termurl = unxmlify(substr($scheme, 9));
            } else {
                $termtype = TERM_CATEGORY;
            }
            $termterm = notags(trim(unxmlify($term)));
            if ($termterm) {
                $terms[] = array('otype' => TERM_OBJ_POST, 'type' => $termtype, 'url' => $termurl, 'term' => $termterm);
            }
        }
    }
    if (!is_null($terms)) {
        $res['term'] = $terms;
    }
    $attach = $item->get_enclosures();
    if ($attach) {
        $res['attach'] = array();
        foreach ($attach as $att) {
            $len = intval($att->get_length());
            $link = str_replace(array(',', '"'), array('%2D', '%22'), notags(trim(unxmlify($att->get_link()))));
            $title = str_replace(array(',', '"'), array('%2D', '%22'), notags(trim(unxmlify($att->get_title()))));
            $type = str_replace(array(',', '"'), array('%2D', '%22'), notags(trim(unxmlify($att->get_type()))));
            if (strpos($type, ';')) {
                $type = substr($type, 0, strpos($type, ';'));
            }
            if (!$link || strpos($link, 'http') !== 0) {
                continue;
            }
            if (!$title) {
                $title = ' ';
            }
            if (!$type) {
                $type = 'application/octet-stream';
            }
            $res['attach'][] = array('href' => $link, 'length' => $len, 'type' => $type, 'title' => $title);
        }
    }
    $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
    if ($rawobj) {
        $obj = array();
        $child = $rawobj[0]['child'];
        if ($child[NAMESPACE_ACTIVITY]['obj_type'][0]['data']) {
            $res['obj_type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data'];
            $obj['type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data'];
        }
        if (x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data']) {
            $obj['id'] = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'];
        }
        if (x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
            $obj['link'] = encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']);
        }
        if (x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data']) {
            $obj['title'] = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'];
        }
        if (x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
            $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
            if (!$body) {
                $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
            }
            // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
            $obj['orig'] = xmlify($body);
            if (strpos($body, '<') !== false || strpos($body, '>') !== false) {
                $body = purify_html($body);
                $body = html2bbcode($body);
            }
            $obj['content'] = $body;
        }
        $res['object'] = $obj;
    }
    $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
    if ($rawobj) {
        $obj = array();
        $child = $rawobj[0]['child'];
        if ($child[NAMESPACE_ACTIVITY]['obj_type'][0]['data']) {
            $res['tgt_type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data'];
            $obj['type'] = $child[NAMESPACE_ACTIVITY]['obj_type'][0]['data'];
        }
        if (x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data']) {
            $obj['id'] = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'];
        }
        if (x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
            $obj['link'] = encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']);
        }
        if (x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data']) {
            $obj['title'] = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'];
        }
        if (x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
            $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
            if (!$body) {
                $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
            }
            // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
            $obj['orig'] = xmlify($body);
            if (strpos($body, '<') !== false || strpos($body, '>') !== false) {
                $body = purify_html($body);
                $body = html2bbcode($body);
            }
            $obj['content'] = $body;
        }
        $res['target'] = $obj;
    }
    $res['public_policy'] = 'specific';
    $res['comment_policy'] = 'none';
    $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
    call_hooks('parse_atom', $arr);
    logger('get_atom_elements: author: ' . print_r($author, true), LOGGER_DATA);
    logger('get_atom_elements: ' . print_r($res, true), LOGGER_DATA);
    return $res;
}
Exemplo n.º 8
0
            } else {
                $real_start = $event_start;
            }
            if ($event->getDueDate() instanceof DateTimeValue) {
                $real_duration = new DateTimeValue($event->getDueDate()->getTimestamp() + 3600 * logged_user()->getTimezone());
            } else {
                $real_duration = $event_duration;
            }
        }
    }
    $pre_tf = $real_start->getDay() == $real_duration->getDay() ? '' : 'D j, ';
    $ev_hour_text = format_date($real_start, $pre_tf . $timeformat, 0) . " - " . format_date($real_duration, $pre_tf . $timeformat, 0);
    $assigned = "";
    if ($event instanceof ProjectTask && $event->getAssignedToContactId() > 0) {
        $assigned = "<br>" . lang('assigned to') . ': ' . $event->getAssignedToName();
        $tipBody = purify_html($event->getText());
    } else {
        $tipBody = $ev_hour_text . $assigned . (trim(clean($event->getDescription())) != '' ? '<br><br>' . clean($event->getDescription()) : '');
        $tipBody = str_replace(array("\r", "\n"), array(' ', '<br>'), $tipBody);
    }
    if (strlen_utf($tipBody) > 200) {
        $tipBody = substr_utf($tipBody, 0, strpos($tipBody, ' ', 200)) . ' ...';
    }
    ?>
												<script>
													if (<?php 
    echo $top;
    ?>
 < scroll_to || scroll_to == -1) {
														scroll_to = <?php 
    echo $top;
Exemplo n.º 9
0
<div class="print-view-message">

<div class="header">
<h1><?php echo clean($message->getObjectName()); ?></h1>
<b><?php echo lang('from') ?>:</b> <?php echo clean($message->getCreatedByDisplayName()) ?><br />
<b><?php echo lang('date') ?>:</b> <?php echo format_datetime($message->getUpdatedOn(), null, logged_user()->getTimezone()) ?><br />
<b><?php /*FIXME echo lang('workspace') ?>:</b> <?php echo clean($message->getWorkspacesNamesCSV()) */?><br />
</div>

<div class="body">
<?php 
    if($message->getTypeContent() == "text"){
        echo escape_html_whitespace(convert_to_links(clean($message->getText())));
    }else{
        echo purify_html(nl2br($message->getText()));
    }
?>
</div>

<?php
$i = 0;
$comments = $message->getComments();
if (count($comments) > 0) {
?>
<div class="comments">
<h2><?php echo lang("comments") ?></h2>
<?php foreach ($comments as $comment) {
	$i++;
?>
	<div class="comment">
Exemplo n.º 10
0
/**
 * Given raw text (eg typed in by a user), this function cleans it up
 * and removes any nasty tags that could mess up Moodle pages.
 *
 * @uses FORMAT_MOODLE
 * @uses FORMAT_PLAIN
 * @uses ALLOWED_TAGS
 * @param string $text The text to be cleaned
 * @param int $format Identifier of the text format to be used
 *            (FORMAT_MOODLE, FORMAT_HTML, FORMAT_PLAIN, FORMAT_WIKI, FORMAT_MARKDOWN)
 * @return string The cleaned up text
 */
function clean_text($text, $format = FORMAT_MOODLE)
{
    global $ALLOWED_TAGS, $CFG;
    if (empty($text) or is_numeric($text)) {
        return (string) $text;
    }
    switch ($format) {
        case FORMAT_PLAIN:
        case FORMAT_MARKDOWN:
            return $text;
        default:
            if (!empty($CFG->enablehtmlpurifier)) {
                $text = purify_html($text);
            } else {
                /// Fix non standard entity notations
                $text = preg_replace('/(&#[0-9]+)(;?)/', "\\1;", $text);
                $text = preg_replace('/(&#x[0-9a-fA-F]+)(;?)/', "\\1;", $text);
                /// Remove tags that are not allowed
                $text = strip_tags($text, $ALLOWED_TAGS);
                /// Clean up embedded scripts and , using kses
                $text = cleanAttributes($text);
                /// Again remove tags that are not allowed
                $text = strip_tags($text, $ALLOWED_TAGS);
            }
            /// Remove potential script events - some extra protection for undiscovered bugs in our code
            $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text);
            $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text);
            return $text;
    }
}
Exemplo n.º 11
0
	<fieldset>
		<legend><?php echo lang('linked objects') ?></legend>
		<?php echo render_object_link_form($object) ?>
	</fieldset>	
	</div>
	<?php } // if ?>
	
	<?php
		if(config_option("wysiwyg_messages")){
			if($message->isNew()) {
				$ckEditorContent = '';
			} else {
				if(array_var($message_data, 'type_content') == "text"){
					$ckEditorContent = nl2br(htmlspecialchars(array_var($message_data, 'text')));
				}else{
					$ckEditorContent = purify_html(nl2br(array_var($message_data, 'text')));
				}
			}
		?>
        <div>
            <?php echo label_tag(lang('text'), $genid . 'messageFormText', false) ?>
            <div id="<?php echo $genid ?>ckcontainer" style="height: 350px">
                <textarea cols="80" id="<?php echo $genid ?>ckeditor" name="message[text]" rows="10"><?php echo clean($ckEditorContent) ?></textarea>
            </div>
        </div>
        
        <script>
            var h = document.getElementById("<?php echo $genid ?>ckcontainer").offsetHeight;
            var editor = CKEDITOR.replace('<?php echo $genid ?>ckeditor', {
            	height: (h-60) + 'px',
            	enterMode: CKEDITOR.ENTER_DIV,
Exemplo n.º 12
0
	function display_content() {
		
		$file = ProjectFiles::findById(get_id());
		if (!$file instanceof ProjectFile) {
			die(lang("file dnx"));
		}
		if (!$file->canView(logged_user())) {
			die(lang("no access permissions"));
		}
		
		if (defined('SANDBOX_URL')) {
			$html_content = $file->getFileContentWithRealUrls();
		} else {
			$html_content = purify_html($file->getFileContentWithRealUrls());
		}
		$charset = "";
		if ($file->getTypeString() == "text/html") {
			$encoding = detect_encoding($html_content, array('UTF-8', 'ISO-8859-1', 'WINDOWS-1252'));
			$charset = ";charset=".$encoding;
		}
		
		if ($file->getTypeString() == 'text/html') {
			// Include stylesheet from FCK Editor
			$css = '<style type="text/css">';
			$css .= file_get_contents(ROOT.'/public/assets/javascript/ckeditor/contents.css');
			$css .= '</style>';
			$html_content = $css.$html_content;
		}
		
		header("Expires: " . gmdate("D, d M Y H:i:s", mktime(date("H") + 2, date("i"), date("s"), date("m"), date("d"), date("Y"))) . " GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Content-Type: " . $file->getTypeString() . $charset);
		header("Content-Length: " . (string) strlen($html_content));

		print($html_content);
		die();
	}
Exemplo n.º 13
0
 public function test_allowed_schemes()
 {
     // First standard schemas.
     $text = '<a href="http://www.example.com/course/view.php?id=5">link</a>';
     $this->assertSame($text, purify_html($text));
     $text = '<a href="https://www.example.com/course/view.php?id=5">link</a>';
     $this->assertSame($text, purify_html($text));
     $text = '<a href="ftp://user@ftp.example.com/some/file.txt">link</a>';
     $this->assertSame($text, purify_html($text));
     $text = '<a href="nntp://example.com/group/123">link</a>';
     $this->assertSame($text, purify_html($text));
     $text = '<a href="news:groupname">link</a>';
     $this->assertSame($text, purify_html($text));
     $text = '<a href="mailto:user@example.com">link</a>';
     $this->assertSame($text, purify_html($text));
     // Extra schemes allowed in moodle.
     $text = '<a href="irc://irc.example.com/3213?pass">link</a>';
     $this->assertSame($text, purify_html($text));
     $text = '<a href="rtsp://www.example.com/movie.mov">link</a>';
     $this->assertSame($text, purify_html($text));
     $text = '<a href="rtmp://www.example.com/video.f4v">link</a>';
     $this->assertSame($text, purify_html($text));
     $text = '<a href="teamspeak://speak.example.com/?par=val?par2=val2">link</a>';
     $this->assertSame($text, purify_html($text));
     $text = '<a href="gopher://gopher.example.com/resource">link</a>';
     $this->assertSame($text, purify_html($text));
     $text = '<a href="mms://www.example.com/movie.mms">link</a>';
     $this->assertSame($text, purify_html($text));
     // Now some borked or dangerous schemes.
     $text = '<a href="javascript://www.example.com">link</a>';
     $this->assertSame('<a>link</a>', purify_html($text));
     $text = '<a href="hmmm://www.example.com">link</a>';
     $this->assertSame('<a>link</a>', purify_html($text));
 }
Exemplo n.º 14
0
                                    $img_url = image_url('/16x16/task_end.png');
                                    $tip_pre = 'end_';
                                } else {
                                    $tip_title = lang('start of task');
                                    $img_url = image_url('/16x16/task_start.png');
                                    $tip_pre = 'st_';
                                }
                            }
                            $tip_pre .= gen_id() . "_";
                            $count++;
                            if ($count <= $max_events_to_show) {
                                $color = 'B1BFAC';
                                $subject = clean($task->getObjectName()) . '- <span class="italic">' . lang('task') . '</span>';
                                $cal_text = clean($task->getObjectName());
                                $tip_text = str_replace("\r", '', lang('assigned to') . ': ' . clean($task->getAssignedToName()) . (trim($task->getText()) == '' ? '' : '<br><br>' . html_to_text($task->getText())));
                                $tip_text = purify_html(str_replace("\n", '<br>', $tip_text));
                                if (strlen_utf($tip_text) > 200) {
                                    $tip_text = substr_utf($tip_text, 0, strpos($tip_text, ' ', 200)) . ' ...';
                                }
                                ?>
													<div id="m_ta_div_<?php 
                                echo $tip_pre . $task->getId();
                                ?>
" class="<?php 
                                echo "og-wsname-color-{$ws_color}";
                                ?>
" style="height:20px;margin: 1px;padding-left:1px;padding-bottom:0px;border-radius:4px;border: 1px solid;border-color:<?php 
                                echo $border_color;
                                ?>
;<?php 
                                echo $extra_style;
Exemplo n.º 15
0
 public function test_purify_html_ruby()
 {
     $this->resetAfterTest();
     $ruby = "<p><ruby><rb>京都</rb><rp>(</rp><rt>きょうと</rt><rp>)</rp></ruby>は" . "<ruby><rb>日本</rb><rp>(</rp><rt>にほん</rt><rp>)</rp></ruby>の" . "<ruby><rb>都</rb><rp>(</rp><rt>みやこ</rt><rp>)</rp></ruby>です。</p>";
     $illegal = '<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>';
     $cleaned = purify_html($ruby . $illegal);
     $this->assertEquals($ruby, $cleaned);
 }
Exemplo n.º 16
0
 protected function clean_up($text)
 {
     return purify_html($text, FORMAT_HTML);
 }
Exemplo n.º 17
0
    }
    if ($message->canDelete(logged_user())) {
        if ($message->isTrashed()) {
            add_page_action(lang('restore from trash'), "javascript:if(confirm(lang('confirm restore objects'))) og.openLink('" . $message->getUntrashUrl() . "');", 'ico-restore', null, null, true);
            add_page_action(lang('delete permanently'), "javascript:if(confirm(lang('confirm delete permanently'))) og.openLink('" . $message->getDeletePermanentlyUrl() . "');", 'ico-delete', null, null, true);
        } else {
            add_page_action(lang('move to trash'), "javascript:if(confirm(lang('confirm move to trash'))) og.openLink('" . $message->getTrashUrl() . "');", 'ico-trash', null, null, true);
        }
    }
    // if
    add_page_action(lang('print view'), $message->getPrintViewUrl(), "ico-print", "_blank");
    ?>

<div style="padding:7px">
<div class="message">
<?php 
    if ($message->getTypeContent() == "text") {
        $content = escape_html_whitespace(convert_to_links(clean($message->getText())));
    } else {
        $content = '<div class="wysiwyg-description">' . convert_to_links(purify_html(nl2br($message->getText()))) . '</div>';
    }
    tpl_assign("content", $content);
    tpl_assign("object", $message);
    tpl_assign('iconclass', $message->isTrashed() ? 'ico-large-message-trashed' : ($message->isArchived() ? 'ico-large-message-archived' : 'ico-large-message'));
    $this->includeTemplate(get_template_path('view', 'co'));
    ?>
</div>
</div>
<?php 
}
//if isset
Exemplo n.º 18
0
function mod_8_settings($b)
{
    global $config, $mod;
    //if ($b === 'infinity' && $mod['type'] !== ADMIN)
    //	error('Settings temporarily disabled for this board.');
    if (!in_array($b, $mod['boards']) and $mod['boards'][0] != '*') {
        error($config['error']['noaccess']);
    }
    if (!hasPermission($config['mod']['edit_settings'], $b)) {
        error($config['error']['noaccess']);
    }
    if (!openBoard($b)) {
        error("Could not open board!");
    }
    $possible_languages = array_diff(scandir('inc/locale/'), array('..', '.', '.tx', 'README.md'));
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $board_type = $_POST['board_type'];
        $imgboard = $board_type == 'imgboard';
        $txtboard = $board_type == 'txtboard';
        $fileboard = $board_type == 'fileboard';
        $title = $_POST['title'];
        $subtitle = $_POST['subtitle'];
        $country_flags = isset($_POST['country_flags']) ? 'true' : 'false';
        $field_disable_name = isset($_POST['field_disable_name']) ? 'true' : 'false';
        $enable_embedding = isset($_POST['enable_embedding']) ? 'true' : 'false';
        $force_image_op = $imgboard && isset($_POST['force_image_op']) ? 'true' : 'false';
        $disable_images = $txtboard ? 'true' : 'false';
        $poster_ids = isset($_POST['poster_ids']) ? 'true' : 'false';
        $show_sages = isset($_POST['show_sages']) ? 'true' : 'false';
        $auto_unicode = isset($_POST['auto_unicode']) ? 'true' : 'false';
        $strip_combining_chars = isset($_POST['strip_combining_chars']) ? 'true' : 'false';
        $allow_roll = isset($_POST['allow_roll']) ? 'true' : 'false';
        $image_reject_repost = isset($_POST['image_reject_repost']) ? 'true' : 'false';
        $image_reject_repost_in_thread = isset($_POST['image_reject_repost_in_thread']) ? 'true' : 'false';
        $early_404 = isset($_POST['early_404']) ? 'true' : 'false';
        $allow_delete = isset($_POST['allow_delete']) ? 'true' : 'false';
        $allow_flash = $imgboard && isset($_POST['allow_flash']) ? '$config[\'allowed_ext_files\'][] = \'swf\';' : '';
        $allow_pdf = $imgboard && isset($_POST['allow_pdf']) ? '$config[\'allowed_ext_files\'][] = \'pdf\';' : '';
        $code_tags = isset($_POST['code_tags']) ? '$config[\'additional_javascript\'][] = \'js/code_tags/run_prettify.js\';$config[\'markup\'][] = array("/\\[code\\](.+?)\\[\\/code\\]/ms", "<code><pre class=\'prettyprint\' style=\'display:inline-block\'>\\$1</pre></code>");' : '';
        $katex = isset($_POST['katex']) ? '$config[\'katex\'] = true;$config[\'additional_javascript\'][] = \'js/katex/katex.min.js\'; $config[\'markup\'][] = array("/\\[tex\\](.+?)\\[\\/tex\\]/ms", "<span class=\'tex\'>\\$1</span>"); $config[\'additional_javascript\'][] = \'js/katex-enable.js\';' : '';
        $user_flags = isset($_POST['user_flags']) ? "if (file_exists('{$b}/flags.php')) { include 'flags.php'; }\n" : '';
        $captcha = isset($_POST['captcha']) ? 'true' : 'false';
        $force_subject_op = isset($_POST['force_subject_op']) ? 'true' : 'false';
        $force_flag = isset($_POST['force_flag']) ? 'true' : 'false';
        $tor_posting = isset($_POST['tor_posting']) ? 'true' : 'false';
        $tor_image_posting = isset($_POST['tor_image_posting']) ? 'true' : 'false';
        $robot_enable = isset($_POST['robot_enable']) ? 'true' : 'false';
        $new_thread_capt = isset($_POST['new_thread_capt']) ? 'true' : 'false';
        $oekaki = ($imgboard || $fileboard) && isset($_POST['oekaki']) ? 'true' : 'false';
        $view_bumplock = isset($_POST['view_bumplock']) ? '-1' : 'MOD';
        if ($tor_image_posting === 'true' && isset($_POST['meta_noindex'])) {
            error('Please index your board to enable this.');
        }
        if ($_POST['locale'] !== 'en' && in_array($_POST['locale'], $possible_languages)) {
            $locale = "\$config['locale'] = '{$_POST['locale']}.UTF-8';";
        } else {
            $locale = '';
        }
        if (isset($_POST['max_images']) && (int) $_POST['max_images'] && (int) $_POST['max_images'] <= 5) {
            $_POST['max_images'] = (int) $_POST['max_images'];
            $multiimage = "\$config['max_images'] = {$_POST['max_images']};\n\t\t\t\t\t   \$config['additional_javascript'][] = 'js/multi-image.js';";
        } else {
            $multiimage = '';
        }
        if (isset($_POST['custom_assets'])) {
            $assets = "\$config['custom_assets'] = true;\n\t\t\t\t           \$config['spoiler_image'] = 'static/assets/{$b}/spoiler.png';\n\t\t\t\t           \$config['image_deleted'] = 'static/assets/{$b}/deleted.png';\n\t\t\t\t           \$config['no_file_image'] = 'static/assets/{$b}/no-file.png';\n\t\t\t\t";
        } else {
            $assets = '';
        }
        $file_board = '';
        if ($fileboard) {
            $force_image_op = true;
            $file_board = "\$config['threads_per_page'] = 30;\n\t\t\t\t\t       \$config['file_board'] = true;\n\t\t\t\t\t       \$config['threads_preview'] = 0;\n\t\t\t\t               \$config['threads_preview_sticky'] = 0;\n\t\t\t\t\t       \$config['allowed_ext_files'] = array();\n";
            if (isset($_POST['allowed_type'])) {
                foreach ($_POST['allowed_type'] as $val) {
                    if (in_array($val, $config['fileboard_allowed_types'])) {
                        $file_board .= "\$config['allowed_ext_files'][] = '{$val}';\n";
                    }
                }
            }
            if (isset($_POST['allowed_ext_op'])) {
                $file_board .= "\$config['allowed_ext_op'] = \$config['allowed_ext_files'];\n";
                if (isset($_POST['allowed_ext_op_video'])) {
                    $file_board .= "\$config['allowed_ext_op'][] = 'webm';\n\t\t\t\t\t\t\t\t\$config['allowed_ext_op'][] = 'mp4';\n";
                }
            }
            if (isset($_POST['tag_id'])) {
                $file_board .= "\$config['allowed_tags'] = array();\n";
                foreach ($_POST['tag_id'] as $id => $v) {
                    $file_board .= "\$config['allowed_tags'][";
                    $file_board .= 'base64_decode("';
                    $file_board .= base64_encode($_POST['tag_id'][$id]);
                    $file_board .= '")';
                    $file_board .= "] = ";
                    $file_board .= 'base64_decode("';
                    $file_board .= base64_encode($_POST['tag_desc'][$id]);
                    $file_board .= '")';
                    $file_board .= ";\n";
                }
            }
        }
        $anal_filenames = $fileboard && isset($_POST['anal_filenames']) ? "\$config['filename_func'] = 'filename_func';\n" : '';
        $anonymous = base64_encode($_POST['anonymous']);
        $blotter = base64_encode(purify_html(html_entity_decode($_POST['blotter'])));
        $add_to_config = @file_get_contents($b . '/extra_config.php');
        $replace = '';
        if (isset($_POST['replace'])) {
            if (sizeof($_POST['replace']) > 200 || sizeof($_POST['with']) > 200) {
                error(_('Sorry, max 200 wordfilters allowed.'));
            }
            if (count($_POST['replace']) == count($_POST['with'])) {
                foreach ($_POST['replace'] as $i => $r) {
                    if ($r !== '') {
                        $w = $_POST['with'][$i];
                        if (strlen($w) > 255) {
                            error(sprintf(_('Sorry, %s is too long. Max replacement is 255 characters'), utf8tohtml($w)));
                        }
                        $replace .= '$config[\'wordfilters\'][] = array(base64_decode(\'' . base64_encode($r) . '\'), base64_decode(\'' . base64_encode($w) . '\'));';
                    }
                }
            }
            if (is_billion_laughs($_POST['replace'], $_POST['with'])) {
                error(_('Wordfilters may not wordfilter previous wordfilters. For example, if a filters to bb and b filters to cc, that is not allowed.'));
            }
        }
        if (isset($_POST['hour_max_threads']) && (int) $_POST['hour_max_threads'] > 0 && (int) $_POST['hour_max_threads'] < 101) {
            $hour_max_threads = (int) $_POST['hour_max_threads'];
        } else {
            $hour_max_threads = 'false';
        }
        if (isset($_POST['max_pages'])) {
            $mp = (int) $_POST['max_pages'];
            if ($mp > 25 || $mp < 1) {
                $max_pages = 15;
            } else {
                $max_pages = $mp;
            }
        } else {
            $max_pages = 15;
        }
        if (isset($_POST['reply_limit'])) {
            $rl = (int) $_POST['reply_limit'];
            if ($rl > 750 || $rl < 250 || $rl % 25) {
                $reply_limit = 250;
            } else {
                $reply_limit = $rl;
            }
        } else {
            $reply_limit = 250;
        }
        if (isset($_POST['max_newlines'])) {
            $mn = (int) $_POST['max_newlines'];
            if ($mn < 20 || $mn > 300) {
                $max_newlines = 0;
            } else {
                $max_newlines = $mn;
            }
        } else {
            $max_newlines = 0;
        }
        if (isset($_POST['min_body'])) {
            $mb = (int) $_POST['min_body'];
            if ($mb < 0 || $mb > 1024) {
                $min_body = 0;
            } else {
                $min_body = $mb;
            }
        } else {
            $min_body = 0;
        }
        if (!(strlen($title) < 40)) {
            error('Invalid title');
        }
        if (!(strlen($subtitle) < 200)) {
            error('Invalid subtitle');
        }
        $query = prepare('UPDATE ``boards`` SET `title` = :title, `subtitle` = :subtitle, `indexed` = :indexed, `public_bans` = :public_bans, `public_logs` = :public_logs, `8archive` = :8archive WHERE `uri` = :uri');
        $query->bindValue(':title', $title);
        $query->bindValue(':subtitle', $subtitle);
        $query->bindValue(':uri', $b);
        $query->bindValue(':indexed', !isset($_POST['meta_noindex']));
        $query->bindValue(':public_bans', isset($_POST['public_bans']));
        $query->bindValue(':public_logs', (int) $_POST['public_logs']);
        $query->bindValue(':8archive', isset($_POST['8archive']));
        $query->execute() or error(db_error($query));
        $config_file = <<<EOT
<?php
\$config['country_flags'] = {$country_flags};
\$config['field_disable_name'] = {$field_disable_name};
\$config['enable_embedding'] = {$enable_embedding};
\$config['force_image_op'] = {$force_image_op};
\$config['disable_images'] = {$disable_images};
\$config['poster_ids'] = {$poster_ids};
\$config['show_sages'] = {$show_sages};
\$config['auto_unicode'] = {$auto_unicode};
\$config['strip_combining_chars'] = {$strip_combining_chars};
\$config['allow_roll'] = {$allow_roll};
\$config['image_reject_repost'] = {$image_reject_repost};
\$config['image_reject_repost_in_thread'] = {$image_reject_repost_in_thread};
\$config['early_404'] = {$early_404};
\$config['allow_delete'] = {$allow_delete};
\$config['anonymous'] = base64_decode('{$anonymous}');
\$config['blotter'] = base64_decode('{$blotter}');
\$config['stylesheets']['Custom'] = 'board/{$b}.css';
\$config['default_stylesheet'] = array('Custom', \$config['stylesheets']['Custom']);
\$config['captcha']['enabled'] = {$captcha};
\$config['force_subject_op'] = {$force_subject_op};
\$config['force_flag'] = {$force_flag};
\$config['tor_posting'] = {$tor_posting};
\$config['tor_image_posting'] = {$tor_image_posting};
\$config['robot_enable'] = {$robot_enable};
\$config['new_thread_capt'] = {$new_thread_capt};
\$config['hour_max_threads'] = {$hour_max_threads};
\$config['reply_limit'] = {$reply_limit};
\$config['max_pages'] = {$max_pages};
\$config['max_newlines'] = {$max_newlines};
\$config['oekaki'] = {$oekaki};
\$config['min_body'] = {$min_body};
\$config['mod']['view_bumplock'] = {$view_bumplock};
{$code_tags} {$katex} {$replace} {$multiimage} {$allow_flash} {$allow_pdf} {$user_flags} 
{$assets}
{$locale}
{$anal_filenames}
{$file_board}

if (\$config['disable_images'])
\t\$config['max_pages'] = 10000;

{$add_to_config}
EOT;
        // Clean up our CSS...no more expression() or off-site URLs.
        $clean_css = preg_replace('/expression\\s*\\(/', '', $_POST['css']);
        $matched = array();
        preg_match_all("#{$config['link_regex']}#im", $clean_css, $matched);
        if (isset($matched[0])) {
            foreach ($matched[0] as $match) {
                $match_okay = false;
                foreach ($config['allowed_offsite_urls'] as $allowed_url) {
                    if (strpos($match, $allowed_url) !== false && strpos($match, '#') === false && strpos($match, '?') === false && strpos($match, ';') === false) {
                        $match_okay = true;
                    }
                }
                if ($match_okay !== true) {
                    error(sprintf(_("Off-site link \"%s\" is not allowed in the board stylesheet"), $match));
                }
            }
        }
        //Filter out imports from sites with potentially unsafe content
        $match_imports = '@import[^;]*';
        $matched = array();
        preg_match_all("#{$match_imports}#im", $clean_css, $matched);
        $unsafe_import_urls = array('https://a.pomf.se/');
        if (isset($matched[0])) {
            foreach ($matched[0] as $match) {
                $match_okay = true;
                foreach ($unsafe_import_urls as $unsafe_import_url) {
                    if (strpos($match, $unsafe_import_url) !== false && strpos($match, '#') === false) {
                        $match_okay = false;
                    }
                }
                if ($match_okay !== true) {
                    error(sprintf(_("Potentially unsafe import \"%s\" is not allowed in the board stylesheet"), $match));
                }
            }
        }
        $query = query('SELECT `uri`, `title`, `subtitle` FROM ``boards`` WHERE `8archive` = TRUE');
        file_write('8archive.json', json_encode($query->fetchAll(PDO::FETCH_ASSOC)));
        file_write($b . '/config.php', $config_file);
        file_write('stylesheets/board/' . $b . '.css', $clean_css);
        $_config = $config;
        unset($config['wordfilters']);
        // Faster than openBoard and bypasses cache...we're trusting the PHP output
        // to be safe enough to run with every request, we can eval it here.
        eval(str_replace('flags.php', "{$b}/flags.php", preg_replace('/^\\<\\?php$/m', '', $config_file)));
        // czaks: maybe reconsider using it, now that config is cached?
        // be smarter about rebuilds...only some changes really require us to rebuild all threads
        if ($_config['captcha']['enabled'] != $config['captcha']['enabled'] || $_config['new_thread_capt'] != $config['new_thread_capt'] || $_config['captcha']['extra'] != $config['captcha']['extra'] || $_config['blotter'] != $config['blotter'] || $_config['field_disable_name'] != $config['field_disable_name'] || $_config['show_sages'] != (isset($config['show_sages']) && $config['show_sages'])) {
            buildIndex();
            $query = query(sprintf("SELECT `id` FROM ``posts_%s`` WHERE `thread` IS NULL", $b)) or error(db_error());
            while ($post = $query->fetch(PDO::FETCH_ASSOC)) {
                buildThread($post['id']);
            }
        }
        modLog('Edited board settings', $b);
    }
    $query = prepare('SELECT * FROM boards WHERE uri = :board');
    $query->bindValue(':board', $b);
    $query->execute() or error(db_error($query));
    $board = $query->fetchAll()[0];
    // Clean the cache
    if ($config['cache']['enabled']) {
        cache::delete('board_' . $board['uri']);
        cache::delete('all_boards');
        cache::delete('config_' . $board['uri']);
        cache::delete('events_' . $board['uri']);
        unlink('tmp/cache/locale_' . $board['uri']);
    }
    $css = @file_get_contents('stylesheets/board/' . $board['uri'] . '.css');
    mod_page(_('Board configuration'), 'mod/settings.html', array('board' => $board, 'css' => prettify_textarea($css), 'token' => make_secure_link_token('settings/' . $board['uri']), 'languages' => $possible_languages, 'allowed_urls' => $config['allowed_offsite_urls']));
}
Exemplo n.º 19
0
function scrub_html($html)
{
    // FIXME
    return purify_html($html);
}
Exemplo n.º 20
0
    /**
     * Test internal function used for clean_text() speedup.
     * @return void
     */
    function test_is_purify_html_necessary() {
        // first our shortcuts
        $text = "";
        $this->assertFalse(is_purify_html_necessary($text));
        $this->assertSame($text, purify_html($text));

        $text = "666";
        $this->assertFalse(is_purify_html_necessary($text));
        $this->assertSame($text, purify_html($text));

        $text = "abc\ndef \" ' ";
        $this->assertFalse(is_purify_html_necessary($text));
        $this->assertSame($text, purify_html($text));

        $text = "abc\n<p>def</p>efg<p>hij</p>";
        $this->assertFalse(is_purify_html_necessary($text));
        $this->assertSame($text, purify_html($text));

        $text = "<br />abc\n<p>def<em>efg</em><strong>hi<br />j</strong></p>";
        $this->assertFalse(is_purify_html_necessary($text));
        $this->assertSame($text, purify_html($text));

        // now failures
        $text = "&nbsp;";
        $this->assertTrue(is_purify_html_necessary($text));

        $text = "Gin & Tonic";
        $this->assertTrue(is_purify_html_necessary($text));

        $text = "Gin > Tonic";
        $this->assertTrue(is_purify_html_necessary($text));

        $text = "Gin < Tonic";
        $this->assertTrue(is_purify_html_necessary($text));

        $text = "<div>abc</div>";
        $this->assertTrue(is_purify_html_necessary($text));

        $text = "<span>abc</span>";
        $this->assertTrue(is_purify_html_necessary($text));

        $text = "<br>abc";
        $this->assertTrue(is_purify_html_necessary($text));

        $text = "<p class='xxx'>abc</p>";
        $this->assertTrue(is_purify_html_necessary($text));

        $text = "<p>abc<em></p></em>";
        $this->assertTrue(is_purify_html_necessary($text));

        $text = "<p>abc";
        $this->assertTrue(is_purify_html_necessary($text));
    }
Exemplo n.º 21
0
 /**
  * Find project objects in commit message, make them links and
  * save the relations to database
  *
  * @param string $commit_message
  * @param string $commit_author
  * @param integer $revision
  * @param Repository $repository
  * @param Project $project
  * @return string
  */
 function analyze_message($commit_message, $commit_author, $revision, $repository, $project)
 {
     if (define('PURIFY_HTML') && PURIFY_HTML) {
         $commit_message = purify_html($commit_message);
         // Clean!
     }
     // if
     $pattern = '/((complete[d]*)[\\s]+)?(ticket|milestone|discussion|task)[s]*[\\s]+[#]*\\d+/i';
     if (preg_match_all($pattern, $commit_message, $matches)) {
         $i = 0;
         $search = array();
         $replace = array();
         $matches_unique = array_unique($matches['0']);
         foreach ($matches_unique as $key => $match) {
             $match_data = preg_split('/[\\s,]+/', $match, null, PREG_SPLIT_NO_EMPTY);
             // check if the object got completed by this commit
             $object_completed = false;
             if (strpos(strtolower($match_data['0']), 'complete') !== false) {
                 $object_completed = true;
                 unset($match_data['0']);
                 $match_data = array_values($match_data);
             }
             // if
             $object_class_name = $match_data['0'];
             $module_name = Inflector::pluralize($object_class_name);
             $object_id = trim($match_data['1'], '#');
             $search[$i] = $match;
             if (class_exists($module_name) && class_exists($object_class_name)) {
                 $object = null;
                 switch (strtolower($module_name)) {
                     case 'tickets':
                         $object = Tickets::findByTicketId($project, $object_id);
                         break;
                     case 'discussions':
                         $object = Discussions::findById($object_id);
                         break;
                     case 'milestones':
                         $object = Milestones::findById($object_id);
                         break;
                     case 'tasks':
                         $object = Tasks::findById($object_id);
                         break;
                 }
                 // switch
                 if (instance_of($object, $object_class_name)) {
                     $link_already_created = CommitProjectObjects::count("object_id = '" . $object->getId() . "' AND revision = '{$revision}'") > 0;
                     if (!$link_already_created) {
                         $comit_project_object = new CommitProjectObject();
                         $comit_project_object->setProjectId($object->getProjectId());
                         $comit_project_object->setObjectId($object->getId());
                         $comit_project_object->setObjectType(ucfirst($object_class_name));
                         $comit_project_object->setRepositoryId($repository->getId());
                         $comit_project_object->setRevision($revision);
                         db_begin_work();
                         $save = $comit_project_object->save();
                         if ($save && !is_error($save)) {
                             db_commit();
                         } else {
                             db_rollback();
                         }
                         // if save
                     }
                     // if
                     $replace[$i] = ($object_completed ? 'Completed ' : '') . '<a href="' . $object->getViewUrl() . '">' . $match_data['0'] . ' ' . $match_data['1'] . '</a>';
                     // set the object as completed
                     if ($object_completed && !instance_of($object, 'Discussion')) {
                         $completed_by = $repository->getMappedUser($commit_author);
                         $object->complete($completed_by);
                     }
                     // if
                 } else {
                     $replace[$i] = ($object_completed ? 'Completed ' : '') . '<a href="#" class="project_object_missing" title="' . lang('Project object does not exist in this project') . '">' . $match_data['0'] . ' ' . $match_data['1'] . '</a>';
                 }
                 // if instance_of
                 $i++;
             }
             // if module loaded
         }
         // foreach
         return str_ireplace($search, $replace, htmlspecialchars($commit_message));
         // linkify
     }
     // if preg_match
     return $commit_message;
 }
Exemplo n.º 22
0
 function workEstimate(ProjectTask $task)
 {
     tpl_assign('task_assigned', $task);
     if (!$task->getAssignedTo() instanceof Contact) {
         return true;
         // not assigned to user
     }
     if (!is_valid_email($task->getAssignedTo()->getEmailAddress())) {
         return true;
     }
     $locale = $task->getAssignedTo()->getLocale();
     Localization::instance()->loadSettings($locale, ROOT . '/language');
     tpl_assign('title', $task->getObjectName());
     tpl_assign('by', $task->getAssignedBy()->getObjectName());
     tpl_assign('asigned', $task->getAssignedTo()->getObjectName());
     $text = "";
     if (config_option("wysiwyg_tasks")) {
         $text = purify_html(nl2br($task->getDescription()));
     } else {
         $text = escape_html_whitespace($task->getDescription());
     }
     tpl_assign('description', $text);
     //descripction
     tpl_assign('description_title', lang("new task work estimate to you desc", $task->getObjectName(), $task->getAssignedBy()->getObjectName()));
     //description_title
     //priority
     if ($task->getPriority()) {
         if ($task->getPriority() >= ProjectTasks::PRIORITY_URGENT) {
             $priorityColor = "#FF0000";
             $priority = lang('urgent priority');
         } else {
             if ($task->getPriority() >= ProjectTasks::PRIORITY_HIGH) {
                 $priorityColor = "#FF9088";
                 $priority = lang('high priority');
             } else {
                 if ($task->getPriority() <= ProjectTasks::PRIORITY_LOW) {
                     $priorityColor = "white";
                     $priority = lang('low priority');
                 } else {
                     $priorityColor = "#DAE3F0";
                     $priority = lang('normal priority');
                 }
             }
         }
         tpl_assign('priority', array($priority, $priorityColor));
     }
     //context
     $contexts = array();
     $members = $task->getMembers();
     if (count($members) > 0) {
         foreach ($members as $member) {
             $dim = $member->getDimension();
             if ($dim->getIsManageable()) {
                 /* @var $member Member */
                 $parent_members = $member->getAllParentMembersInHierarchy();
                 $parents_str = '';
                 foreach ($parent_members as $pm) {
                     /* @var $pm Member */
                     if (!$pm instanceof Member) {
                         continue;
                     }
                     $parents_str .= '<span style="' . get_workspace_css_properties($pm->getMemberColor()) . '">' . $pm->getName() . '</span>';
                 }
                 if ($dim->getCode() == "customer_project" || $dim->getCode() == "customers") {
                     $obj_type = ObjectTypes::findById($member->getObjectTypeId());
                     if ($obj_type instanceof ObjectType) {
                         $contexts[$dim->getCode()][$obj_type->getName()][] = $parents_str . '<span style="' . get_workspace_css_properties($member->getMemberColor()) . '">' . $member->getName() . '</span>';
                     }
                 } else {
                     $contexts[$dim->getCode()][] = $parents_str . '<span style="' . get_workspace_css_properties($member->getMemberColor()) . '">' . $member->getName() . '</span>';
                 }
             }
         }
     }
     tpl_assign('contexts', $contexts);
     //workspaces
     //start date, due date or start
     if ($task->getStartDate() instanceof DateTimeValue) {
         $date = Localization::instance()->formatDescriptiveDate($task->getStartDate(), $task->getAssignedTo()->getTimezone());
         $time = Localization::instance()->formatTime($task->getStartDate(), $task->getAssignedTo()->getTimezone());
         if ($time > 0) {
             $date .= " " . $time;
         }
         tpl_assign('start_date', $date);
         //start_date
     }
     if ($task->getDueDate() instanceof DateTimeValue) {
         $date = Localization::instance()->formatDescriptiveDate($task->getDueDate(), $task->getAssignedTo()->getTimezone());
         $time = Localization::instance()->formatTime($task->getDueDate(), $task->getAssignedTo()->getTimezone());
         if ($time > 0) {
             $date .= " " . $time;
         }
         tpl_assign('due_date', $date);
         //due_date
     }
     $attachments = array();
     try {
         $content = FileRepository::getBackend()->getFileContent(owner_company()->getPictureFile());
         if ($content) {
             $file_path = ROOT . "/tmp/logo_empresa.png";
             $handle = fopen($file_path, 'wb');
             if ($handle) {
                 fwrite($handle, $content);
                 fclose($handle);
                 $attachments['logo'] = array('cid' => gen_id() . substr($task->getAssignedBy()->getEmailAddress(), strpos($task->getAssignedBy()->getEmailAddress(), '@')), 'path' => $file_path, 'type' => 'image/png', 'disposition' => 'inline', 'name' => 'logo_empresa.png');
             }
         }
     } catch (FileNotInRepositoryError $e) {
         unset($attachments['logo']);
     }
     tpl_assign('attachments', $attachments);
     // attachments
     //ALL SUBSCRIBERS
     if ($task->getSubscribers()) {
         $subscribers = $task->getSubscribers();
         $string_subscriber = '';
         $total_s = count($subscribers);
         $c = 0;
         foreach ($subscribers as $subscriber) {
             $c++;
             if ($c == $total_s && $total_s > 1) {
                 $string_subscriber .= lang('and');
             } else {
                 if ($c > 1) {
                     $string_subscriber .= ", ";
                 }
             }
             $string_subscriber .= $subscriber->getFirstName();
             if ($subscriber->getSurname() != "") {
                 $string_subscriber .= " " . $subscriber->getSurname();
             }
         }
         tpl_assign('subscribers', $string_subscriber);
         // subscribers
     }
     if ($task->getAssignedById() == $task->getAssignedToContactId()) {
         if (!$task->getAssignedBy()->getDisabled()) {
             $emails[] = array("to" => array(self::prepareEmailAddress($task->getAssignedBy()->getEmailAddress(), $task->getAssignedBy()->getObjectName())), "from" => self::prepareEmailAddress($task->getUpdatedBy()->getEmailAddress(), $task->getUpdatedByDisplayName()), "subject" => lang('work estimate title'), "body" => tpl_fetch(get_template_path('work_estimate', 'notifier')), "attachments" => $attachments);
         }
     } else {
         if (!$task->getAssignedBy()->getDisabled()) {
             $emails[] = array("to" => array(self::prepareEmailAddress($task->getAssignedBy()->getEmailAddress(), $task->getAssignedBy()->getObjectName())), "from" => self::prepareEmailAddress($task->getUpdatedBy()->getEmailAddress(), $task->getUpdatedByDisplayName()), "subject" => lang('work estimate title'), "body" => tpl_fetch(get_template_path('work_estimate', 'notifier')), "attachments" => $attachments);
         }
         if (!$task->getAssignedTo()->getDisabled()) {
             $emails[] = array("to" => array(self::prepareEmailAddress($task->getAssignedTo()->getEmailAddress(), $task->getAssignedTo()->getObjectName())), "from" => self::prepareEmailAddress($task->getUpdatedBy()->getEmailAddress(), $task->getUpdatedByDisplayName()), "subject" => lang('work estimate title'), "body" => tpl_fetch(get_template_path('work_estimate', 'notifier')), "attachments" => $attachments);
         }
     }
     self::queueEmails($emails);
     $locale = logged_user() instanceof Contact ? logged_user()->getLocale() : DEFAULT_LOCALIZATION;
     Localization::instance()->loadSettings($locale, ROOT . '/language');
 }
Exemplo n.º 23
0
function z_input_filter($channel_id, $s, $type = 'text/bbcode')
{
    if ($type === 'text/bbcode') {
        return escape_tags($s);
    }
    if ($type === 'text/markdown') {
        return escape_tags($s);
    }
    if ($type == 'text/plain') {
        return escape_tags($s);
    }
    if ($type == 'application/x-pdl') {
        return escape_tags($s);
    }
    $a = get_app();
    if ($a->is_sys) {
        return $s;
    }
    $r = q("select account_id, account_roles, channel_pageflags from account left join channel on channel_account_id = account_id where channel_id = %d limit 1", intval($channel_id));
    if ($r) {
        if ($r[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE || $r[0]['channel_pageflags'] & PAGE_ALLOWCODE) {
            if (local_channel() && get_account_id() == $r[0]['account_id']) {
                return $s;
            }
        }
    }
    if ($type === 'text/html') {
        return purify_html($s);
    }
    return escape_tags($s);
}
 function diff($from_lines, $to_lines)
 {
     // remove HTML Tags (nadavkav)
     $removethesetags = array("<br />", "<hr />", "<p>", "</p>", "<div>", "</div>", "<font>", "</font>", "<strong>", "</strong>", "<h2>", "</h2>", "<h1>", "</h1>", "<span>", "</span>", "<h3>", "</h3>", "<a>", "</a>", "<em>", "</em>");
     foreach ($from_lines as $fromline) {
         $from_lines_clean[] = str_replace($removethesetags, "", purify_html($fromline));
     }
     foreach ($to_lines as $toline) {
         $to_lines_clean[] = str_replace($removethesetags, "", purify_html($toline));
     }
     unset($from_lines);
     $from_lines = $from_lines_clean;
     unset($to_lines);
     $to_lines = $to_lines_clean;
     $n_from = sizeof($from_lines);
     $n_to = sizeof($to_lines);
     $this->xchanged = $this->ychanged = array();
     $this->xv = $this->yv = array();
     $this->xind = $this->yind = array();
     unset($this->seq);
     unset($this->in_seq);
     unset($this->lcs);
     // Skip leading common lines.
     for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) {
         if ($from_lines[$skip] != $to_lines[$skip]) {
             break;
         }
         $this->xchanged[$skip] = $this->ychanged[$skip] = false;
     }
     // Skip trailing common lines.
     $xi = $n_from;
     $yi = $n_to;
     for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) {
         if ($from_lines[$xi] != $to_lines[$yi]) {
             break;
         }
         $this->xchanged[$xi] = $this->ychanged[$yi] = false;
     }
     // Ignore lines which do not exist in both files.
     for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
         $xhash[$from_lines[$xi]] = 1;
     }
     for ($yi = $skip; $yi < $n_to - $endskip; $yi++) {
         $line = $to_lines[$yi];
         if ($this->ychanged[$yi] = empty($xhash[$line])) {
             continue;
         }
         $yhash[$line] = 1;
         $this->yv[] = $line;
         $this->yind[] = $yi;
     }
     for ($xi = $skip; $xi < $n_from - $endskip; $xi++) {
         $line = $from_lines[$xi];
         if ($this->xchanged[$xi] = empty($yhash[$line])) {
             continue;
         }
         $this->xv[] = $line;
         $this->xind[] = $xi;
     }
     // Find the LCS.
     $this->_compareseq(0, sizeof($this->xv), 0, sizeof($this->yv));
     // Merge edits when possible
     $this->_shift_boundaries($from_lines, $this->xchanged, $this->ychanged);
     $this->_shift_boundaries($to_lines, $this->ychanged, $this->xchanged);
     // Compute the edit operations.
     $edits = array();
     $xi = $yi = 0;
     while ($xi < $n_from || $yi < $n_to) {
         USE_ASSERTS_IN_WIKI && assert($yi < $n_to || $this->xchanged[$xi]);
         USE_ASSERTS_IN_WIKI && assert($xi < $n_from || $this->ychanged[$yi]);
         // Skip matching "snake".
         $copy = array();
         while ($xi < $n_from && $yi < $n_to && !$this->xchanged[$xi] && !$this->ychanged[$yi]) {
             $copy[] = $from_lines[$xi++];
             ++$yi;
         }
         if ($copy) {
             $edits[] = new _WikiDiffOp_Copy($copy);
         }
         // Find deletes & adds.
         $delete = array();
         while ($xi < $n_from && $this->xchanged[$xi]) {
             $delete[] = $from_lines[$xi++];
         }
         $add = array();
         while ($yi < $n_to && $this->ychanged[$yi]) {
             $add[] = $to_lines[$yi++];
         }
         if ($delete && $add) {
             $edits[] = new _WikiDiffOp_Change($delete, $add);
         } elseif ($delete) {
             $edits[] = new _WikiDiffOp_Delete($delete);
         } elseif ($add) {
             $edits[] = new _WikiDiffOp_Add($add);
         }
     }
     return $edits;
 }
Exemplo n.º 25
0
/**
 * Cleans raw text removing nasties.
 *
 * Given raw text (eg typed in by a user) this function cleans it up and removes any nasty tags that could mess up
 * Moodle pages through XSS attacks.
 *
 * The result must be used as a HTML text fragment, this function can not cleanup random
 * parts of html tags such as url or src attributes.
 *
 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
 *
 * @param string $text The text to be cleaned
 * @param int|string $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
 *   does not remove id attributes when cleaning)
 * @return string The cleaned up text
 */
function clean_text($text, $format = FORMAT_HTML, $options = array())
{
    $text = (string) $text;
    if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
        // TODO: we need to standardise cleanup of text when loading it into editor first.
        // debugging('clean_text() is designed to work only with html');.
    }
    if ($format == FORMAT_PLAIN) {
        return $text;
    }
    if (is_purify_html_necessary($text)) {
        $text = purify_html($text, $options);
    }
    // Originally we tried to neutralise some script events here, it was a wrong approach because
    // it was trivial to work around that (for example using style based XSS exploits).
    // We must not give false sense of security here - all developers MUST understand how to use
    // rawurlencode(), htmlentities(), htmlspecialchars(), p(), s(), moodle_url, html_writer and friends!!!
    return $text;
}
Exemplo n.º 26
0
<p><b><?php echo lang('assigned to') ?>:</b>&nbsp;<?php echo clean($task->getAssignedToName()) ?></p>
<?php } // if ?>


<?php if ($task->getMilestone() instanceof ProjectMilestone) { ?>
<p><b><?php echo lang('milestone') ?>:</b>&nbsp;<?php echo clean($task->getMilestone()->getObjectName()) ?></p>
<?php } // if ?>

<?php if ($task->getText() != '') { ?>
<p><b><?php echo lang('description') ?>:</b></p>
<div style="margin-left:14px;padding:6px;border:1px solid #AAA">
<?php 
    if($task->getTypeContent() == "text"){
        echo escape_html_whitespace(convert_to_links(clean($task->getText())));
    }else{
        echo purify_html(nl2br($task->getText()));
    }
?>
</div>
<?php } // if ?>

<?php 
	$hasIncompleteSubtasks = is_array($task->getOpenSubTasks()) && count($task->getOpenSubTasks()) > 0;
	$hasCompletedSubtasks = is_array($task->getCompletedSubTasks()) && count($task->getCompletedSubTasks()) > 0;
if ($hasIncompleteSubtasks || $hasCompletedSubtasks) { ?>
<div style="margin-bottom:0px;margin-top:20px"><img src="public/assets/themes/default/images/16x16/tasks.png"/>&nbsp;&nbsp;<b><?php echo lang('subtasks') ?>:</b></div>
<ul style="margin-top:2px">
<?php
	if ($hasIncompleteSubtasks) {
		$otArray = $task->getOpenSubTasks();
		foreach ($otArray as $ot){
Exemplo n.º 27
0
		}
  
		if($email->getBodyHtml() != ''){
			if (defined('SANDBOX_URL')) {
				$html_content = $email->getBodyHtml();
				// prevent some outlook malformed tags
				if(substr_count($html_content, "<style") != substr_count($html_content, "</style>") && substr_count($html_content, "/* Font Definitions */") >= 1) {
					$p1 = strpos($html_content, "/* Font Definitions */", 0);
					$html_content1 = substr($html_content, 0, $p1);
					$p0 = strrpos($html_content1, "</style>");
					$html_content = ($p0 >= 0 ? substr($html_content1, 0, $p0) : $html_content1) . substr($html_content, $p1);
					
					$html_content = str_replace_first("/* Font Definitions */","<style>",$html_content);
				}
			} else {
				$html_content = purify_html($email->getBodyHtml());
			}
			if (strpos($html_content, "<html") === false) {
				if (strpos($html_content, "<body") === false) {
					$html_content = "<body>" . $html_content . "</body>";
				}
				if (strpos($html_content, "<head") === false) {
					$html_content = "<head></head>" . $html_content;
				}
				$html_content = "<html>" . $html_content . "</html>";
			}
			//$html_content = convert_to_links($html_content); // commented because it can break HTML (e.g. if an URL or email is found on the title of an element)
			// links must open in a new tab or window
			$html_content = preg_replace('/<a\s/', '<a target="_blank" ', $html_content);
			
			//remove attributes from body
 public function sanitize($data, $type, $base = '')
 {
     $data = trim($data);
     if ($data === '') {
         return '';
     }
     if ($type & SIMPLEPIE_CONSTRUCT_BASE64) {
         $data = base64_decode($data);
     }
     if ($type & SIMPLEPIE_CONSTRUCT_MAYBE_HTML) {
         if (preg_match('/(&(#(x[0-9a-fA-F]+|[0-9]+)|[a-zA-Z0-9]+)|<\\/[A-Za-z][^\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\x2F\\x3E]*' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>)/', $data)) {
             $type |= SIMPLEPIE_CONSTRUCT_HTML;
         } else {
             $type |= SIMPLEPIE_CONSTRUCT_TEXT;
         }
     }
     if ($type & SIMPLEPIE_CONSTRUCT_IRI) {
         $absolute = $this->registry->call('Misc', 'absolutize_url', array($data, $base));
         if ($absolute !== false) {
             $data = $absolute;
         }
         $data = clean_param($data, PARAM_URL);
     }
     if ($type & (SIMPLEPIE_CONSTRUCT_TEXT | SIMPLEPIE_CONSTRUCT_IRI)) {
         $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
     }
     $data = purify_html($data);
     if ($this->remove_div) {
         $data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '', $data);
         $data = preg_replace('/<\\/div>$/', '', $data);
     } else {
         $data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '<div>', $data);
     }
     if ($this->output_encoding !== 'UTF-8') {
         textlib::convert($data, 'UTF-8', $this->output_encoding);
     }
     return $data;
 }
Exemplo n.º 29
0
/**
 * Given raw text (eg typed in by a user), this function cleans it up
 * and removes any nasty tags that could mess up Moodle pages.
 *
 * NOTE: the format parameter was deprecated because we can safely clean only HTML.
 *
 * @param string $text The text to be cleaned
 * @param int $format deprecated parameter, should always contain FORMAT_HTML or FORMAT_MOODLE
 * @param array $options Array of options; currently only option supported is 'allowid' (if true,
 *   does not remove id attributes when cleaning)
 * @return string The cleaned up text
 */
function clean_text($text, $format = FORMAT_HTML, $options = array())
{
    global $ALLOWED_TAGS, $CFG;
    if (empty($text) or is_numeric($text)) {
        return (string) $text;
    }
    if ($format != FORMAT_HTML and $format != FORMAT_HTML) {
        // TODO: we need to standardise cleanup of text when loading it into editor first
        //debugging('clean_text() is designed to work only with html');
    }
    if ($format == FORMAT_PLAIN) {
        return $text;
    }
    if (!empty($CFG->enablehtmlpurifier)) {
        $text = purify_html($text, $options);
    } else {
        /// Fix non standard entity notations
        $text = fix_non_standard_entities($text);
        /// Remove tags that are not allowed
        $text = strip_tags($text, $ALLOWED_TAGS);
        /// Clean up embedded scripts and , using kses
        $text = cleanAttributes($text);
        /// Again remove tags that are not allowed
        $text = strip_tags($text, $ALLOWED_TAGS);
    }
    // Remove potential script events - some extra protection for undiscovered bugs in our code
    $text = preg_replace("~([^a-z])language([[:space:]]*)=~i", "\$1Xlanguage=", $text);
    $text = preg_replace("~([^a-z])on([a-z]+)([[:space:]]*)=~i", "\$1Xon\$2=", $text);
    return $text;
}
Exemplo n.º 30
0
function wiki_save_page($arr)
{
    $pageUrlName = array_key_exists('pageUrlName', $arr) ? $arr['pageUrlName'] : '';
    $content = array_key_exists('content', $arr) ? purify_html($arr['content']) : '';
    $resource_id = array_key_exists('resource_id', $arr) ? $arr['resource_id'] : '';
    $w = wiki_get_wiki($resource_id);
    if (!$w['path']) {
        return array('message' => 'Error reading wiki', 'success' => false);
    }
    $page_path = $w['path'] . '/' . $pageUrlName . '.md';
    if (is_writable($page_path) === true) {
        if (!file_put_contents($page_path, $content)) {
            return array('message' => 'Error writing to page file', 'success' => false);
        }
        return array('message' => '', 'success' => true);
    } else {
        return array('message' => 'Page file not writable', 'success' => false);
    }
}