public function selectByName($name, $siteId, $useMemcache = true) { if ($name !== "_default") { $name = WDStringUtils::toUnixName($name); } if ($useMemcache) { $memcache = Ozone::$memcache; $key = 'category..' . $siteId . '..' . $name; $cat = $memcache->get($key); if ($cat) { return $cat; } else { $c = new Criteria(); $c->add("name", $name); $c->add("site_id", $siteId); $cat = $this->selectOne($c); $memcache->set($key, $cat, 0, 864000); // 10 days ;-) return $cat; } } else { $c = new Criteria(); $c->add("name", $name); $c->add("site_id", $siteId); $cat = $this->selectOne($c); return $cat; } }
public function selectByName($siteId, $name) { $c = new Criteria(); $c->add("site_id", $siteId); $c->add("unix_name", WDStringUtils::toUnixName($name)); return $this->selectOne($c); }
public function process($data) { $search = $_GET['q']; $siteId = $_GET['s']; if (isset($_GET['parent'])) { $parent = WDStringUtils::toUnixName($_GET['parent']); } else { $parent = null; } $title = isset($_GET['title']) && $_GET['title'] == 'yes'; if (!is_numeric($siteId) || $search == null || strlen($search) == 0) { return; } $search = pg_escape_string(preg_quote(str_replace(' ', '-', $search))); $siteId = pg_escape_string($siteId); $orTitle = $title ? "OR title ~* '^{$search}'" : ""; $query = "SELECT unix_name, COALESCE(title,unix_name) AS title FROM page "; $query .= "WHERE site_id ='{$siteId}' AND (unix_name ~* '^{$search}' {$orTitle})"; if ($parent) { $parent = pg_escape_string($parent); $query .= " AND parent_page_id IN (SELECT page_id FROM page WHERE unix_name = '{$parent}') "; } $query .= "ORDER BY unix_name"; Database::init(); return array('pages' => Database::connection()->query($query)->fetchAll()); }
public function cloneSiteEvent($runData) { $pl = $runData->getParameterList(); $site = $runData->getTemp("site"); $siteId = $site->getSiteId(); WDPermissionManager::instance()->canBecomeAdmin($runData->getUser()); $name = trim($pl->getParameterValue("name")); $unixName = trim($pl->getParameterValue("unixname")); $tagline = trim($pl->getParameterValue("tagline")); $description = trim($pl->getParameterValue("description")); $private = (bool) $pl->getParameterValue("private"); // validate form data: $errors = array(); if (strlen($name) < 1) { $errors['name'] = _("Site name must be present."); } elseif (strlen8($name) > 30) { $errors['name'] = _("Site name should not be longer than 30 characters."); } // site unix name ************* if ($unixName === null || strlen($unixName) < 3) { $errors['unixname'] = _("Web address must be present and should be at least 3 characters long."); } elseif (strlen($unixName) > 30) { $errors['unixname'] = _("Web address name should not be longer than 30 characters."); } elseif (preg_match("/^[a-z0-9\\-]+\$/", $unixName) == 0) { $errors['unixname'] = _('Only lowercase alphanumeric and "-" (dash) characters allowed in the web address.'); } elseif (preg_match("/\\-\\-/", $unixName) !== 0) { $errors['unixname'] = _('Only lowercase alphanumeric and "-" (dash) characters allowed in the web address. Double-dash (--) is not allowed.'); } else { $unixName = WDStringUtils::toUnixName($unixName); if (!$runData->getUser()->getSuperAdmin()) { // handle forbidden names $forbiddenUnixNames = explode("\n", file_get_contents(WIKIDOT_ROOT . '/conf/forbidden_site_names.conf')); foreach ($forbiddenUnixNames as $f) { if (preg_match($f, $unixName) > 0) { $errors['unixname'] = _('For some reason this web address is not allowed or is reserved for future use.'); } } } // check if the domain is not taken. $c = new Criteria(); $c->add("unix_name", $unixName); $ss = DB_SitePeer::instance()->selectOne($c); if ($ss) { $errors['unixname'] = _('Sorry, this web address is already used by another site.'); } } if (strlen8($tagline) > 50) { $errors['tagline'] = _("Tagline should not be longer than 50 characters"); } if (count($errors) > 0) { $runData->ajaxResponseAdd("formErrors", $errors); throw new ProcessException("Form errors", "form_errors"); } // and now... CREATE THE SITE!!!!!!!!!!!!!!!! $siteProps = array('name' => $name, 'subtitle' => $tagline, 'unixname' => $unixName, 'description' => $description, 'private' => $private); $dup = new Duplicator(); $dup->cloneSite($site, $siteProps); }
public function build($runData) { $site = $runData->getTemp("site"); $pl = $runData->getParameterList(); $categoryName = trim($pl->getParameterValue("category", "MODULE")); $template = trim($pl->getParameterValue("template", "MODULE")); $format = trim($pl->getParameterValue("format", "MODULE")); $runData->contextAdd("categoryName", WDStringUtils::toUnixName($categoryName)); if ($template) { $ta = explode(',', $template); $tp = array(); foreach ($ta as $t) { // for each of the suggested arrays $t = trim($t); if (!preg_match("/^template:/", $t)) { throw new ProcessException(sprintf(_('"%s" is not in the "template:" category.'), $t), "not_template"); } $page = DB_PagePeer::instance()->selectByName($site->getSiteId(), $t); if ($page == null) { throw new ProcessException(sprintf(_('Template "%s" can not be found.'), $t), "no_template"); } $tp[] = $page; } if (count($tp) > 1) { $runData->contextAdd("templates", $tp); } if (count($tp) == 1) { $runData->contextAdd("template", $tp[0]); } } // size of the field $fieldSize = $pl->getParameterValue("size", "MODULE"); $style = $pl->getParameterValue("style", "MODULE"); $buttonText = $pl->getParameterValue("button", "MODULE"); if (!$fieldSize) { $fieldSize = 30; } $runData->contextAdd('size', $fieldSize); $runData->contextAdd('style', $style); $runData->contextAdd('button', $buttonText); // check if format is valid (vali regexp) $m = false; if ($format) { $m = @preg_match($format, 'abc'); if ($m !== false) { $runData->contextAdd('format', $format); } else { $runData->contextAdd("formatError", $format); } } }
public function createNewPageEvent($runData) { // this just checks if page exists and if the user has permissions to create. // returns cleaned name. $pl = $runData->getParameterList(); $pageName = trim($pl->getParameterValue("pageName")); $categoryName = trim($pl->getParameterValue("categoryName")); $format = trim($pl->getParameterValue("format")); $autoincrement = $pl->getParameterValue('autoincrement'); $templateId = $pl->getParameterValue("template"); $site = $runData->getTemp("site"); if (strlen($pageName) === 0) { $runData->ajaxResponseAdd("status", "no_name"); $runData->ajaxResponseAdd("message", "You should provide a page name."); return; } // check if use a title too //if(WDStringUtils::toUnixName($pageName) != $pageName){ $pageTitle = $pageName; //} if ($format) { $m = false; $m = @preg_match($format, $pageName); if ($m !== false && $m === 0) { throw new ProcessException(_("The page name is not in the required format.")); } } if ($autoincrement) { $unixName = $categoryName . ':autoincrementpage'; } else { $unixName = WDStringUtils::toUnixName($categoryName . ':' . $pageName); } $page = DB_PagePeer::instance()->selectByName($site->getSiteId(), $unixName); if ($page != null) { $runData->ajaxResponseAdd("status", "page_exists"); $runData->ajaxResponseAdd("message", "The page <em>" . $unixName . "</em> already exists." . ' <a href="/' . $unixName . '">Jump to it</a> if you wish.'); return; } if ($templateId) { $templatePage = DB_PagePeer::instance()->selectByPrimaryKey($templateId); if (!$templatePage || !preg_match("/^template:/", $templatePage->getUnixName())) { throw new ProcessException("Error selecting the template"); } $runData->ajaxResponseAdd("templateId", $templateId); } $runData->ajaxResponseAdd("unixName", $unixName); if ($pageTitle) { $runData->ajaxResponseAdd("pageTitle", $pageTitle); } }
public function saveEvent($runData) { $pl = $runData->getParameterList(); $nick_name = $pl->getParameterValue("nick_name"); $password = $pl->getParameterValue("password1"); $u = DB_OzoneUserPeer::instance()->selectByPrimaryKey(1); $u->setName($nick_name); $u->setEmail($nick_name); $u->setNickName($nick_name); $u->setUnixName(WDStringUtils::toUnixName($nick_name)); $u->setPassword(md5($password)); $u->setSuperAdmin(true); $u->save(); }
function process(&$matches) { $pageName = WDStringUtils::toUnixName(trim($matches[1])); // get page source (if exists) $runData = Ozone::getRunData(); $site = $runData->getTemp("site"); $page = DB_PagePeer::instance()->selectByName($site->getSiteId(), $pageName); if ($page == null) { //$output = $this->wiki->addToken( // $this->rule, array('fromIncludeRule' => true, 'type' => 'error', 'pageName' => $pageName) $output = "\n\n" . '[[div class="error-block"]]' . "\n" . sprintf(_('Page to be included %s can not be found!'), htmlspecialchars($pageName)) . "\n" . '[[/div]]' . "\n\n"; $wiki = $this->wiki; if ($wiki->vars['inclusionsNotExist'] == null) { $wiki->vars['inclusionsNotExist'] = array(); } $wiki->vars['inclusionsNotExist'][$pageName] = $pageName; } else { $output = $page->getSource(); // prepare entry... $wiki = $this->wiki; if ($wiki->vars['inclusions'] == null) { $wiki->vars['inclusions'] = array(); } $wiki->vars['inclusions'][$page->getPageId()] = $page->getPageId(); // preprocess the output too!!! // missed a few rules so far... TODO!!! //process the output - make substitutions. $subs = $matches[2]; if ($subs) { $subsArray = explode('|', $subs); foreach ($subsArray as $sub) { if (strpos($sub, '=') !== false) { $pos = strpos($sub, '='); $var = trim(substr($sub, 0, $pos)); $value = trim(substr($sub, $pos + 1)); if ($value != '' && $var != '' && preg_match('/^[a-z0-9\\-\\_]+$/i', $var)) { // substitute!!! $output = str_replace('{$' . $var . '}', $value, $output); } } } } } // done, place the script output directly in the source return "\n\n" . $output . "\n\n"; }
/** * * Renders a token into text matching the requested format. * * @access public * * @param array $options The "options" portion of the token (second * element). * * @return string The text rendered from the token options. * */ function token($options) { $userName = $options['userName']; $unixName = WDStringUtils::toUnixName($userName); $c = new Criteria(); $c->add("unix_name", $unixName); $user = DB_OzoneUserPeer::instance()->selectOne($c); if ($user == null) { return '<span class="error-inline">' . sprintf(_('User <em>%s</em> can not be found.'), $userName) . '</span>'; } else { $o = array(); if ($options['image']) { $o['image'] = true; } return WDRenderUtils::renderUser($user, $o); } }
public function build($runData) { $pl = $runData->getParameterList(); $noRedirect = (bool) $pl->getParameterValue("noredirect"); if ($runData->isAjaxMode()) { $noRedirect = true; } $target = trim($pl->getParameterValue("destination")); if ($target == "") { throw new ProcessException(_('No redirection destination specified. Please use the destination="page-name" or destination="url" attribute.')); } $currentUri = $_SERVER['REQUEST_URI']; if (!$noRedirect) { // ok, redirect!!! // check if mapping should be done. if ($target[strlen($target) - 1] === '/' && strpos($currentUri, '/', 1)) { $map = true; } else { $map = false; } // check if $target is an URI or just a page name if (!strpos($target, '://')) { $target = WDStringUtils::toUnixName($target); $target = '/' . $target; if ($map) { $target .= '/'; } } if ($map) { // use more advanced mapping //strip page name and take the remaining part $mappedUri = substr($currentUri, strpos($currentUri, '/', 1) + 1); $target .= $mappedUri; } header('HTTP/1.1 301 Moved Permanently'); header('Location: ' . $target); exit; } else { $runData->contextAdd("target", $target); } }
public function build($runData) { if ($runData->getUser() == null) { $runData->contextAdd("notLogged", true); } else { // // } $pl = $runData->getParameterList(); $siteUnixName = WDStringUtils::toUnixName($pl->getParameterValue('address')); $runData->contextAdd('unixName', $siteUnixName); $siteName = str_replace('-', ' ', $siteUnixName); $siteName = ucwords($siteName); $runData->contextAdd('siteName', $siteName); // get template sites $c = new Criteria(); $c->add('unix_name', '^template-', '~'); $c->addOrderAscending('site_id'); $templates = DB_SitePeer::instance()->select($c); $runData->contextAdd('templates', $templates); }
public function newWikiEvent($runData) { $pl = $runData->getParameterList(); $siteName = $pl->getParameterValue('siteName'); // validate even more $unixName = WDStringUtils::toUnixName($siteName); if ($unixName === null || strlen($unixName) < 3) { throw new ProcessException(_("Web address must be at least 3 characters long.")); } if (strlen($unixName) > 30) { throw new ProcessException(_("Web address name should not be longer than 30 characters.")); } if (preg_match("/^[a-z0-9\\-]+\$/", $unixName) == 0) { throw new ProcessException(_('Only lowercase alphanumeric and "-" (dash) characters allowed in the web address.')); } if (preg_match("/\\-\\-/", $unixName) !== 0) { throw new ProcessException(_('Only lowercase alphanumeric and "-" (dash) characters allowed in the web address. Double-dash (--) is not allowed.')); } $unixName = WDStringUtils::toUnixName($unixName); if (!$runData->getUser() || !$runData->getUser()->getSuperAdmin()) { // handle forbidden names $forbiddenUnixNames = explode("\n", file_get_contents(WIKIDOT_ROOT . '/conf/forbidden_site_names.conf')); foreach ($forbiddenUnixNames as $f) { if (preg_match($f, $unixName) > 0) { throw new ProcessException(_('For some reason this web address is not allowed or is reserved for future use.')); } } } // check if the domain is not taken. $c = new Criteria(); $c->add("unix_name", $unixName); $ss = DB_SitePeer::instance()->selectOne($c); if ($ss) { throw new ProcessException(_('Sorry, this web address is already used by another wiki.')); } $runData->ajaxResponseAdd('unixName', $unixName); }
/** * * Generates a replacement for the matched text. Token options are: * * 'page' => the wiki page name (e.g., HomePage). * * 'text' => alternative text to be displayed in place of the wiki * page name. * * 'anchor' => a named anchor on the target wiki page * * @access public * * @param array &$matches The array of matches from parse(). * * @return A delimited token to be used as a placeholder in * the source text, plus any text priot to the match. * */ function process(&$matches) { // use nice variable names $page = $matches[1]; $text = $matches[3]; $anchor = $matches[2]; if ($page[0] == '_') { $page = substr($page, 1); $nonbr = true; } // check if references to another site too. $site = null; if (strpos($page, '::')) { $site = substr($page, 0, strpos($page, '::')); $site = WDStringUtils::toUnixName($site); $page = substr($page, strpos($page, '::') + 2); if (!$page) { $page = $site; } } // is the page given a new text appearance? if (trim($text) == '') { // no $text = $page; if (strpos($text, ':') != false) { $text = substr($text, strpos($text, ':') + 1); } } elseif (trim($text) == '|') { // get $text from the page title (if exists) $textFromTitle = true; } else { // yes, strip the leading | character $text = substr($text, 1); } // MF: 'purify' the page name $page = WDStringUtils::toUnixName($page); // set the options $options = array('site' => $site, 'page' => $page, 'text' => $text, 'anchor' => $anchor, 'textFromTitle' => $textFromTitle); if ($nonbr) { $options['nonbr'] = true; } // return a token placeholder return $this->wiki->addToken($this->rule, $options); }
public function createSiteEvent($runData) { WDPermissionManager::instance()->canBecomeAdmin($runData->getUser()); $pl = $runData->getParameterList(); $name = trim($pl->getParameterValue("name")); $unixName = trim($pl->getParameterValue("unixname")); $tagline = trim($pl->getParameterValue("tagline")); $templateId = $pl->getParameterValue("template"); $private = (bool) $pl->getParameterValue("private"); // validate form data: $errors = array(); if (strlen($name) < 1) { $errors['name'] = _("Site name must be present."); } elseif (strlen8($name) > 30) { $errors['name'] = _("Site name should not be longer than 30 characters."); } // site unix name ************* if ($unixName === null || strlen($unixName) < 3) { $errors['unixname'] = _("Web address must be present and should be at least 3 characters long."); } elseif (strlen($unixName) > 30) { $errors['unixname'] = _("Web address name should not be longer than 30 characters."); } elseif (preg_match("/^[a-z0-9\\-]+\$/", $unixName) == 0) { $errors['unixname'] = _('Only lowercase alphanumeric and "-" (dash) characters allowed in the web address.'); } elseif (preg_match("/\\-\\-/", $unixName) !== 0) { $errors['unixname'] = _('Only lowercase alphanumeric and "-" (dash) characters allowed in the web address. Double-dash (--) is not allowed.'); } else { $unixName = WDStringUtils::toUnixName($unixName); if (!$runData->getUser()->getSuperAdmin()) { // handle forbidden names $forbiddenUnixNames = explode("\n", file_get_contents(WIKIDOT_ROOT . '/conf/forbidden_site_names.conf')); foreach ($forbiddenUnixNames as $f) { if (preg_match($f, $unixName) > 0) { $errors['unixname'] = _('For some reason this web address is not allowed or is reserved for future use.'); } } } // check if the domain is not taken. $c = new Criteria(); $c->add("unix_name", $unixName); $ss = DB_SitePeer::instance()->selectOne($c); if ($ss) { $errors['unixname'] = _('Sorry, this web address is already used by another site.'); } } // template if (!$templateId) { $errors['template'] = _('Please choose a template for your site'); } if (strlen8($tagline) > 50) { $errors['tagline'] = _("Tagline should not be longer than 50 characters"); } // TOS if (!$pl->getParameterValue("tos")) { $errors['tos'] = _("Please read and agree to the Terms of Service."); } if (count($errors) > 0) { $runData->ajaxResponseAdd("formErrors", $errors); throw new ProcessException("Form errors", "form_errors"); } // and now... CREATE THE SITE!!!!!!!!!!!!!!!! $dup = new Duplicator(); $dup->setOwner($runData->getUser()); $db = Database::connection(); $db->begin(); $templateSite = DB_SitePeer::instance()->selectByPrimaryKey($templateId); if (!preg_match(';^template\\-;', $templateSite->getUnixName())) { throw new ProcessException('Error'); } $site = new DB_Site(); $site->setName($name); $site->setSubtitle($tagline); $site->setUnixName($unixName); $site->setLanguage($templateSite->getLanguage()); $site->setDateCreated(new ODate()); $site->setPrivate($private); if ($private) { // change file flag too $flagDir = WIKIDOT_ROOT . '/web/files--sites/' . $site->getUnixName() . '/flags'; $flagFile = $flagDir . '/private'; mkdirfull($flagDir); //just to make sure if (!file_exists($flagFile)) { file_put_contents($flagFile, "private"); } } $site->save(); $dup->addExcludedCategory("forum"); // should be initialized independently $dup->addExcludedCategory("profile"); $dup->duplicateSite($templateSite, $site); // index the site too $ind = Indexer::instance(); $c = new Criteria(); $c->add("site_id", $site->getSiteId()); $pages = DB_PagePeer::instance()->select($c); foreach ($pages as $p) { $ind->indexPage($p); } $db->commit(); // clear captcha code $runData->sessionDel("captchaCode"); $runData->ajaxResponseAdd("siteUnixName", $unixName); }
public function signEvent($runData) { require WIKIDOT_ROOT . '/php/unclassified/country_codes.php'; $site = $runData->getTemp("site"); $pl = $runData->getParameterList(); $campaignId = $pl->getParameterValue("campaignId"); $db = Database::connection(); $db->begin(); $c = new Criteria(); $c->add("site_id", $site->getSiteId()); $c->add("deleted", false); $c->add("campaign_id", $campaignId); $camp = DB_PetitionCampaignPeer::instance()->selectOne($c); if (!$camp) { throw new ProcessException(_("The campaign can not be found.")); } if (!$camp->getActive()) { throw new ProcessException(_("This petition campaign is paused.")); } $errors = array(); // prepare the new signature at the same time $pet = new DB_PetitionSignature(); // first and last name $firstName = trim($pl->getParameterValue("firstName")); if (strlen($firstName) == 0) { $errors['firstName'] = _("Please enter your first name."); } elseif (strlen8($firstName) > 64) { $errors['firstName'] = _("First name seems to be too long."); } $lastName = trim($pl->getParameterValue("lastName")); if (strlen($lastName) == 0) { $errors['lastName'] = _("Please enter your last name."); } elseif (strlen8($lastName) > 64) { $errors['lastName'] = _("Last name seems to be too long."); } $pet->setFirstName($firstName); $pet->setLastName($lastName); // address if ($camp->getCollectAddress()) { $address1 = trim($pl->getParameterValue("address1")); $address2 = trim($pl->getParameterValue("address2")); if (strlen($address1) == 0) { $errors['address'] = _("Please enter your address."); } elseif (strlen8($address1) > 100) { $errors['address'] = _("The address seems to be too long."); } if (strlen8($address2) > 100) { $errors['address'] = _("The address seems to be too long."); } $pet->setAddress1($address1); $pet->setAddress2($address2); } //city if ($camp->getCollectCity()) { $city = trim($pl->getParameterValue("city")); if (strlen($city) == 0) { $errors['city'] = _("Please enter the city of residence."); } elseif (strlen8($city) > 64) { $errors['city'] = _("The city name seems to be too long."); } $pet->setCity($city); } //state if ($camp->getCollectState()) { $state = trim($pl->getParameterValue("state")); //}else if (strlen8($state) > 64) { $errors['state'] = _("The name of the state seems to be too long."); } $pet->setState($state); } //zip if ($camp->getCollectZip()) { $zip = trim($pl->getParameterValue("zip")); if (strlen($zip) == 0) { $errors['zip'] = _("Please enter your zip/postal code."); } elseif (strlen8($zip) > 20) { $errors['zip'] = _("The zip/postal code seems to be too long."); } $pet->setZip($zip); } //country if ($camp->getCollectCountry()) { $country = trim($pl->getParameterValue("country")); if (strlen($country) == 0 || !isset($iso3166_country_codes[$country])) { $errors['country'] = _("Please choose your country."); } $pet->setCountryCode($country); $pet->setCountry($iso3166_country_codes[$country]); /* if(strlen($country) == 0){ $errors['country'] = _("Please enter your country."); }elseif(strlen8($country) > 60){ $errors['country'] = _("The name of the country is too long."); } $pet->setCountry($country); */ } //comments if ($camp->getCollectComments()) { $comments = trim($pl->getParameterValue("comments")); if (strlen8($comments) > 300) { $errors['comments'] = _("The comments should not be longer than 300 characters."); } $pet->setComments($comments); } //verify email $email = trim($pl->getParameterValue("email")); if (!preg_match('/^[_a-zA-Z0-9\\-\\+]+(\\.[_a-zA-Z0-9\\-\\+]+)*@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)+$/', $email)) { $errors['email'] = _("Please provide a valid email address."); } // check if email is unique for this campaign! if (!$errors['email']) { $c = new Criteria(); $c->add("campaign_id", $camp->getCampaignId()); $c->add("email", $email); $pet0 = DB_PetitionSignaturePeer::instance()->selectOne($c); if ($pet0) { if ($pet0->getConfirmed()) { $errors['email'] = _("This email has been already used for signing the petition."); } else { DB_PetitionSignaturePeer::instance()->deleteByPrimaryKey($pet0->getSignatureId()); } } } $pet->setEmail($email); if (count($errors) > 0) { // there are some errors!!! $runData->ajaxResponseAdd("errors", $errors); throw new ProcessException(_("The form contains some errors."), "form_errors"); } // everything should be ok at this point - finish creating the signature, // save the signature and send a verification email. $pet->setCampaignId($camp->getCampaignId()); $pet->setDate(new ODate()); // generate hash. $hash = substr(md5($email . time()), 0, 20); $pageUnixName = $pl->getParameterValue("petitionUrl"); $pageUnixName = WDStringUtils::toUnixName($pageUnixName); $url = $site->getDomain() . '/' . $pageUnixName; $pet->setConfirmationUrl($url); $oe = new OzoneEmail(); $oe->addAddress($email); $oe->setSubject(_("Petition confirmation")); $oe->contextAdd('firstName', $firstName); $oe->contextAdd('lastName', $lastName); $oe->contextAdd('hash', $hash); $oe->contextAdd("site", $site); $oe->contextAdd("siteName", $site->getName()); $oe->contextAdd("url", $url); $oe->contextAdd("campaign", $camp); $oe->contextAdd("campaignName", $camp->getName()); $oe->contextAdd("sig", $pet); $oe->setBodyTemplate('wiki/petition/PetitionConfirmation'); if (!$oe->Send()) { throw new ProcessException(_("Confirmation email can not be delivered to the specified address.")); } $pet->setConfirmationHash($hash); $pet->setConfirmationUrl('/' . $pageUnixName); $pet->save(); $db->commit(); $runData->setModuleTemplate("extra/petition/ConfirmationSentModule"); $runData->sessionAdd("keep", true); }
public function build($runData) { $pl = $runData->getParameterList(); $site = $runData->getTemp("site"); $pageId = $pl->getParameterValue("page_id"); $mode = $pl->getParameterValue("mode"); $runData->ajaxResponseAdd("mode", $mode); $user = $runData->getUser(); $userId = $runData->getUserId(); if ($userId == null) { $userString = $runData->createIpString(); $runData->contextAdd("anonymousString", $userString); } $db = Database::connection(); $db->begin(); if ($pageId === null || $pageId === '') { // means probably creating a new page // no context is needed $runData->sessionStart(); $mode = "page"; $runData->contextAdd("mode", $mode); $runData->contextAdd("newPage", true); // first create if a page not already exists! $unixName = $pl->getParameterValue("wiki_page"); $unixName = WDStringUtils::toUnixName($unixName); // purify! (for sure) if (!$unixName) { throw new ProcessException(_("The page can not be found or does not exist."), "no_page"); } $page = DB_PagePeer::instance()->selectByName($site->getSiteId(), $unixName); if ($page != null) { // page exists!!! error! throw new ProcessException(_("The page you want to create already exists. Please refresh the page in your browser to see it.")); /* $runData->ajaxResponseAdd("pageExists", true); $runData->ajaxResponseAdd("locked", true); //well, it is somehow locked... $runData->setModuleTemplate("edit/NewPageExistsWinModule"); $db->commit(); return; */ } // extract category name if (strpos($unixName, ':') != false) { // ok, there is category! $exp = explode(':', $unixName); $categoryName = $exp[0]; $suggestedTitle = ucwords(str_replace("-", " ", $exp[1])); } else { // no category name, "_default" assumed $categoryName = "_default"; $suggestedTitle = ucwords(str_replace("-", " ", $unixName)); } $stitle = $pl->getParameterValue("title"); if ($stitle) { $suggestedTitle = $stitle; } $category = DB_CategoryPeer::instance()->selectByName($categoryName, $site->getSiteId()); if ($category == null) { // get the default! //$category = DB_CategoryPeer::instance()->selectByName('_default', $site->getSiteId()); $category = $this->createTempCategory($categoryName, $site); } // now check for permissions!!! WDPermissionManager::instance()->hasPagePermission('create', $user, $category); $autoincrement = false; if (preg_match(';^([a-z0-9]+:)?' . self::$AUTOINCREMENT_PAGE . '$;', $unixName)) { $autoincrement = true; } if (!$autoincrement) { $lock = new DB_PageEditLock(); $lock->setPageUnixName($unixName); $lock->setSiteId($site->getSiteId()); $lock->setUserId($runData->getUserId()); $lock->setUserString($runData->getSession()->getIpAddress()); $lock->setDateStarted(new ODate()); $lock->setDateLastAccessed(new ODate()); $lock->setMode("page"); if ($pl->getParameterValue("force_lock") != null) { $lock->deleteConflicts(); } else { // check for conflicts $conflicts = $lock->getConflicts(); if ($conflicts != null) { $runData->ajaxResponseAdd("locked", true); $runData->setModuleTemplate("edit/NewPageLockedWinModule"); $runData->contextAdd("locks", $conflicts); return; } } $secret = md5(time() . rand(1000, 9999)); $lock->setSecret($secret); $lock->setSessionId($runData->getSession()->getSessionId()); $lock->save(); $runData->ajaxResponseAdd('lock_id', $lock->getLockId()); $runData->ajaxResponseAdd('lock_secret', $secret); } else { $runData->contextAdd('disableLocks', true); $runData->ajaxResponseAdd('disableLocks', true); } $runData->contextAdd("title", $suggestedTitle); /* Select available templates, but only if the category does not have a live template. */ $templatePage = $category->getTemplatePage(); if ($templatePage && ($form = Wikidot_Form::fromSource($templatePage->getSource()))) { $runData->contextAdd("form", new Wikidot_Form_Renderer($form)); } elseif (!$templatePage || !preg_match(';^={4,}$;sm', $templatePage->getSource())) { $templatesCategory = DB_CategoryPeer::instance()->selectByName("template", $site->getSiteId()); if ($templatesCategory != null) { $c = new Criteria(); $c->add("category_id", $templatesCategory->getCategoryId()); $c->addOrderAscending("title"); $templates = DB_PagePeer::instance()->select($c); $runData->contextAdd("templates", $templates); } // check if there is a default template... if ($category != null) { if ($category->getTemplateId() != null) { $runData->contextAdd("templateId", $category->getTemplateId()); } } } else { /* Has default template, try to populate the edit box with initial content. */ $templateSource = $templatePage->getSource(); $split = preg_split(';^={4,}$;sm', $templateSource); if (count($split) >= 2) { /* Fine, there is some initial content. */ $templateSource = trim(preg_replace(";^.*?\n={4,};s", '', $templateSource)); } else { $templateSource = ''; } $runData->contextAdd('source', $templateSource); } $db->commit(); return; } // now if editing an existing page... if (!$pageId || !is_numeric($pageId)) { throw new ProcessException(_("The page can not be found or does not exist."), "no_page"); } $page = DB_PagePeer::instance()->selectByPrimaryKey($pageId); if (!$page || $page->getSiteId() !== $site->getSiteId()) { throw new ProcessException(_("The page can not be found or does not exist."), "no_page"); } $category = $page->getCategory(); if ($category == null) { throw new ProcessException(_("Internal error - page category does not exist!!!")); } // now check for permissions! WDPermissionManager::instance()->hasPagePermission('edit', $user, $category, $page); // now check if form is defined $templatePage = $category->getTemplatePage(); if (preg_match('/^[^:]*:[^_]|^[^_:][^:]*$/', $page->getUnixName()) && $templatePage && ($form = Wikidot_Form::fromSource($templatePage->getSource()))) { $form->setDataFromYaml($page->getSource()); $runData->contextAdd("form", new Wikidot_Form_Renderer($form)); // check if mode is sections if page is editable in this mode } elseif ($mode == "section") { $compiledContent = $page->getCompiled()->getText(); $editable = WDEditUtils::sectionsEditable($compiledContent); if ($editable == false) { throw new ProcessException(_("Sections are not editable due to unclear section structure. This sometimes happen when nested headings are used (inside other page elements) or the page include other pages."), "sections_uneditable"); } // ok, get ranges for edit now. $pageSource = $page->getSource(); $rangeMap = WDEditUtils::sectionMapping($pageSource); $sectionId = $pl->getParameterValue("section"); if (!isset($rangeMap[$sectionId])) { throw new ProcessException(_("Sections are not editable due to unclear section structure. This sometimes happen when nested headings are used (inside other page elements) or the page include other pages."), "sections_uneditable"); } $rangeStart = $rangeMap[$sectionId]['start']; $rangeEnd = $rangeMap[$sectionId]['end']; $runData->ajaxResponseAdd('section', $sectionId); $runData->ajaxResponseAdd('rangeStart', $rangeStart); $runData->ajaxResponseAdd('rangeEnd', $rangeEnd); } // if we have not returned yet it means that the lock does not exist or is expired // if session is not started - start it! $runData->sessionStart(); // create new page lock $lock = new DB_PageEditLock(); $lock->setPageId($page->getPageId()); $lock->setPageUnixName($page->getUnixName()); $lock->setSiteId($site->getSiteId()); $lock->setUserId($runData->getUserId()); $lock->setUserString($runData->getSession()->getIpAddress()); $lock->setDateStarted(new ODate()); $lock->setDateLastAccessed(new ODate()); $lock->setMode($mode); if ($mode == "section") { $lock->setRangeStart($rangeStart); $lock->setRangeEnd($rangeEnd); } // delete outdated... DB_PageEditLockPeer::instance()->deleteOutdated($pageId); // check for conflicts if ($pl->getParameterValue("force_lock") != null) { $lock->deleteConflicts(); } else { $blocklocks = $lock->getConflicts(); if ($blocklocks != null) { // conflicting locks exist. $runData->setModuleTemplate("edit/LockExistsWinModule"); $runData->ajaxResponseAdd("locked", true); $runData->contextAdd("locks", $blocklocks); return; } } $secret = md5(time() . rand(1000, 9999)); $lock->setSecret($secret); $lock->setSessionId($runData->getSession()->getSessionId()); $lock->save(); $runData->ajaxResponseAdd('lock_id', $lock->getLockId()); $runData->ajaxResponseAdd('lock_secret', $secret); // also put current page revision in case one wants to regain lock after expired. $runData->ajaxResponseAdd('page_revision_id', $page->getRevisionId()); // keep the session - i.e. put an object into session storage not to delete it!!! $runData->sessionAdd("keep", true); if ($mode == "page") { $pageSource = $page->getSource(); $runData->contextAdd("source", $pageSource); } if ($mode == "append") { $runData->contextAdd("source", ""); // source not required... } if ($mode == "section") { // slice the source... $sliced = explode("\n", $pageSource); $s = array_slice($sliced, $rangeStart, $rangeEnd - $rangeStart + 1); $runData->contextAdd("source", trim(implode("\n", $s))); } $runData->contextAdd("title", $page->getTitleRaw()); $runData->contextAdd("pageId", $page->getPageId()); $runData->contextAdd("mode", $mode); $runData->ajaxResponseAdd("timeLeft", 15 * 60); $db->commit(); }
public function changeScreenNameEvent($runData) { $user = $runData->getUser(); $userId = $user->getUserId(); $profile = $user->getProfile(); if ($profile->getChangeScreenNameCount() >= 2) { throw new ProcessException('Your are allowed to change your screen name only 2 times.'); } $pl = $runData->getParameterList(); $name = trim($pl->getParameterValue("screenName")); if ($name == $user->getNickName()) { throw new ProcessException("Your new and current screen names are the same."); } $db = Database::connection(); $db->begin(); $unixified = WDStringUtils::toUnixName($name); if (strlen($name) < 2) { throw new ProcessException(_("You really should provide the screen name you want to use.")); } if (strlen8($name) > 20) { throw new ProcessException(_("Your screen name should not be longer than 20 characters.")); } if (preg_match('/^[ _a-zA-Z0-9-\\!#\\$%\\^\\*\\(\\)]+$/', $name) == 0) { throw new ProcessException(_("Only alphanumeric characters (+a few special) can be used in the screen name.")); } if (strlen($unixified) < 2) { throw new ProcessException(_("It seems there are too less alphanumeric characters in your screen name")); } //handle forbidden names $unixName = WDStringUtils::toUnixName($name); $forbiddenUnixNames = explode("\n", file_get_contents(WIKIDOT_ROOT . '/conf/forbidden_user_names.conf')); foreach ($forbiddenUnixNames as $f) { if (preg_match($f, $unixName) > 0) { throw new ProcessException(_('For some reason this name is not allowed or is reserved for future use.')); } } // check if user does not exist $c = new Criteria(); $c->add("unix_name", $unixified); $u = DB_OzoneUserPeer::instance()->selectOne($c); if ($u != null) { throw new ProcessException(_("A user with this screen name (or very similar) already exists.")); } // rename the profile page $c = new Criteria(); $c->add("unix_name", "profiles"); $nsite = DB_SitePeer::instance()->selectOne($c); $pageName = 'profile:' . $user->getUnixName(); $c = new Criteria(); $c->add('site_id', $nsite->getSiteId()); $c->add('unix_name', $pageName); $page = DB_PagePeer::instance()->selectOne($c); if (!$page) { throw new ProcessException('Internal error'); } $metadata = $page->getMetadata(); $metadata->setUnixName('profile:' . $unixified); $page->setUnixName('profile:' . $unixified); $metadata->save(); $page->save(); // outdate page cache $outdater = new Outdater(); $outdater->pageEvent("rename", $page, $pageName); // now, try to apply new name!!! $user->setNickName($name); $user->setUnixName($unixified); $user->save(); $profile->setChangeScreenNameCount($profile->getChangeScreenNameCount() + 1); $profile->save(); $db->commit(); }
public function renderEdit() { $m = array(); $path = array(); $v = $this->field['value']; $path = array(); if (preg_match($this->rule, $v, $m)) { $parts = explode(']]]', $v); foreach ($parts as $part) { $m = array(); if (preg_match(':^[^[]*\\[\\[\\[([^|]*)([|]|$):', $part, $m)) { $path[] = WDStringUtils::toUnixName($m[1]); } } } $path[] = ''; $selects = array(); $c = new Criteria(); $c->add('name', $this->field['category']); if ($category = DB_CategoryPeer::instance()->selectOne($c)) { $categoryId = $category->getCategoryId(); $pages = array(); $parentId = null; foreach ($path as $part) { $select = "<select>"; $select .= '<option value=""></option>'; $pages = $this->selectPagesByParent($categoryId, $parentId); $parentId = null; foreach ($pages as $page) { $unixName = htmlspecialchars($page->getUnixName()); $title = htmlspecialchars($page->getTitleOrUnixName()); $selected = ""; if ($unixName == $part) { $selected = ' selected="selected"'; $parentId = $page->getPageId(); } $select .= "<option value=\"{$unixName}\"{$selected}>{$title}</option>"; } $select .= '<option value="+" style="border-top: 1px solid #666; font-weight: bold">Create new</option>'; $select .= '</select>'; $selects[] = $select; if (!$parentId) { break; } } } $selectsEnd = ''; $selectsNo = count($selects); for ($i = 1; $i < count($selects); $i++) { $selectsEnd .= '</span>'; } return '<div class="field-pagepath-chooser">' . '<input class="value" type="hidden" name="field_' . $this->field['name'] . '" value="' . $this->hvalue() . '"/>' . '<input class="category" type="hidden" value="' . $this->field['category'] . '"/>' . '<input class="new_page_parent" type="hidden" name="newpageparent_' . $this->field['name'] . '" value=""/>' . '<input class="new_page_title" type="hidden" name="newpagetitle_' . $this->field['name'] . '" value=""/>' . '<span>' . implode("<span> / ", $selects) . '<span></span>' . $selectsEnd . '</span>' . '</div>'; /* in the end we get something like this: <div class="field-pagepath-choser"> <input type="hidden" value="" name=""/> <span> <select> <option/> <option/> ... </select> <span> / <select> <option/> <option/> ... </select> <span> / <select> <option/> <option/> ... </select> <span> / <select> <option/> <option/> ... </select> <span> </span> </span> </span> </span> </span> </div> */ }
public function save($args) { $db = Database::connection(); $db->begin(); // simple argument checking if (!isset($args['page'])) { throw new Wikidot_Facade_Exception_WrongArguments("Page argument must be passed"); } $pm = new WDPermissionManager(); $now = new ODate(); // page (existant or not) name $arg_page = WDStringUtils::toUnixName($args['page']); // parse the rest (beside page name) unset($args['page']); $this->parseArgs($args, array("performer", "site")); try { // parse page name to figure out if it points to an existant page $page = $this->_parsePage($this->site, $arg_page); $new = false; // check permissions to edit the page $pm->hasPagePermission('edit', $this->performer, $page->getCategory(), $page); } catch (Wikidot_Facade_Exception_WrongArguments $e) { if ($this->source === null) { $this->source = ""; } if ($this->title === null) { $this->title = $arg_page; } $new = true; $category_name = preg_replace('/^([^:]*):.*$/', '\\1', $arg_page); if ($category_name == $arg_page) { $category_name = '_default'; } $category = $this->_getOrCreateCategory($this->site, $category_name); $page = new DB_Page(); $page->setSiteId($this->site->getSiteId()); $page->setCategoryId($category->getCategoryId()); $page->setUnixName($arg_page); $page->setDateCreated(new ODate()); $page->setOwnerUserId($this->performer->getUserId()); $page->save(); $compiled = new DB_PageCompiled(); $compiled->setPageId($page->getPageId()); $compiled->save(); } // get current revision and metadata if (!$new) { $cur_rev = $page->getCurrentRevision(); $cur_meta = $cur_rev->getMetadata(); } // construct new metadata if ($new) { $new_meta = new DB_PageMetadata(); $new_meta->setUnixName($arg_page); $new_meta->setOwnerUserId($this->performer->getUserId()); } else { $new_meta = clone $cur_meta; $new_meta->setNew(true); $new_meta->setMetadataId(null); } // construct new revision $new_rev = new DB_PageRevision(); $new_rev->setSiteId($this->site->getSiteId()); $new_rev->setPageId($page->getPageId()); $new_rev->setUserId($this->performer->getUserId()); $new_rev->setDateLastEdited($now); if ($new) { $new_rev->setRevisionNumber(0); } else { $new_rev->setRevisionNumber($cur_rev->getRevisionNumber() + 1); } $src_changed = false; $title_changed = false; $parent_changed = false; $tags_changed = false; // handle source change if ($new || $this->source !== null && $page->getSource() != $this->source) { $new_src = new DB_PageSource(); $new_src->setText($this->source); $new_src->save(); $new_rev->setSourceId($new_src->getSourceId()); $src_changed = true; } else { $new_rev->setSourceId($cur_rev->getSourceId()); $new_rev->setSinceFullSource($cur_rev->getSinceFullSource()); $new_rev->setDiffSource($cur_rev->getDiffSource()); } // handle tags change if ($this->tags) { $new_tags = $this->tags; $cur_tags = $page->getTagsAsArray(); sort($cur_tags); sort($new_tags); if ($cur_tags != $new_tags) { $tags_changed = true; $tags_deleted = array(); $tags_added = array(); foreach ($cur_tags as $tag) { if (!in_array($tag, $new_tags)) { $c = new Criteria(); $c->add('page_id', $page->getPageId()); $c->add('tag', $tag); if ($t = DB_PageTagPeer::instance()->selectOne($c)) { $t->delete(); $tags_deleted[] = $tag; } } } foreach ($new_tags as $tag) { if (!in_array($tag, $cur_tags)) { $t = new DB_PageTag(); $t->getPageId($page->getPageId()); $t->setSiteId($this->site->getSiteId()); $t->setTag($tag); $t->save(); $tags_added[] = $tag; } } } } // handle metadata: title change if ($new || $this->title !== null && $cur_meta->getTitle() != $this->title) { $new_meta->setTitle($this->title); $page->setTitle($this->title); $title_changed = true; } // handle metadata: parent page change if ($this->parent_page) { if (!$cur_meta->getParentPageId() || $cur_meta->getParentPageId() != $this->parent_page->getPageId()) { $new_meta->setParentPageId($this->parent_page->getPageId()); $parent_changed = true; } } if ($this->clear_parent_page && $page->getParentPageId()) { $new_meta->setParentPageId(null); $parent_changed = true; } $meta_changed = $title_changed || $parent_changed; // decide whether to use previous metadata or create a new object if ($meta_changed) { $new_meta->save(); $new_rev->setMetadataId($new_meta->getMetadataId()); } else { $new_rev->setMetadataId($cur_meta->getMetadataId()); } // set flag on revision if ($new) { $new_rev->setFlagNew(true); } else { if ($src_changed) { $new_rev->setFlagText(true); } if ($title_changed) { $new_rev->setFlagTitle(true); } if ($parent_changed) { $new_rev->setFlagMeta(true); } } if ($src_changed || $meta_changed || $tags_changed) { $new_rev->save(); $page->setSourceId($new_rev->getSourceId()); $page->setDateLastEdited($now); $page->setMetadataId($new_rev->getMetadataId()); $page->setRevisionNumber($new_rev->getRevisionNumber()); $page->setRevisionId($new_rev->getRevisionId()); $page->save(); $db->commit(); $GLOBALS['site'] = $this->site; $outdater = new Outdater(); if ($src_changed) { $outdater->pageEvent("source_changed", $page); } if ($title_changed) { $outdater->pageEvent("title_changed", $page); } if ($parent_changed) { $outdater->pageEvent("parent_changed", $page); } if ($tags_changed) { $outdater->pageEvent("tag_changed", $page); } } else { /* This place is reached when API client tries to set source or * title or parent page or tags that are already set (in the DB) * to the same value. * * Let's suppose doing nothing is the desired behavior in this case * * Other possible way to react can be raising an exception. * But it should be different from Wikidot_Facade_Exception_WrongArguments * because this one implies client error (and client does not need * to know the exact database state). */ } }
public function saveCollectEvent($runData) { $site = $runData->getTemp("site"); $pl = $runData->getParameterList(); $campaignId = $pl->getParameterValue("campaignId"); $thankYouPage = WDStringUtils::toUnixName($pl->getParameterValue("thankYouPage")); $c = new Criteria(); $c->add("site_id", $site->getSiteId()); $c->add("deleted", false); $c->add("campaign_id", $campaignId); $camp = DB_PetitionCampaignPeer::instance()->selectOne($c); if (!$camp) { throw new ProcessException(_("The campaign can not be found.")); } // so, what to collect and show? $co = array(); $sh = array(); $co['address'] = (bool) $pl->getParameterValue("collectAddress"); $co['city'] = (bool) $pl->getParameterValue("collectCity"); $sh['city'] = (bool) $pl->getParameterValue("showCity"); $co['state'] = (bool) $pl->getParameterValue("collectState"); $sh['state'] = (bool) $pl->getParameterValue("showState"); $co['zip'] = (bool) $pl->getParameterValue("collectZip"); $sh['zip'] = (bool) $pl->getParameterValue("showZip"); $co['country'] = (bool) $pl->getParameterValue("collectCountry"); $sh['country'] = (bool) $pl->getParameterValue("showCountry"); $co['comments'] = (bool) $pl->getParameterValue("collectComments"); $sh['comments'] = (bool) $pl->getParameterValue("showComments"); // check if the landing page exists if ($thankYouPage) { $page = DB_PagePeer::instance()->selectByName($site->getSiteId(), $thankYouPage); if (!$page) { throw new ProcessException('The "thank you" page does not exist'); } } $camp->setCollectAddress($co['address']); $camp->setCollectCity($co['city']); $camp->setShowCity($sh['city']); $camp->setCollectState($co['state']); $camp->setShowState($sh['state']); $camp->setCollectZip($co['zip']); $camp->setShowZip($sh['zip']); $camp->setCollectCountry($co['country']); $camp->setShowCountry($sh['country']); $camp->setCollectComments($co['comments']); $camp->setShowComments($sh['comments']); $camp->setThankYouPage($thankYouPage); $camp->save(); }
public function build($runData) { $pl = $runData->getParameterList(); $site = $runData->getTemp("site"); $categoryIds = $pl->getParameterValue("category"); $limit = $pl->getParameterValue("limit"); $offset = $pl->getParameterValue("offset"); if ($limit == null) { $limit = 20; } if ($categoryIds === null) { throw new ProcessException(_('No forum category has been specified. Please use attribute category="id" where id is the index number of the category.'), "no_category"); } if (strlen($categoryIds) > 90) { throw new ProcessException(_("Category string too long."), "max_categories"); } $cats = preg_split('/[,;] ?/', $categoryIds); $ccat = new Criteria(); $categories = array(); if (count($cats) > 20) { throw new ProcessException(_("Maximum number of categories exceeded."), "max_categories"); } foreach ($cats as $categoryId) { if ($categoryId === null || !is_numeric($categoryId)) { throw new ProcessException(_('Problem parsing attribute "category".'), "no_category"); } $category = DB_ForumCategoryPeer::instance()->selectByPrimaryKey($categoryId); if ($category == null) { throw new ProcessException(_('Requested forum category does not exist.'), "no_category"); } if ($category->getSiteId() !== $site->getSiteId()) { $fSite = DB_SitePeer::instance()->selectByPrimaryKey($category->getSiteId()); if ($fSite->getPrivate()) { throw new ProcessException(_('The requested category belongs to a private site.'), "no_category"); } } $category->setTemp("group", $category->getForumGroup()); $categories[$category->getCategoryId()] = $category; $ccat->addOr("category_id", $category->getCategoryId()); } $c = new Criteria(); $c->addCriteriaAnd($ccat); $c->addOrderDescending("thread_id"); $c->setLimit($limit, $offset); $threads = DB_ForumThreadPeer::instance()->select($c); $format = $pl->getParameterValue("module_body"); if ($format == null || $format == '') { $format = "" . "+ %%linked_title%%\n\n" . _("by") . " %%author%% %%date|%O ago (%e %b %Y, %H:%M %Z)%%\n\n" . "%%content%%\n\n%%comments%% | " . _("category") . ": %%category%%"; } // process the format and create the message template $wt = new WikiTransformation(); $wt->setMode("feed"); $template = $wt->processSource($format); $template = preg_replace('/<p\\s*>\\s*(%%((?:short)|(?:description)|(?:summary)|(?:content)|(?:long)|(?:body)|(?:text))%%)\\s*<\\/\\s*p>/smi', "<div>\\1</div>", $template); $items = array(); foreach ($threads as $thread) { $post = $thread->getFirstPost(); if (!$post) { continue; } $b = $template; $b = str_ireplace("%%title%%", htmlspecialchars($thread->getTitle()), $b); $b = preg_replace("/%%((linked_title)|(title_linked))%%/i", preg_quote_replacement('<a href="/forum/t-' . $thread->getThreadId() . '/' . $thread->getUnixifiedTitle() . '">' . htmlspecialchars($thread->getTitle()) . '</a>'), $b); $b = str_ireplace("%%author%%", WDRenderUtils::renderUser($thread->getUserOrString(), array("image" => true)), $b); $dateString = '<span class="odate">' . $thread->getDateStarted()->getTimestamp() . '|%e %b %Y, %H:%M %Z|agohover</span>'; $b = str_ireplace('%%date%%', $dateString, $b); $b = preg_replace('/%%date\\|(.*?)%%/i', '<span class="odate">' . preg_quote_replacement($thread->getDateStarted()->getTimestamp()) . '|\\1</span>', $b); $b = str_ireplace("%%comments%%", '<a href="/forum/t-' . $thread->getThreadId() . '/' . $thread->getUnixifiedTitle() . '">' . _('Comments') . ': ' . ($thread->getNumberPosts() - 1) . '</a>', $b); $b = str_ireplace("%%link%%", '/forum/t-' . $thread->getThreadId() . '/' . $thread->getUnixifiedTitle(), $b); $category = $categories[$thread->getCategoryId()]; $b = str_ireplace("%%category%%", '<a href="/forum/c-' . $category->getCategoryId() . '/' . $category->getUnixifiedName() . '">' . htmlspecialchars($category->getTemp("group")->getName() . " / " . $category->getName()) . '</a>', $b); $b = preg_replace("/%%((description)|(short)|(summary))%%/i", preg_quote_replacement(htmlspecialchars($thread->getDescription())), $b); $b = preg_replace("/%%((body)|(text)|(long)|(content))%%/i", preg_quote_replacement($post->getText()), $b); $items[] = $b; } $runData->contextAdd("items", $items); // post a feed??? $flabel = WDStringUtils::toUnixName($pl->getParameterValue("feed")); $page = $runData->getTemp("page"); if ($flabel && $page) { $ftitle = trim($pl->getParameterValue("feedTitle")); if ($ftitle == '') { $ftitle = $site->getName() . " feed"; } $fdescription = $pl->getParameterValue("feedDescription"); $fcats = trim($categoryIds); $parmhash = crc32($ftitle . " " . $fcats); // first check the memcache!!! to avoid db connection. // get the feed object $c = new Criteria(); $c->add("page_id", $page->getPageId()); $c->add("label", $flabel); $feed = DB_FrontForumFeedPeer::instance()->selectOne($c); if ($feed == null) { // create the feed $feed = new DB_FrontForumFeed(); $feed->setLabel($flabel); $feed->setTitle($ftitle); $feed->setCategories($fcats); $feed->setPageId($page->getPageId()); $feed->setDescription($fdescription); $feed->setSiteId($site->getSiteId()); $feed->save(); } else { // check hash if ($feed->getParmhash() != $parmhash) { $feed->setTitle($ftitle); $feed->setCategories($fcats); $feed->setDescription($fdescription); $feed->save(); } } // and the feed url is: $feedUrl = "/feed/front/" . $page->getUnixName() . "/" . $flabel . ".xml"; $this->vars['feedUrl'] = $feedUrl; $this->vars['feedTitle'] = $ftitle; $this->vars['feedLabel'] = $flabel; // put a link into text $runData->contextAdd("feedUri", $feedUrl); } }
public function sendFormEvent($runData) { $pl = $runData->getParameterList(); $values = $pl->getParameterValue("formdata"); $json = new JSONService(SERVICES_JSON_LOOSE_TYPE); $values = $json->decode($values); $site = $runData->getTemp("site"); $fkey = trim($pl->getParameterValue("formdef")); $data = DatabaseStorage::instance()->get($fkey); if (!$data) { throw new ProcessException(_("No form definition found.")); } $fields = $data['fields']; $email = $data['email']; $title = $data['title']; $format = strtolower(trim($data['format'])); if (!in_array($format, array('csv'))) { $format = null; } // parse and validate! $errors = array(); foreach ($fields as &$field) { $name = $field['name']; $value = $values[$field['name']]; $field['value'] = $value; // check if need to validate. any rules? // first, if select, can not be empty if ($field['type'] == "select") { if (!$value) { $errors[$name] = _('Please select an option'); continue; } } if ($field['rules'] && is_array($field['rules'])) { foreach ($field['rules'] as $ruleName => $ruleValue) { switch ($ruleName) { case 'required': if ($value == "") { $errors[$name] = _('Please enter this information'); break 2; } break; case 'minLength': if (strlen8($value) < $ruleValue) { $errors[$name] = _('Value is too short'); break 2; } break; case 'maxLength': if (strlen8($value) > $ruleValue) { $errors[$name] = _('Value is too long'); break 2; } break; case 'match': if (!preg_match($ruleValue, $value)) { $errors[$name] = _('Value is not valid'); break 2; } break; case 'number': if (!is_numeric($value)) { $errors[$name] = _('Value is not numeric'); break 2; } break; case 'minValue': if (!is_numeric($value) || 1 * $value < 1 * $ruleValue) { $errors[$name] = _('Value is too small'); break 2; } break; case 'maxValue': if (!is_numeric($value) || 1 * $value > 1 * $ruleValue) { $errors[$name] = _('Value is too large'); break 2; } break; } } } // fix checkboxes if ($field['type'] == "checkbox") { if (!$value) { $field['value'] = _('No'); } else { $field['value'] = _('Yes'); } } } if (count($errors)) { // "sir, we have some errors here. shit." $runData->ajaxResponseAdd("errors", $errors); throw new ProcessException("Form errors.", "form_errors"); } $title = $title ? $title : sprintf(_("[%s] MailForm form data"), GlobalProperties::$SERVICE_NAME); $oe = new OzoneEmail(); $oe->addAddress($email); $oe->setSubject($title); $oe->contextAdd('fields', $fields); $oe->contextAdd('values', $values); switch ($format) { case 'csv': $emailTemplate = 'wiki/mailform/MailFormCSV'; // fix the values (escape) foreach ($fields as &$field) { $value = $field['value']; if (preg_match("/[,\"\n]/", $value)) { $value = str_replace('"', '""', $value); $value = '"' . $value . '"'; $field['value'] = $value; } } break; default: $emailTemplate = 'wiki/mailform/MailForm'; break; } $oe->setBodyTemplate($emailTemplate); if (!$oe->Send()) { throw new ProcessException(_("The form data could not be sent to the specified email address."), "email_failed"); } // ok, is there any success page? $successPage = $data['successPage']; if ($successPage) { $successPage = WDStringUtils::toUnixName($successPage); $page = DB_PagePeer::instance()->selectByName($site->getSiteId(), $successPage); if ($page) { $runData->ajaxResponseAdd("successPage", $successPage); } } if (GlobalProperties::$UI_SLEEP) { sleep(1); } }
protected function _parsePage($site, $page) { if (is_int($page)) { // int = ID $page = DB_PagePeer::instance()->selectByPrimaryKey($page); } elseif (is_string($page)) { if ($site) { $page = preg_replace("/^_default:/", "", $page); $c = new Criteria(); $c->add("unix_name", WDStringUtils::toUnixName($page)); $c->add("site_id", $site->getSiteId()); $page = DB_PagePeer::instance()->selectOne($c); } } if ($page instanceof DB_Page) { return $page; } throw new Wikidot_Facade_Exception_WrongArguments("Page does not exist"); }
public function saveEvent($runData) { $params = $runData->getParameterList()->asArray(); $ids = array(); foreach ($params as $param_key => $param_val) { $m = array(); if (preg_match(';^nick_name_([new0-9]+)$;', $param_key, $m)) { $ids[] = $m[1]; } } foreach ($ids as $id) { $nick_name = $params["nick_name_{$id}"]; $password = $params["password_{$id}"]; $admin = $params["admin_{$id}"] ? true : false; $mod = $params["mod_{$id}"] ? true : false; $site = $runData->getTemp('site'); if ($nick_name) { if ($id = 1 * $id) { $u = DB_OzoneUserPeer::instance()->selectByPrimaryKey($id); } else { $u = null; } $next = false; if (!$u) { $u = new DB_OzoneUser(); if (!$password) { $next = true; } $u->save(); $m = new DB_Member(); $m->setUserId($u->getUserId()); $m->setSiteId($site->getSiteId()); $m->save(); } if (!$next) { $u->setName($nick_name); $u->setEmail($nick_name); $u->setNickName($nick_name); $u->setUnixName(WDStringUtils::toUnixName($nick_name)); if ($password) { $u->setPassword(md5($password)); } $u->save(); if ($admin) { if (!WDPermissionManager::hasPermission('manage_site', $u, $site)) { $a = new DB_Admin(); $a->setUserId($u->getUserId()); $a->setSiteId($site->getSiteId()); $a->save(); } } else { // ! $admin $c = new Criteria(); $c->add('site_id', $site->getSiteId()); $c->add('user_id', $u->getUserId()); DB_AdminPeer::instance()->delete($c); } if ($mod) { if (!WDPermissionManager::hasPermission('moderate_site', $u, $site)) { $m = new DB_Moderator(); $m->setUserId($u->getUserId()); $m->setSiteId($site->getSiteId()); $m->save(); } } else { // ! $mod $c = new Criteria(); $c->add('site_id', $site->getSiteId()); $c->add('user_id', $u->getUserId()); DB_ModeratorPeer::instance()->delete($c); } } } } }
public function setParentPageEvent($runData) { $site = $runData->getTemp("site"); $pl = $runData->getParameterList(); $pageId = $pl->getParameterValue("pageId"); // originating page id. $ppName = trim($pl->getParameterValue("parentName")); $ppName = WDStringUtils::toUnixName($ppName); $db = Database::connection(); $db->begin(); $c = new Criteria(); $c->add("page_id", $pageId); $c->setForUpdate(true); $page = DB_PagePeer::instance()->selectOne($c); if ($page == null) { throw new ProcessException(_("Error: original page does not exist any more...???"), "no_page"); } // check permissions $user = $runData->getUser(); $category = $page->getCategory(); WDPermissionManager::instance()->hasPagePermission('edit', $user, $category, $page); if ($ppName == null || $ppName === '') { $ppName = null; $ppId = null; } else { // get the page! $pp = DB_PagePeer::instance()->selectByName($site->getSiteId(), $ppName); if ($pp == null) { // page does not exist. return error throw new ProcessException(_("The requested page does not exist. Please indicate a parent page that already exists."), "no_parent_page"); } // check if not "self" if ($pp->getPageId() == $page->getPageId()) { throw new ProcessException(_("Can not set parent page to this page."), "loop_error"); } // check permissions to edit the parent page (???) - it somehow affects // the parrent page when listing childpages or making pagetree $category2 = $pp->getCategory(); try { WDPermissionManager::instance()->hasPagePermission('edit', $user, $category2); } catch (Exception $e) { throw new ProcessException(_('You are not allowed to alter contents of the parent page. You should have the "edit" permission on the parent page too.'), "not_allowed"); } $ppId = $pp->getPageId(); } // now check if the parent_page_id has changed... if ($page->getParentPageId() != $ppId) { // need to change... // create a new revision!!!!!!!!!!!!!!! // create new revision, new metadata and alter the page object too. $oldMetadata = $page->getMetadata(); $metadata = clone $oldMetadata; $metadata->setNew(true); $metadata->setMetadataId(null); $metadata->setParentPageId($ppId); $metadata->save(); $revision = $page->getCurrentRevision(); $revision->setNew(true); $revision->setRevisionId(null); $revision->resetFlags(); $revision->setFlagMeta(true); $revision->setMetadataId($metadata->getMetadataId()); $revision->setRevisionNumber($revision->getRevisionNumber() + 1); $now = new ODate(); $revision->setDateLastEdited($now); $revision->setComments(_("Parent page set to") . ": \"{$ppName}\"."); $userId = $runData->getUserId(); if ($userId == null) { $userString = $runData->createIpString(); } if ($userId) { $revision->setUserId($userId); $page->setLastEditUserId($userId); } else { $revision->setUserId(0); $page->setLastEditUserId(0); $revision->setUserString($userString); $page->setLastEditUserString($userString); } $revision->setDateLastEdited($now); $revision->save(); // alter the page info $page->setRevisionId($revision->getRevisionId()); $page->setRevisionNumber($revision->getRevisionNumber()); $page->setDateLastEdited($now); $page->setParentPageId($ppId); $page->save(); // outdate page $od = new Outdater(); $od->pageEvent('parent_changed', $page); EventLogger::instance()->logPageParentChange($page, $pp); } else { // no need to change! throw new ProcessException(_("Parent page has not been changed because the submitted and current values are identical."), "no_change"); } $db->commit(); }
/** * Changes the "unix name" of the site and effectively its URL address. * * @param unknown_type $runData */ public function renameSiteEvent($runData) { $pl = $runData->getParameterList(); $site = $runData->getTemp("site"); $user = $runData->getUser(); $unixName = trim($pl->getParameterValue('unixName')); $c = new Criteria(); $c->add("user_id", $user->getUserId()); $c->add("site_id", $site->getSiteId()); $c->add("founder", true); $rel = DB_AdminPeer::instance()->selectOne($c); if (!$rel) { throw new ProcessException(_("Sorry, you have no permissions to change URL of this site.")); } $db = Database::connection(); $db->begin(); $oldUnixName = $site->getUnixName(); // validate unix name $errors = array(); if ($unixName == $site->getUnixName()) { $errors['unixname'] = _('The new and current addresses are the same.'); } elseif ($unixName === null || strlen($unixName) < 3 || strlen(WDStringUtils::toUnixName($unixName)) < 3) { $errors['unixname'] = _("Web address must be present and should be at least 3 characters long."); } elseif (strlen($unixName) > 30) { $errors['unixname'] = _("Web address name should not be longer than 30 characters."); } elseif (preg_match("/^[a-z0-9\\-]+\$/", $unixName) == 0) { $errors['unixname'] = _('Only lowercase alphanumeric and "-" (dash) characters allowed in the web address.'); } elseif (preg_match("/\\-\\-/", $unixName) !== 0) { $errors['unixname'] = _('Only lowercase alphanumeric and "-" (dash) characters allowed in the web address. Double-dash (--) is not allowed.'); } else { $unixName = WDStringUtils::toUnixName($unixName); if (!$runData->getUser()->getSuperAdmin()) { // handle forbidden names $forbiddenUnixNames = explode("\n", file_get_contents(WIKIDOT_ROOT . '/conf/forbidden_site_names.conf')); foreach ($forbiddenUnixNames as $f) { if (preg_match($f, $unixName) > 0) { $errors['unixname'] = _('For some reason this web address is not allowed or is reserved for future use.'); } } } // check if the domain is not taken. $c = new Criteria(); $c->add("unix_name", $unixName); $ss = DB_SitePeer::instance()->selectOne($c); if ($ss) { $errors['unixname'] = _('Sorry, this web address is already used by another site.'); } } if (isset($errors['unixname'])) { throw new ProcessException($errors['unixname']); } // remove some data. $c = new Criteria(); $c->add('site_id', $site->getSiteId()); // now clear cache! $keys = array(); $keys[] = 'site..' . $site->getUnixName(); $keys[] = 'site_cd..' . $site->getCustomDomain(); $mc = OZONE::$memcache; foreach ($keys as $k) { $mc->delete($k); } $outdater = new Outdater(); $outdater->siteEvent('delete', $site); $outdater->siteEvent('sitewide_change', $site); // change site name!!! $site->setUnixName($unixName); $site->save(); // remove custom domain link // rename the files @rename(WIKIDOT_ROOT . '/web/files--sites/' . $oldUnixName, WIKIDOT_ROOT . '/web/files--sites/' . $site->getUnixName()); // delete custom domain link if ($site->getCustomDomain()) { @unlink(WIKIDOT_ROOT . '/web/custom--domains/' . $site->getCustomDomain()); symlink(WIKIDOT_ROOT . '/web/files--sites/' . $site->getUnixName(), WIKIDOT_ROOT . '/web/custom--domains/' . $site->getCustomDomain()); } $db->commit(); $runData->ajaxResponseAdd("unixName", $site->getUnixName()); }
public function restoreSiteEvent($runData) { $pl = $runData->getParameterList(); $siteId = $pl->getParameterValue('siteId'); $unixName = trim($pl->getParameterValue('unixName')); $c = new Criteria(); $c->add('site_id', $siteId); $c->add('deleted', true); $site = DB_SitePeer::instance()->selectOne($c); if (!$site) { throw new ProcessException(_('Error selecting a site to restore.')); } // check if allowed $user = $runData->getUser(); $c = new Criteria(); $c->add("user_id", $user->getUserId()); $c->add("site_id", $site->getSiteId()); $c->add("founder", true); $rel = DB_AdminPeer::instance()->selectOne($c); if (!$rel) { throw new ProcessException(_("Sorry, you have no permissions to restore this site.")); } $db = Database::connection(); $db->begin(); // validate unix name $errors = array(); if ($unixName === null || strlen($unixName) < 3 || strlen(WDStringUtils::toUnixName($unixName)) < 3) { $errors['unixname'] = _("Web address must be present and should be at least 3 characters long."); } elseif (strlen($unixName) > 30) { $errors['unixname'] = _("Web address name should not be longer than 30 characters."); } elseif (preg_match("/^[a-z0-9\\-]+\$/", $unixName) == 0) { $errors['unixname'] = _('Only lowercase alphanumeric and "-" (dash) characters allowed in the web address.'); } elseif (preg_match("/\\-\\-/", $unixName) !== 0) { $errors['unixname'] = _('Only lowercase alphanumeric and "-" (dash) characters allowed in the web address. Double-dash (--) is not allowed.'); } else { $unixName = WDStringUtils::toUnixName($unixName); if (!$runData->getUser()->getSuperAdmin()) { // handle forbidden names $forbiddenUnixNames = explode("\n", file_get_contents(WIKIDOT_ROOT . '/conf/forbidden_site_names.conf')); foreach ($forbiddenUnixNames as $f) { if (preg_match($f, $unixName) > 0) { $errors['unixname'] = _('For some reason this web address is not allowed or is reserved for future use.'); } } } // check if the domain is not taken. $c = new Criteria(); $c->add("unix_name", $unixName); $ss = DB_SitePeer::instance()->selectOne($c); if ($ss) { $errors['unixname'] = _('Sorry, this web address is already used by another site.'); } } if (isset($errors['unixname'])) { throw new ProcessException($errors['unixname']); } $oldUnixName = $site->getUnixName(); $oldLocalPath = $site->getLocalFilesPath(); $site->setUnixName($unixName); // rename the files mkdirfull(dirname($site->getLocalFilesPath())); @rename($oldLocalPath, $site->getLocalFilesPath()); $site->setDeleted(false); $site->setCustomDomain(null); $site->save(); $db->commit(); $runData->ajaxResponseAdd('unixName', $site->getUnixName()); }
private function fixLink($matches) { $pageName = WDStringUtils::toUnixName($matches[2]); $start = $matches[1]; $rest = $matches[3]; if ($pageName != $this->oldPageName) { return $matches[0]; } else { return $start . $this->newPageName . $rest; } }
public function getUnixifiedTitle() { return WDStringUtils::toUnixName($this->getTitle()); }
public function finalizeEvent($runData, $skipEvcode = false) { // get the form data $pl = $runData->getParameterList(); if (!$skipEvcode) { $evcode = $pl->getParameterValue("evcode", "AMODULE"); //check if the email vercode is correct $evcode2 = $runData->sessionGet('evcode'); if ($evcode !== $evcode2) { throw new ProcessException(_("Invalid email verification code."), "invalid_code"); } } $data = $runData->sessionGet("ca_data"); $name = $data['name']; $email = $data['email']; $password = $data['password']; $lang = $data['language']; $db = Database::connection(); $db->begin(); // check again if email and nick are not duplicate! $c = new Criteria(); $c->add("lower(email)", strtolower($email)); $u = DB_OzoneUserPeer::instance()->selectOne($c); if ($u != null) { $runData->resetSession(); throw new ProcessException(_("A user with this email already exists. Must have been created meanwhile... " . "Unfortunately you have to repeat the whole procedure. :-("), "user_exists"); } $unixified = WDStringUtils::toUnixName($name); $c = new Criteria(); $c->add("unix_name", $unixified); $u = DB_OzoneUserPeer::instance()->selectOne($c); if ($u != null) { $runData->resetSession(); throw new ProcessException(_("A user with this name (or very similar) already exists. Must have been created meanwhile... " . "Unfortunately you have to repeat the whole procedure. :-("), "user_exists"); } // add new user!!! $nuser = new DB_OzoneUser(); /* email as the username!!! */ $nuser->setName($email); $nuser->setEmail($email); $nuser->setPassword(md5($password)); $nuser->setNickName($name); $nuser->setUnixName($unixified); $nuser->setLanguage($lang); $date = new ODate(); $nuser->setRegisteredDate($date); $nuser->setLastLogin($date); $nuser->save(); // profile $profile = new DB_Profile(); $profile->setUserId($nuser->getUserId()); $profile->save(); $us = new DB_UserSettings(); $us->setUserId($nuser->getUserId()); $us->save(); // profile page $c = new Criteria(); $c->add("unix_name", "profiles"); $nsite = DB_SitePeer::instance()->selectOne($c); $ncategory = DB_CategoryPeer::instance()->selectByName('profile', $nsite->getSiteId()); $dup = new Duplicator(); $dup->setOwner($nuser); $dup->duplicatePage(DB_PagePeer::instance()->selectByName($nsite->getSiteId(), 'template:profile'), $nsite, $ncategory, 'profile:' . $nuser->getUnixName()); $page = DB_PagePeer::instance()->selectByName($nsite->getSiteId(), 'profile:' . $nuser->getUnixName()); $ou = new Outdater(); $ou->pageEvent('new_page', $page); $db->commit(); /* Handle originalUrl. */ $originalUrl = $runData->sessionGet('loginOriginalUrl'); if ($originalUrl) { $runData->ajaxResponseAdd('originalUrl', $originalUrl); if ($runData->sessionGet('loginOriginalUrlForce')) { $runData->ajaxResponseAdd('originalUrlForce', true); } } // reset session etc. $runData->resetSession(); $runData->getSession()->setUserId($nuser->getUserId()); setcookie("welcome", $nuser->getUserId(), time() + 10000000, "/", GlobalProperties::$SESSION_COOKIE_DOMAIN); setcookie(GlobalProperties::$SESSION_COOKIE_NAME_IE, $runData->getSessionId(), null, "/"); }