/** * Invitation form and processing of invited user details */ public function actionIndex($p) { if ($this->request->isPost()) { $firstName = Fari_Decode::accents($this->request->getPost('first')); $lastName = Fari_Decode::accents($this->request->getPost('last')); $email = $this->request->getPost('email'); if (!Fari_Filter::isEmail($email) or empty($firstName)) { $this->bag->message = array('status' => 'fail', 'message' => 'Whoops, make sure you enter a full name and proper email address.'); $this->bag->first = $this->request->getRawPost('first'); $this->bag->last = $this->request->getRawPost('last'); $this->bag->email = $this->request->getRawPost('email'); } else { $name = $this->accounts->newInvitation($firstName, $lastName, $email); // mail the instructions $mail = new Mailer(); try { $mail->sendInvitation(); } catch (UserNotFoundException $e) { $this->redirectTo('/error404/'); } $this->flashSuccess = "{$name} is now added to your account. An email with instructions was sent to {$email}"; $this->redirectTo('/users/'); } } $this->bag->tabs = $this->user->inRooms(); $this->renderAction('new'); }
/** * Check for uniqueness of the username * * @param string $username URL encoded username */ public function actionCheckUsername($username) { // is this Ajax? if ($this->request->isAjax()) { // URL decode & filter out username $username = Fari_Escape::text(Fari_Decode::url($username)); if (empty($username)) { $this->renderJson("The username can't be empty."); } else { // alphanumeric only? if (!Fari_Filter::isAlpha($username)) { $this->renderJson("Only alphanumeric characters are allowed."); } else { // do we have a match? if (!$this->accounts->isUsernameUnique($username)) { $this->renderJson("The username \"{$username}\" is unavailable, sorry."); } else { $this->renderJson(''); } } } } else { $this->renderTemplate('error404/javascript'); } }
/** * Will format the date in tables as per our wishes. * Will leave date unchanged if $dateFormat not recognized * * @param string $date Date in 'standard' format YYYY-MM-DD * @param string $dateFormat Target formatting to use (YYYY-MM-DD, DD-MM-YYYY, D MONTH YYYY, RSS) * @return string Formatted date */ public static function date($date, $dateFormat) { // check if input date is valid if (Fari_Filter::isDate($date)) { // split into params list($year, $month, $day) = preg_split('/[-\\.\\/ ]/', $date); // else return input } else { return $date; } switch ($dateFormat) { case 'DD-MM-YYYY': return $day . '-' . $month . '-' . $year; break; case 'D MONTH YYYY': // get month's name $month = date('F', mktime(0, 0, 0, $month, 1)); // make a nice day formatting, 9th, 10th etc. if ($day < 10) { $day = substr($day, 1, 1); } return $day . ' ' . $month . ' ' . $year; break; case 'RSS': return date(DATE_RSS, mktime(0, 0, 0, $month, $day, $year)); break; // for unknown formats or default, just return // for unknown formats or default, just return default: return $date; } }
private function filterLinkify($text) { $urls = explode(' ', $text); $containsLink = FALSE; foreach ($urls as &$link) { if (Fari_Filter::isURL($link)) { $containsLink = TRUE; // do we have a YouTube video? // source: http://www.youtube.com/watch?v=nBBMnY7mANg&feature=popular // target: <img src="http://img.youtube.com/vi/nBBMnY7mANg/0.jpg" alt="0"> if (stripos(strtolower($link), 'youtube') !== FALSE) { $url = parse_url($link); parse_str($url[query], $query); // replace link with an image 'boosted' link :) $link = '<a class="youtube" target="_blank" href="' . $link . '"><img src="http://img.youtube.com/vi/' . $query['v'] . '/0.jpg" alt="YouTube"></a>'; } else { // plain old link $link = '<a target="_blank" href="' . $link . '">' . $link . '</a>'; } // convert so we can insert into DB $link = Fari_Escape::html($link); } } if ($containsLink) { return implode(' ', $urls); } else { return $text; } }
public function get($lastMessageId) { if (Fari_Filter::isInt($lastMessageId)) { // get is the freshest messages $newMessages = Messages::get($lastMessageId); // handle with JSON echo json_encode($newMessages); } }
/** * Set a cookie under our namespace. * * @param string $name Name of the cookie we want to save it under * @param string $value Value we want to set * @param int $expiry Expiry in seconds from now * @return boolean FALSE if cookie set unsuccesfuly */ public static function set($name, $value, $expiry) { // check we have data if (isset($name) && isset($value) && Fari_Filter::isInt($expiry)) { setcookie(self::COOKIE_STORAGE . $name, $value, time() + $expiry); } else { return FALSE; } }
/** * File upload * FIXME anyone can upload to another room! */ public function actionUpload() { $roomId = $this->request->getPost('roomId'); if (Fari_Filter::isInt($roomId)) { $file =& $this->request->getFile(); // save the file and get its code $this->file = new Upload($file, $roomId); $this->renderUpload($roomId); } }
/** * Delete the room */ public function actionDelete($roomId) { if ($this->request->isAjax()) { if (Fari_Filter::isInt($roomId)) { try { $this->settings->deleteRoom($roomId); } catch (RoomNotFoundException $e) { // } } } else { $this->renderTemplate('error404/javascript'); } }
public function sendInvitation() { // fetch the newly invited user $users = new Table('users'); $user = $users->findFirst('id DESC')->where(array('role' => 'invited')); // have we actually retrieved the user? if (!Fari_Filter::isInt($user->id)) { throw new UserNotFoundException(); } // form the email $this->mailer->addTo($user->email)->addFrom('*****@*****.**', 'Clubhouse'); $this->mailer->setSubject('You\'re invited to join Clubhouse'); $this->mailer->setBody("Hi {$user->first},\nYou're invited to join Clubhouse, our group chat system.\n\n" . "Click this link to get started:\n" . url('account/invitation/' . $user->invitation . '/', FALSE, TRUE) . "\n\nThanks"); //$this->mailer->send(); }
/** * Display transcripts listing */ public function actionIndex($page) { // set the default page number if (!isset($page)) { $page = 1; } // room tabs $this->bag->tabs = $this->user->inRooms(); try { // setup new transcripts object $transcripts = new TranscriptListing($this->user->getPermissionsDbString()); } catch (TranscriptEmptyException $e) { $this->renderAction('empty'); } // are we fetching a page number in a proper range? if (!Fari_Filter::isInt($page, array(1, ceil($transcripts->count / $this->pagination)))) { $this->renderTemplate('Error404/error404'); } // fetch transcript users, files and highlighted messages $this->renderAction('listing', array(&$transcripts, $page)); }
/** * Main point of entry for text parsing. * * @param int $months The number of months to display * @param string $date "n-Y" formatted date when to start calendar * @return string HTML formatted calendar ready to echo in the View */ public static function get($months, $date = NULL) { // determine today's date if (isset($date)) { // input date separated by '-' $date = explode('-', $date); // check and use passed month if (!empty($date[0]) && Fari_Filter::isInt($date[0], array(0, 12))) { $startMonth = $date[0]; } else { $startMonth = date('n'); } // check and use passed year if (!empty($date[1]) && Fari_Filter::isInt($date[1], array(1900, 2999))) { $startYear = $date[1]; } else { $startMonth = date('n'); } } else { $startMonth = date('n'); // 0 - 12 $startYear = date('Y'); // 1984 } $result = array(); // check that the number of months to display is a positive int, default to 4 $months = $months > 0 ? $months : 4; // get us x months for ($i = 0; $i < $months; $i++) { // we are changing the year if ($startMonth + $i > 12) { $startMonth = 0; $startYear++; } $result = self::_getMonth($startMonth + $i, $startYear, $result); } return $result; }
public function edit($slug) { $slug = Fari_Escape::text($slug); // are we saving? if ($_POST) { $success = TRUE; // save categories, sources & types $category = Fari_Escape::text($_POST['category']); $categorySlug = Fari_Escape::slug($category); $source = Fari_Escape::text($_POST['source']); $sourceSlug = Fari_Escape::slug($source); $type = Fari_Escape::text($_POST['type']); $typeSlug = Fari_Escape::slug($type); if (empty($category)) { Fari_Message::fail('The category can\'t be empty.'); $success = FALSE; } else { $result = Fari_Db::selectRow('hierarchy', 'key', array('value' => $category, 'type' => 'category')); if (empty($result)) { Fari_Db::insert('hierarchy', array('value' => $category, 'slug' => $categorySlug, 'type' => 'category')); } } if (empty($source)) { Fari_Message::fail('The source can\'t be empty.'); $success = FALSE; } else { $result = Fari_Db::selectRow('hierarchy', 'key', array('value' => $source, 'type' => 'source')); if (empty($result)) { Fari_Db::insert('hierarchy', array('value' => $source, 'slug' => $sourceSlug, 'type' => 'source')); } } if (empty($type)) { Fari_Message::fail('The category can\'t be empty.'); $success = FALSE; } else { $result = Fari_Db::selectRow('hierarchy', 'key', array('value' => $type, 'type' => 'type')); if (empty($result)) { Fari_Db::insert('hierarchy', array('value' => $type, 'type' => 'type')); } } if ($success) { $text = Fari_Escape::quotes($_POST['textarea']); // convert main text to stems & add the lowercase original to it (better matches) $stems = Knowledge::stems($text) . ' ' . strtolower($text); $tags = Fari_Escape::text($_POST['tags']); $category = Fari_Escape::text($_POST['category']); $source = Fari_Escape::text($_POST['source']); $type = Fari_Escape::text($_POST['type']); $comments = Fari_Escape::text($_POST['comments']); $date = Fari_Escape::text($_POST['date']); // date if (!Fari_Filter::isDate($date)) { Fari_Message::fail('The date is not in the correct format.'); } else { // INSERT Fari_Db::update('kb', array('text' => $text, 'comments' => $comments, 'date' => $date, 'tags' => $tags, 'category' => $category, 'categorySlug' => $categorySlug, 'source' => $source, 'sourceSlug' => $sourceSlug, 'type' => $type, 'stems' => $stems), array('slug' => $slug)); Fari_Message::success('Saved successfully.'); } } } // fetch categories, sources & types $this->view->categories = $categories = Fari_Db::select('hierarchy', 'key, value', array('type' => 'category'), 'slug ASC'); $this->view->sources = $sources = Fari_Db::select('hierarchy', 'key, value', array('type' => 'source'), 'slug ASC'); $this->view->types = $types = Fari_Db::select('hierarchy', 'key, value', array('type' => 'type'), 'value ASC'); // form $saved = Fari_Db::selectRow('kb', '*', array('slug' => $slug)); $saved['textarea'] = $saved['text']; // for reuse... $this->view->saved = $saved; // get all messages $this->view->messages = Fari_Message::get(); $this->view->display('edit'); }
/** * Will set a valid page number requested for pagination and return number of pages in the query. * * @param int $requestedPage Page requested by user, can be invalid! * @param int $itemsTotal Number of items in the query result * @return int Pages total count */ private function setPageRequested($requestedPage, $itemsTotal) { // get the total number of pages we can display $pagesTotal = ceil($itemsTotal / $this->itemsPerPage); // set to first page if request invalid (not within the the min page, max page range) if (!Fari_Filter::isInt($requestedPage, array(1, $pagesTotal))) { $requestedPage = 1; } // set page requested $this->pageRequested = $requestedPage; return $pagesTotal; }
public function index($param) { // are we saving? if ($_POST) { $success = TRUE; // save categories, sources & types $category = Fari_Escape::text($_POST['category']); $categorySlug = Fari_Escape::slug($category); $source = Fari_Escape::text($_POST['source']); $sourceSlug = Fari_Escape::slug($source); $type = Fari_Escape::text($_POST['type']); $typeSlug = Fari_Escape::slug($type); if (empty($category)) { Fari_Message::fail('The category can\'t be empty.'); $success = FALSE; } else { $result = Fari_Db::selectRow('hierarchy', 'key', array('value' => $category, 'type' => 'category')); if (empty($result)) { Fari_Db::insert('hierarchy', array('value' => $category, 'slug' => $categorySlug, 'type' => 'category')); } } if (empty($source)) { Fari_Message::fail('The source can\'t be empty.'); $success = FALSE; } else { $result = Fari_Db::selectRow('hierarchy', 'key', array('value' => $source, 'type' => 'source')); if (empty($result)) { Fari_Db::insert('hierarchy', array('value' => $source, 'slug' => $sourceSlug, 'type' => 'source')); } } if (empty($type)) { Fari_Message::fail('The category can\'t be empty.'); $success = FALSE; } else { $result = Fari_Db::selectRow('hierarchy', 'key', array('value' => $type, 'type' => 'type')); if (empty($result)) { Fari_Db::insert('hierarchy', array('value' => $type, 'type' => 'type')); } } if ($success) { $title = Fari_Escape::text($_POST['title']); if (empty($title)) { Fari_Message::fail('The title can\'t be empty.'); } else { $slug = Fari_Escape::slug($_POST['title']); // unique slug/title $result = Fari_Db::selectRow('kb', 'id', array('slug' => $slug)); if (!empty($result)) { Fari_Message::fail('The title is not unique.'); } else { $text = Fari_Escape::quotes($_POST['textarea']); // convert title & main text to its stems and add lowercase originals better matches) $titleStems = Knowledge::stems($title) . ' ' . strtolower($title); $stems = Knowledge::stems($text) . ' ' . strtolower($text); $tags = Fari_Escape::text($_POST['tags']); $category = Fari_Escape::text($_POST['category']); $source = Fari_Escape::text($_POST['source']); $type = Fari_Escape::text($_POST['type']); $comments = Fari_Escape::text($_POST['comments']); $date = Fari_Escape::text($_POST['date']); // date if (!Fari_Filter::isDate($date)) { Fari_Message::fail('The date is not in the correct format.'); } else { // INSERT Fari_Db::insert('kb', array('title' => $title, 'slug' => $slug, 'text' => $text, 'tags' => $tags, 'category' => $category, 'categorySlug' => $categorySlug, 'source' => $source, 'sourceSlug' => $sourceSlug, 'type' => $type, 'stems' => $stems, 'comments' => $comments, 'date' => $date, 'titleStems' => $titleStems, 'starred' => 'empty')); Fari_Message::success('Saved successfully.'); $this->redirect('/text/edit/' . $slug); die; } } } } } // fetch categories, sources & types $this->view->categories = $categories = Fari_Db::select('hierarchy', 'key, value', array('type' => 'category'), 'slug ASC'); $this->view->sources = $sources = Fari_Db::select('hierarchy', 'key, value', array('type' => 'source'), 'slug ASC'); $this->view->types = $types = Fari_Db::select('hierarchy', 'key, value', array('type' => 'type'), 'value ASC'); // form if save failed... $this->view->saved = $_POST; // get all messages $this->view->messages = Fari_Message::get(); $this->view->display('new'); }
/** * Transforms all URLs or e-mail addresses within the string into clickable HTML links. * @param string $string email or url * @param string $ref reference to the link (optional) * @param string $type link/email (optional) */ function autoLink($string, $ref = NULL, $type = NULL) { // target reference if (!isset($ref)) { $ref = $string; } // it's an email if ($type == 'email' || Fari_Filter::isEmail($string)) { echo "<a href=\"mailto:{$string}\">{$ref}</a>"; // or a link } else { // formed URL, just echo as a link if (Fari_Filter::isURL($string)) { echo '<a href="' . $string . '">' . $ref . '</a>'; } else { // prefix with BASEPATH so we can link internally if (substr($string, 0, 1) !== '/') { $string = "/{$string}"; } echo '<a href="' . WWW_DIR . $string . '">' . $ref . '</a>'; } } }
/** * Message highlighting * * @uses Ajax */ public function actionHighlight($messageId) { if (Fari_Filter::isInt($messageId)) { $time = mktime(); $messages = new Message(); try { $result = $messages->switchHighlight($messageId); } catch (MessageNotFoundException $e) { // you mess with us... we mess with you $this->renderJson('bye'); } $this->renderJson($result); } else { $this->renderJson('bye'); } }
/** * Convert a time to distance from now. * * @param string $time A timestamp of a date (or convert into one from YYYY-MM-DD) * @return string A formatted string of a date from now, e.g.: '3 days ago' */ public static function age($time) { // convert YYYY-MM-DD into a timestamp if (Fari_Filter::isDate($time)) { list($year, $month, $day) = preg_split('/[-\\.\\/ ]/', $time); $time = mktime('1', '1', '1', $month, $day, $year); } // time now $now = time(); // the difference $difference = $now - $time; // in the past? $ago = $difference > 0 ? 1 : 0; // absolute value $difference = abs($difference); // switch case textual difference switch ($difference) { case $difference < 60: $result = 'less than a minute'; break; case $difference < 60 * 2: $result = '2 minutes'; break; case $difference < 60 * 3: $result = '3 minutes'; break; case $difference < 60 * 4: $result = '4 minutes'; break; case $difference < 60 * 5: $result = '5 minutes'; break; case $difference < 60 * 10: $result = '10 minutes'; break; case $difference < 60 * 15: $result = '15 minutes'; break; case $difference < 60 * 20: $result = '20 minutes'; break; case $difference < 60 * 25: $result = '25 minutes'; break; case $difference < 60 * 30: $result = 'half an hour'; break; case $difference < 60 * 40: $result = '40 minutes'; break; case $difference < 60 * 50: $result = '50 minutes'; break; case $difference < 60 * 60: $result = 'an hour'; break; case $difference < 60 * 60 * 24: $result = 'a day'; break; case $difference < 60 * 60 * 24 * 7: $result = 'a week'; break; case $difference < 60 * 60 * 24 * 7 * 2: $result = 'two weeks'; break; case $difference < 60 * 60 * 24 * 7 * 3: $result = 'three weeks'; break; case $difference < 60 * 60 * 24 * 30: $result = 'a month'; break; case $difference < 60 * 60 * 24 * 60: $result = 'two months'; break; case $difference < 60 * 60 * 24 * 90: $result = 'three months'; break; case $difference < 60 * 60 * 24 * 120: $result = 'four months'; break; case $difference < 60 * 60 * 24 * 182: $result = 'half a year'; break; case $difference < 60 * 60 * 24 * 365: $result = 'a year'; break; case $difference < 60 * 60 * 24 * 365 * 2: $result = 'two years'; break; case $difference < 60 * 60 * 24 * 365 * 3: $result = 'three years'; break; case $difference < 60 * 60 * 24 * 365 * 4: $result = 'four years'; break; case $difference < 60 * 60 * 24 * 365 * 5: $result = 'five years'; break; case $difference < 60 * 60 * 24 * 365 * 6: $result = 'six years'; break; case $difference < 60 * 60 * 24 * 365 * 7: $result = 'seven years'; break; case $difference < 60 * 60 * 24 * 365 * 10: $result = 'a decade'; break; case $difference < 60 * 60 * 24 * 365 * 20: $result = 'two decades'; break; case $difference < 60 * 60 * 24 * 365 * 30: $result = 'three decades'; break; case $difference < 60 * 60 * 24 * 365 * 40: $result = 'four decades'; break; case $difference < 60 * 60 * 24 * 365 * 50: $result = 'half a century'; break; case $difference < 60 * 60 * 24 * 365 * 100: $result = 'a century'; break; default: $result = 'more than a century'; break; } return $ago ? $result . ' ago' : 'in ' . $result; }
/** * Echo the SQL statement into the view * * @param string $statement SQL query string * @param array $values The values to insert, update * @param array/string $where The where clause * @return echo Query string into the view */ private static function _toString($statement, array $values = NULL, $where = NULL) { // traverse the values and where clause arrays if (is_array($where)) { $binder = 'set'; foreach (array($values, $where) as $array) { if (isset($array)) { // replace bound parametres with actual values $i = 0; foreach ($array as $value) { // determine value type of string or integer $value = Fari_Filter::isInt($value) ? "{$value}" : "'{$value}'"; // we have a variable binding key $statement = preg_replace("/:{$binder}{$i}/", $value, $statement); $i++; } } // a switch to keep track of which array are we traversing $binder = 'id'; } } // echo into the view die("<pre>{$statement}</pre>"); }
/** * Format email and name string to build an email ready header. * @param string $email Email address * @param string $name Optional name * @return string */ private function formatEmail($email, $name) { try { // check email validity if (empty($email) or !Fari_Filter::isEmail($email)) { throw new Fari_Exception("\"{$email}\" is not a valid email address."); } else { $email = "<{$email}>"; // have we provided the name? if (!empty($name)) { // only alphanumeric characters allowed if (!Fari_Filter::isAlpha($name)) { throw new Fari_Exception("\"{$name}\" needs to contain only alphanumeric characters."); } else { // prepend name before the email return '"' . $name . '" ' . $email; } } else { // add brackets around the email return $email; } } } catch (Fari_Exception $exception) { $exception->fire(); } }
/** * Leave the room */ public function actionLeave($roomId) { if (Fari_Filter::isInt($roomId)) { // are we actually in the room? if ($this->user->inRoom($roomId)) { // remove us from participants $this->user->leaveRoom($roomId); // message about it $time = mktime(); $message = new MessageSpeak($roomId, $time); $message->leave($roomId, $time, $this->user->getShortName()); // the user might be a guest in which case show her a slightly different exit message if ($this->user->isGuest()) { $this->renderAction('bye'); } } } // redir either way $this->redirectTo('/'); }
/** * Determine a type of the value. * @param <type> $value * @return <type> */ private function valueType($value) { // a file if (get_resource_type($value) == 'stream') { return PDO::PARAM_LOB; // a string or an integer } else { return Fari_Filter::isInt($value) ? PDO::PARAM_INT : PDO::PARAM_STR; } }
/** * Delete a user other than the owner * * @uses Ajax */ public function actionDelete($userId) { // is this Ajax? if ($this->request->isAjax()) { $adminUser = $this->user->getAdmin(); if (Fari_Filter::isInt($userId) && $userId != $adminUser['id']) { try { $this->accounts->deleteUser($userId); } catch (UserNotFoundException $e) { // } } } else { $this->renderTemplate('error404/javascript'); } }