PageRenderTime 57ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/app/shortener/models/Shortener.php

https://github.com/voitto/openmicroblogger_classic
PHP | 379 lines | 274 code | 91 blank | 14 comment | 57 complexity | a7e8339472a3465b217367280fa568e5 MD5 | raw file
  1. <?php
  2. // do shortener redirect
  3. // and set memcached 301
  4. before_filter('do_shorten_redirect','find_by');
  5. class Shortener extends Model {
  6. function Shortener() {
  7. $this->char_field( 'apikey' );
  8. $this->char_field( 'nickname' );
  9. $this->char_field( 'password' );
  10. $this->char_field( 'type' );
  11. $this->int_field( 'urlcount' );
  12. $this->int_field( 'hitcount' );
  13. $this->char_field( 'urlbase' );
  14. $this->char_field( 'endpoint' );
  15. $this->time_field( 'created' );
  16. $this->time_field( 'modified' );
  17. $this->int_field( 'profile_id' );
  18. $this->int_field( 'entry_id' );
  19. $this->auto_field( 'id' );
  20. // relationships
  21. $this->has_one( 'entry' );
  22. // permissions
  23. $this->let_access( 'all:administrators' );
  24. }
  25. }
  26. function get_code($seed_length=30) {
  27. $seed = "ABCDEFGHJKLMNPQRSTUVWXYZ234567892345678923456789";
  28. $str = '';
  29. srand((double)microtime()*1000000);
  30. for ($i=0;$i<$seed_length;$i++) {
  31. $str .= substr ($seed, rand() % 48, 1);
  32. }
  33. return strtolower($str);
  34. }
  35. function do_shorten() {
  36. add_include_path(library_path().'urlshort/upload');
  37. require_once 'includes/config.php'; // settings
  38. require_once 'includes/gen.php'; // url generation and location
  39. $perma = parse_url( $_SERVER['REQUEST_URI'] );
  40. $_PERMA = explode( "/", $perma['path'] );
  41. @array_shift( $_PERMA );
  42. $shorturl = new shorturl();
  43. $msg = '';
  44. $strurl = '';
  45. global $db,$request;
  46. $Url =& $db->model('Url');
  47. global $pretty_url_base;
  48. $urlbase = $pretty_url_base;
  49. global $prefix;
  50. if (!empty($prefix)) {
  51. $sql = "SELECT urlbase FROM shorteners WHERE nickname LIKE '".$db->escape_string($request->username)."'";
  52. $sql .= " AND password LIKE '".$db->escape_string($request->password)."'";
  53. $result = $db->get_result( $sql );
  54. $url_base = $db->result_value( $result, 0, "urlbase" );
  55. if ( $db->num_rows($result) == 1 ) {
  56. $urlbase = 'http://'.$url_base;
  57. } else {
  58. trigger_error('sorry the username and password were incorrect', E_USER_ERROR);
  59. }
  60. } else {
  61. $parts = split('\.',$urlbase);
  62. if (count($parts)>2) {
  63. $urlbase = 'http://'.$parts[1].'.'.$parts[2];
  64. }
  65. }
  66. if ( defined('REWRITE') && REWRITE ) {
  67. $urlbase = $urlbase.dirname($_SERVER['PHP_SELF']);
  68. } else {
  69. $urlbase = 'http://'.$request->domain.$_SERVER['PHP_SELF'];
  70. }
  71. if ( isset($request->url) ) {
  72. $longurl = trim(mysql_escape_string($request->url));
  73. $plain = trim(mysql_escape_string($request->plain));
  74. $protocol_ok = false;
  75. if ( count($allowed_protocols) ) {
  76. foreach ( $allowed_protocols as $ap ) {
  77. if ( strtolower(substr($longurl, 0, strlen($ap))) == strtolower($ap) ) {
  78. $protocol_ok = true;
  79. break;
  80. }
  81. }
  82. } else {
  83. $protocol_ok = true;
  84. }
  85. $protocol_ok = true;
  86. $plaincheck = check_plain($plain);
  87. // url Required The destination URL to be shortened.
  88. // custom Optional A custom URL that is preferred to an auto-generated URL.
  89. // searchtags Optional A search string value to attach to a tr.im URL.
  90. // privacycode Optional A string value that must be appended after the URL.
  91. // newtrim Optional If present with any value, it will force the creation of a new tr.im URL.
  92. // sandbox Optional If present with any value a test data set will be returned, and no URL created. This is intended for testing so that you do not consume API calls or insert pointless data while in development.
  93. // api_key Optional An application API key assigned to your application.
  94. // username Optional A tr.im username that you would like to attach the URL to.
  95. // password Optional The password for the tr.im username referenced above.
  96. // if the id has been sent to this script
  97. if ( isset($request->custom) && strlen(trim($request->custom)) ){
  98. $shorten = trim(mysql_escape_string($request->custom));
  99. $string = "$shorten";
  100. list($string1,$string2) = explode("$install_path",$string);
  101. $shortid = $string1.$string2;
  102. $q2 = 'SELECT url FROM `urls` WHERE `id` LIKE CONVERT(_utf8 \''.$shortid.'\' USING latin1)';
  103. $result2 = mysql_query($q2);
  104. while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
  105. printf($row["url"]);
  106. exit();
  107. }
  108. if ( mysql_num_rows( $result2 ) == $result2 ) {
  109. $longurl = mysql_result($result2, 1);
  110. }
  111. else{
  112. header('HTTP/1.1 500 Internal Server Error');
  113. exit;
  114. }
  115. }
  116. $make_new_url = true;
  117. $q2 = 'SELECT id FROM '.URL_TABLE.' WHERE (url="'.$longurl.'")';
  118. $result2 = mysql_query($q2);
  119. if ( mysql_num_rows( $result2 ))
  120. $make_new_url = false;
  121. if (isset($request->searchtags))
  122. $longurl .= $request->searchtags;
  123. if (isset($request->privacycode))
  124. $longurl .= $request->privacycode;
  125. if (isset($request->newtrim))
  126. $make_new_url = true;
  127. if ($protocol_ok && $plaincheck){
  128. if (isset($request->sandbox)) {
  129. $trimresponse = array(
  130. 'trimpath'=>'w92s',
  131. 'reference'=>'lsTZf8vHaslrrmskREhbRArpHh125c',
  132. 'trimmed'=>'10/08/2009',
  133. 'destination'=>"http://www.google.com/",
  134. 'trim_path'=>'w92S',
  135. 'domain'=>'google.com',
  136. 'url'=>'http://tr.im/w92S',
  137. 'visits'=>0,
  138. 'status'=>array(
  139. 'result'=>'OK',
  140. 'code'=>'200',
  141. 'message'=>'tr.im URL Added.'
  142. ),
  143. 'date_time'=>'2009/08/10 05:46:13 -0400'
  144. );
  145. $time_of = time();
  146. $responsetype = $request->client_wants;
  147. $trimpath = $trimresponse['trimpath'];
  148. $reference = $trimresponse['reference'];
  149. $trimmed = $trimresponse['trimmed'];
  150. $destination = $trimresponse['destination'];
  151. $trim_path = $trimresponse['trim_path'];
  152. $domain = $trimresponse['domain'];
  153. $strurl = $trimresponse['url'];
  154. $visits = 0;
  155. $status_result = 'OK';
  156. $status_code = '200';
  157. $date_time = $trimresponse['date_time'];
  158. } else {
  159. $shorturl->add_url($longurl, $plain);
  160. if ( defined('REWRITE') && REWRITE ) {
  161. $strurl = $urlbase.''.$shorturl->get_id($longurl);
  162. } else {
  163. $strurl = $urlbase.'?id='.$shorturl->get_id($longurl);
  164. }
  165. $time_of = time() - (3 * 60 * 60);
  166. $responsetype = $request->client_wants;
  167. $id = $shorturl->get_id($longurl);
  168. $trimpath = $id;
  169. $reference = get_code();
  170. $trimmed = date("d/m/Y",$time_of);
  171. $destination = $longurl;
  172. $trim_path = $id;
  173. $url_parts = @parse_url( $longurl );
  174. $domain = $url_parts["host"];
  175. $visits = 0;
  176. $status_result = 'OK';
  177. $status_code = '200';
  178. $date_time = date("Y/m/d H:i:s O",$time_of);
  179. $l = $Url->find_by(array('id'=>$id));
  180. if ($make_new_url) {
  181. $l->set_value('text',$plain);
  182. $l->set_value('title',$plain);
  183. $l->set_value('trimurl',$strurl);
  184. $l->set_value('created',date("Y-m-d H:i:s",$time_of));
  185. $l->set_value('date',date("Y-m-d H:i:s",$time_of));
  186. $l->set_value('trimpath',$trimpath);
  187. $l->set_value('trimref',$reference);
  188. $l->set_value('trimmed',$trimmed);
  189. $l->set_value('trimvisits',$visits);
  190. $l->set_value('trimtime',$date_time);
  191. $l->save_changes();
  192. } else {
  193. $reference = $l->reference;
  194. $trimpath = $l->trimpath;
  195. $reference = $l->trimref;
  196. $trimmed = $l->trimmed;
  197. $trimpath = $l->trimpath;
  198. $trim_path = $l->trimpath;
  199. $visits = $l->trimvisits;
  200. $date_time = $l->trimtime;
  201. $l->set_value('trimvisits',$l->trimvisits + 1);
  202. $l->save_changes();
  203. }
  204. }
  205. $arr = array('destination','url','trimmed');
  206. if ($responsetype == 'json')
  207. foreach( $arr as $var)
  208. $$var = str_replace('/', '\/', $$var);
  209. if (substr($longurl,-strlen($domain)) == $domain)
  210. $destination .= '\/';
  211. $callback1 = '';
  212. $callback2 = '';
  213. if (isset($request->callback)) {
  214. $callback1 = $request->callback.'(';
  215. $callback2 = ')';
  216. }
  217. if ($responsetype == 'json') {
  218. header( 'Content-Type: application/json' );
  219. header( "Content-Disposition: inline" );
  220. }
  221. if ($responsetype == 'xml') echo '<?xml version="1.0" encoding="UTF-8"?>
  222. <trim>
  223. <status result="OK" code="200" message="tr.im URL Added."/>
  224. <url>'.$strurl.'</url>
  225. <reference>'.$reference.'</reference>
  226. <trimpath>'.$trimpath.'</trimpath>
  227. </trim>';
  228. if ($responsetype == 'json') echo $callback1.'{"trimpath": "'.$trimpath.'", "reference": "'.$reference.'", "trimmed": "'.$trimmed.'", "destination": "'.$destination.'", "trim_path": "'.$trim_path.'", "domain": "'.$domain.'", "url": "'.$strurl.'", "visits": '.$visits.', "status": {"result": "'.$status_result.'", "code": "'.$status_code.'", "message": "tr.im URL Added."}, "date_time": "'.$date_time.'"}'.$callback2;
  229. }
  230. $redircode = '<html>
  231. <head>
  232. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  233. <title></title>
  234. <META HTTP-EQUIV="Refresh" CONTENT="0;URL='.stripslashes($destination).'">
  235. <meta name="robots" content="noindex"/>
  236. <link rel="canonical" href="'.stripslashes($destination).'"/>
  237. </head>
  238. <body>
  239. </body>
  240. </html>';
  241. $make_s3 = false;
  242. if ($url_base && $make_s3) {
  243. $redirfile = tempnam( "/tmp", $url_base.'/'.$trimpath );
  244. $handle = fopen($redirfile, "w");
  245. fwrite($handle, $redircode);
  246. fclose($handle);
  247. lib_include( 'S3' );
  248. $s3 = new S3( environment('awsAccessKey'), environment('awsSecretKey') );
  249. if ($s3) {
  250. $s3->getBucket($url_base);
  251. $s3->putObjectFile( $redirfile , $url_base, $trimpath, 'public-read' );
  252. }
  253. }
  254. }
  255. exit;
  256. }
  257. function do_shorten_redirect(&$model,&$model) {
  258. global $request;
  259. if (!($model->table == 'settings'))
  260. return;
  261. if (!pretty_urls()) return;
  262. $perma = parse_url( $_SERVER['REQUEST_URI'] );
  263. $_PERMA = explode( "/", $perma['path'] );
  264. @array_shift( $_PERMA );
  265. if ( isset($_PERMA[0]) )
  266. $id = mysql_escape_string($_PERMA[0]);
  267. else
  268. $id = '';
  269. if ( $id != '' && $id != basename($_SERVER['PHP_SELF']) ){
  270. add_include_path(library_path().'urlshort/upload');
  271. require_once 'includes/config.php'; // settings
  272. require_once 'includes/gen.php'; // url generation and location
  273. $url = new shorturl();
  274. $location = $url->get_url($id);
  275. if ( $location != -1 ) {
  276. include 'db/library/pca/pca.class.php';
  277. $cache = PCA::get_best_backend();
  278. $timeout = 86400;
  279. $cache->add($_SERVER['REQUEST_URI'], $location, $timeout);
  280. header('Location: '.$location, TRUE, 301);
  281. exit;
  282. }
  283. }
  284. }