Ejemplo n.º 1
0
 /**
  * Action to short links
  */
 public function shorten()
 {
     $this->setJson();
     $link = trim($_POST['link']);
     if (empty($link)) {
         $this->setError('Link can not be empty');
     }
     if (!preg_match('#^https?://.*?$#', $link)) {
         //there is no http(s)
         $link = 'http://' . $link;
     }
     $link = filter_var($link, FILTER_VALIDATE_URL);
     if (!$link) {
         $this->setError('It is not a valid url');
     }
     $modelLink = new Link();
     $linkRow = $modelLink->getOrCreateShort($link);
     $linkRow['short_link'] = $this->router->url($linkRow['short']);
     $latest = $this->getLatest();
     //set cookie
     $sids = isset($_COOKIE['shids']) ? explode(',', $_COOKIE['shids']) : array();
     $sids[] = $linkRow['id'];
     if (count($sids) > 10) {
         //there can be only 10 latest
         $sids = array_splice($sids, -10);
     }
     setcookie('shids', implode(',', $sids), time() + 7200000, '/');
     echo json_encode(['link' => $linkRow, 'latest' => $latest ? $latest : null]);
     exit;
 }