1 | <?php |
||
11 | class ShortList extends DataObject |
||
12 | { |
||
13 | |||
14 | /** |
||
|
|||
15 | * Fields. |
||
16 | */ |
||
17 | private static $db = array( |
||
18 | 'SessionID' => 'varchar(64)', |
||
19 | 'URL' => 'Varchar(255)', |
||
20 | 'UserAgent' => 'Varchar(512)' |
||
21 | ); |
||
22 | |||
23 | /** |
||
24 | * Attaches to many items. |
||
25 | */ |
||
26 | private static $has_many = array( |
||
27 | 'ShortListItems' => 'ShortListItem' |
||
28 | ); |
||
29 | |||
30 | /** |
||
31 | * Where the URL is unique. |
||
32 | */ |
||
33 | private static $indexes = array( |
||
34 | 'UniqueURL' => array( |
||
35 | 'type' => 'unique', |
||
36 | 'value' => 'URL' |
||
37 | ) |
||
38 | ); |
||
39 | |||
40 | /** |
||
41 | * Ensure we populate these fields before a save. |
||
42 | */ |
||
43 | public function onBeforeWrite() |
||
44 | { |
||
45 | |||
46 | // Run other beforewrites first. |
||
47 | parent::onBeforeWrite(); |
||
48 | |||
49 | // if (!$this->isBrowser()) { |
||
50 | // return false; |
||
51 | // } |
||
52 | |||
53 | // If this is the first save... |
||
54 | if (!$this->isInDB()) { |
||
55 | // Ensure the session exists before querying it. |
||
56 | if (!Session::request_contains_session_id()) { |
||
57 | Session::start(); |
||
58 | } |
||
59 | |||
60 | // Store the sesion and in the database. |
||
61 | $this->SessionID = SecurityToken::inst()->getValue(); |
||
62 | |||
63 | if (is_null($this->SessionID)) { |
||
64 | return false; |
||
65 | } |
||
66 | |||
67 | $gen = new RandomGenerator(); |
||
68 | $uniqueurl = substr($gen->randomToken(), 0, 32); |
||
69 | |||
70 | while (ShortList::get()->filter('URL', $uniqueurl)->count() > 0) { |
||
71 | $uniqueurl = substr($gen->randomToken(), 0, 32); |
||
72 | } |
||
73 | |||
74 | $this->URL = $uniqueurl; |
||
75 | $this->UserAgent = Controller::curr()->getRequest()->getHeader('User-Agent'); |
||
76 | } |
||
77 | } |
||
78 | |||
79 | /** |
||
80 | * All URLs are prefixed with URLSegment from config. |
||
81 | */ |
||
82 | public function Link($action = null) |
||
86 | |||
87 | /** |
||
88 | * A basic browser detection. |
||
89 | * * if a browser is not here - assume it's a crawler or a bot. In which case, it shouldn't create a shortlist. |
||
90 | * |
||
91 | * @see http://stackoverflow.com/a/1537636 |
||
92 | * */ |
||
93 | public static function isBrowser() |
||
102 | } |
||
103 |