Ejemplo n.º 1
0
 function destroy($args, $apidata)
 {
     parent::handle($args);
     if (!in_array($_SERVER['REQUEST_METHOD'], array('POST', 'DELETE'))) {
         $this->clientError(_('This method requires a POST or DELETE.'), 400, $apidata['content-type']);
         return;
     }
     $id = $apidata['api_arg'];
     # We can't subscribe to a remote person, but we can unsub
     $other = $this->get_profile($id);
     $user = $apidata['user'];
     $sub = new Subscription();
     $sub->subscriber = $user->id;
     $sub->subscribed = $other->id;
     if ($sub->find(true)) {
         $sub->query('BEGIN');
         $sub->delete();
         $sub->query('COMMIT');
     } else {
         $this->clientError(_('You are not friends with the specified user.'), 403, $apidata['content-type']);
         return;
     }
     $type = $apidata['content-type'];
     $this->init_document($type);
     $this->show_profile($other, $type);
     $this->end_document($type);
 }
Ejemplo n.º 2
0
 private function dataExist($id)
 {
     $data = Subscription::find($id);
     if (!$data) {
         return Redirect::route('subscription_list')->with('mError', 'Cet abonnement est introuvable !');
     } else {
         return $data;
     }
 }
Ejemplo n.º 3
0
 function getSubscribers()
 {
     $subs = array();
     $sub = new Subscription();
     $sub->subscribed = $this->user->id;
     if ($sub->find()) {
         while ($sub->fetch()) {
             if ($sub->subscriber != $this->user->id) {
                 $subs[] = clone $sub;
             }
         }
     }
     return $subs;
 }
Ejemplo n.º 4
0
 function view($id = FALSE)
 {
     $this->view_data['submenu'] = array($this->lang->line('application_back') => 'subscriptions');
     $this->view_data['subscription'] = Subscription::find($id);
     $this->view_data['items'] = SubscriptionHasItem::find('all', array('conditions' => array('subscription_id=?', $id)));
     if ($this->view_data['subscription']->company_id != $this->client->company->id) {
         redirect('csubscriptions');
     }
     $datediff = strtotime($this->view_data['subscription']->end_date) - strtotime($this->view_data['subscription']->issue_date);
     $timespan = floor($datediff / (60 * 60 * 24));
     switch ($this->view_data['subscription']->frequency) {
         case '+7 day':
             $this->view_data['run_time'] = round($timespan / 7);
             $this->view_data['p3'] = "1";
             $this->view_data['t3'] = "W";
             break;
         case '+14 day':
             $this->view_data['run_time'] = round($timespan / 14);
             $this->view_data['p3'] = "2";
             $this->view_data['t3'] = "W";
             break;
         case '+1 month':
             $this->view_data['run_time'] = round($timespan / 30);
             $this->view_data['p3'] = "1";
             $this->view_data['t3'] = "M";
             break;
         case '+3 month':
             $this->view_data['run_time'] = round($timespan / 90);
             $this->view_data['p3'] = "3";
             $this->view_data['t3'] = "M";
             break;
         case '+6 month':
             $this->view_data['run_time'] = round($timespan / 182);
             $this->view_data['p3'] = "6";
             $this->view_data['t3'] = "M";
             break;
         case '+1 year':
             $this->view_data['run_time'] = round($timespan / 365);
             $this->view_data['p3'] = "1";
             $this->view_data['t3'] = "Y";
             break;
     }
     $this->content_view = 'subscriptions/client_views/view';
 }
Ejemplo n.º 5
0
 function count_subscriptions($profile)
 {
     $count = 0;
     $sub = new Subscription();
     $sub->subscribed = $profile->id;
     $count = $sub->find();
     if ($count > 0) {
         return $count - 1;
     } else {
         return 0;
     }
 }
 function validateOmb()
 {
     $listener = $_GET['omb_listener'];
     $listenee = $_GET['omb_listenee'];
     $nickname = $_GET['omb_listenee_nickname'];
     $profile = $_GET['omb_listenee_profile'];
     $user = User::staticGet('uri', $listener);
     if (!$user) {
         // TRANS: Exception thrown when no valid user is found for an authorisation request.
         // TRANS: %s is a listener URI.
         throw new Exception(sprintf(_('Listener URI "%s" not found here.'), $listener));
     }
     if (strlen($listenee) > 255) {
         // TRANS: Exception thrown when listenee URI is too long for an authorisation request.
         // TRANS: %s is a listenee URI.
         throw new Exception(sprintf(_('Listenee URI "%s" is too long.'), $listenee));
     }
     $other = User::staticGet('uri', $listenee);
     if ($other) {
         // TRANS: Exception thrown when listenee URI is a local user for an authorisation request.
         // TRANS: %s is a listenee URI.
         throw new Exception(sprintf(_('Listenee URI "%s" is a local user.'), $listenee));
     }
     $remote = Remote_profile::staticGet('uri', $listenee);
     if ($remote) {
         $sub = new Subscription();
         $sub->subscriber = $user->id;
         $sub->subscribed = $remote->id;
         if ($sub->find(true)) {
             // TRANS: Exception thrown when already subscribed.
             throw new Exception('You are already subscribed to this user.');
         }
     }
     if ($profile == common_profile_url($nickname)) {
         // TRANS: Exception thrown when profile URL is a local user for an authorisation request.
         // TRANS: %s is a profile URL.
         throw new Exception(sprintf(_('Profile URL "%s" is for a local user.'), $profile));
     }
     $license = $_GET['omb_listenee_license'];
     $site_license = common_config('license', 'url');
     if (!common_compatible_license($license, $site_license)) {
         // TRANS: Exception thrown when licenses are not compatible for an authorisation request.
         // TRANS: %1$s is the license for the listenee, %2$s is the license for "this" StatusNet site.
         throw new Exception(sprintf(_('Listenee stream license "%1$s" is not ' . 'compatible with site license "%2$s".'), $license, $site_license));
     }
     $avatar = $_GET['omb_listenee_avatar'];
     if ($avatar) {
         if (!common_valid_http_url($avatar) || strlen($avatar) > 255) {
             // TRANS: Exception thrown when avatar URL is invalid for an authorisation request.
             // TRANS: %s is an avatar URL.
             throw new Exception(sprintf(_('Avatar URL "%s" is not valid.'), $avatar));
         }
         $size = @getimagesize($avatar);
         if (!$size) {
             // TRANS: Exception thrown when avatar URL could not be read for an authorisation request.
             // TRANS: %s is an avatar URL.
             throw new Exception(sprintf(_('Cannot read avatar URL "%s".'), $avatar));
         }
         if (!in_array($size[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
             // TRANS: Exception thrown when avatar URL return an invalid image type for an authorisation request.
             // TRANS: %s is an avatar URL.
             throw new Exception(sprintf(_('Wrong image type for avatar URL ' . '"%s".'), $avatar));
         }
     }
 }
Ejemplo n.º 7
0
 function handle($args)
 {
     parent::handle($args);
     header('Content-Type: application/rdf+xml');
     $this->startXML();
     $this->elementStart('rdf:RDF', array('xmlns:rdf' => 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'xmlns:rdfs' => 'http://www.w3.org/2000/01/rdf-schema#', 'xmlns:geo' => 'http://www.w3.org/2003/01/geo/wgs84_pos#', 'xmlns' => 'http://xmlns.com/foaf/0.1/'));
     // This is the document about the user
     $this->showPpd('', $this->user->uri);
     // XXX: might not be a person
     $this->elementStart('Person', array('rdf:about' => $this->user->uri));
     $this->element('mbox_sha1sum', null, sha1('mailto:' . $this->user->email));
     if ($this->profile->fullname) {
         $this->element('name', null, $this->profile->fullname);
     }
     if ($this->profile->homepage) {
         $this->element('homepage', array('rdf:resource' => $this->profile->homepage));
     }
     if ($this->profile->bio) {
         $this->element('rdfs:comment', null, $this->profile->bio);
     }
     // XXX: more structured location data
     if ($this->profile->location) {
         $this->elementStart('based_near');
         $this->elementStart('geo:SpatialThing');
         $this->element('name', null, $this->profile->location);
         $this->elementEnd('geo:SpatialThing');
         $this->elementEnd('based_near');
     }
     $this->showMicrobloggingAccount($this->profile, common_root_url());
     $avatar = $this->profile->getOriginalAvatar();
     if ($avatar) {
         $this->elementStart('img');
         $this->elementStart('Image', array('rdf:about' => $avatar->url));
         foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
             $scaled = $this->profile->getAvatar($size);
             if (!$scaled->original) {
                 // sometimes the original has one of our scaled sizes
                 $this->elementStart('thumbnail');
                 $this->element('Image', array('rdf:about' => $scaled->url));
                 $this->elementEnd('thumbnail');
             }
         }
         $this->elementEnd('Image');
         $this->elementEnd('img');
     }
     // Get people user is subscribed to
     $person = array();
     $sub = new Subscription();
     $sub->subscriber = $this->profile->id;
     $sub->whereAdd('subscriber != subscribed');
     if ($sub->find()) {
         while ($sub->fetch()) {
             if ($sub->token) {
                 $other = Remote_profile::staticGet('id', $sub->subscribed);
             } else {
                 $other = User::staticGet('id', $sub->subscribed);
             }
             if (!$other) {
                 common_debug('Got a bad subscription: ' . print_r($sub, true));
                 continue;
             }
             $this->element('knows', array('rdf:resource' => $other->uri));
             $person[$other->uri] = array(LISTENEE, $other);
         }
     }
     // Get people who subscribe to user
     $sub = new Subscription();
     $sub->subscribed = $this->profile->id;
     $sub->whereAdd('subscriber != subscribed');
     if ($sub->find()) {
         while ($sub->fetch()) {
             if ($sub->token) {
                 $other = Remote_profile::staticGet('id', $sub->subscriber);
             } else {
                 $other = User::staticGet('id', $sub->subscriber);
             }
             if (!$other) {
                 common_debug('Got a bad subscription: ' . print_r($sub, true));
                 continue;
             }
             if (array_key_exists($other->uri, $person)) {
                 $person[$other->uri][0] = BOTH;
             } else {
                 $person[$other->uri] = array(LISTENER, $other);
             }
         }
     }
     $this->elementEnd('Person');
     foreach ($person as $uri => $p) {
         $foaf_url = null;
         if ($p[1] instanceof User) {
             $foaf_url = common_local_url('foaf', array('nickname' => $p[1]->nickname));
         }
         $this->profile = Profile::staticGet($p[1]->id);
         $this->elementStart('Person', array('rdf:about' => $uri));
         if ($p[0] == LISTENER || $p[0] == BOTH) {
             $this->element('knows', array('rdf:resource' => $this->user->uri));
         }
         $this->showMicrobloggingAccount($this->profile, $p[1] instanceof User ? common_root_url() : null);
         if ($foaf_url) {
             $this->element('rdfs:seeAlso', array('rdf:resource' => $foaf_url));
         }
         $this->elementEnd('Person');
         if ($foaf_url) {
             $this->showPpd($foaf_url, $uri);
         }
     }
     $this->elementEnd('rdf:RDF');
     $this->endXML();
 }
Ejemplo n.º 8
0
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/pdf', function () {
    $data['user'] = User::find(11);
    $data['subscription'] = Subscription::find(10);
    $data['payment'] = Payment::find(34);
    //$pdf = PDF::loadView('docs.faktura', $data);
    return View::make('docs.faktura', $data);
    //return $pdf->stream();
});
//sitewide
Route::get('/', array('uses' => 'HomeController@showHome'));
Route::get('/informacje', array('uses' => 'HomeController@showAboutUs'));
//Route::get('/faq', array('uses' =>'HomeController@showFaq'));
Route::get('/kontakt', array('uses' => 'HomeController@showContact'));
Route::get('/regulamin', array('uses' => 'HomeController@showLegal'));
//Route::get('/oferta', array('uses' =>'HomeController@showPricing'));
Route::post('/contact/send', array('uses' => 'HomeController@postContactForm'));
Route::get('/robots.txt', array('uses' => 'HomeController@generateRobots'));
Route::get('/sitemap.xml', array('uses' => 'HomeController@generateSitemap'));
// auth
Ejemplo n.º 9
0
 /**
  * Get the Nth most recent subscription for this user
  *
  * @param User    $user The user to get subscriptions for
  * @param integer $n    How far to count back
  *
  * @return Subscription a subscription or null
  */
 private function _getNthSub($user, $n)
 {
     $sub = new Subscription();
     $sub->subscriber = $user->id;
     $sub->orderBy('created DESC');
     $sub->limit($n - 1, 1);
     if ($sub->find(true)) {
         return $sub;
     } else {
         return null;
     }
 }
Ejemplo n.º 10
0
 function getSubscribers()
 {
     $subs = array();
     $sub = new Subscription();
     $sub->subscribed = $this->user->id;
     if (!empty($this->after)) {
         $sub->whereAdd("created > '" . common_sql_date($this->after) . "'");
     }
     if ($sub->find()) {
         while ($sub->fetch()) {
             if ($sub->subscriber != $this->user->id) {
                 $subs[] = clone $sub;
             }
         }
     }
     return $subs;
 }
Ejemplo n.º 11
0
 function _deleteSubscriptions()
 {
     $sub = new Subscription();
     $sub->subscriber = $this->getID();
     $sub->find();
     while ($sub->fetch()) {
         try {
             $other = $sub->getSubscribed();
             if (!$other->sameAs($this)) {
                 Subscription::cancel($this, $other);
             }
         } catch (NoResultException $e) {
             // Profile not found
             common_log(LOG_INFO, 'Subscribed profile id==' . $sub->subscribed . ' not found when deleting profile id==' . $this->getID() . ', ignoring...');
         } catch (ServerException $e) {
             // Subscription cancel failed
             common_log(LOG_INFO, 'Subscribed profile id==' . $other->getID() . ' could not be reached for unsubscription notice when deleting profile id==' . $this->getID() . ', ignoring...');
         }
     }
     $sub = new Subscription();
     $sub->subscribed = $this->getID();
     $sub->find();
     while ($sub->fetch()) {
         try {
             $other = $sub->getSubscriber();
             common_log(LOG_INFO, 'Subscriber profile id==' . $sub->subscribed . ' not found when deleting profile id==' . $this->getID() . ', ignoring...');
             if (!$other->sameAs($this)) {
                 Subscription::cancel($other, $this);
             }
         } catch (NoResultException $e) {
             // Profile not found
             common_log(LOG_INFO, 'Subscribed profile id==' . $sub->subscribed . ' not found when deleting profile id==' . $this->getID() . ', ignoring...');
         } catch (ServerException $e) {
             // Subscription cancel failed
             common_log(LOG_INFO, 'Subscriber profile id==' . $other->getID() . ' could not be reached for unsubscription notice when deleting profile id==' . $this->getID() . ', ignoring...');
         }
     }
     // Finally delete self-subscription
     $self = new Subscription();
     $self->subscriber = $this->getID();
     $self->subscribed = $this->getID();
     $self->delete();
 }
Ejemplo n.º 12
0
 function index()
 {
     $this->theme_view = 'blank';
     $this->load->helper(array('dompdf', 'file'));
     $timestamp = time();
     $core_settings = Setting::first();
     $date = date("Y-m-d");
     if ($core_settings->cronjob == "1" && time() > $core_settings->last_cronjob + 300) {
         $core_settings->last_cronjob = time();
         $core_settings->save();
         $this->load->database();
         //Check Subscriptions
         $sql = 'SELECT * FROM subscriptions WHERE status != "Inactive" AND end_date > "' . $date . '" AND "' . $date . '" >= next_payment ORDER BY next_payment';
         $res = $this->db->query($sql);
         $res = $res->result();
         foreach ($res as $key2 => $value2) {
             $eventline = 'New invoice created for subscription <a href="' . base_url() . 'subscriptions/view/' . $value2->id . '">#' . $value2->reference . '</a>';
             $subscription = Subscription::find($value2->id);
             $invoice = Invoice::last();
             $invoice_reference = Setting::first();
             if ($subscription) {
                 $_POST['subscription_id'] = $subscription->id;
                 $_POST['company_id'] = $subscription->company_id;
                 if ($subscription->subscribed != 0) {
                     $_POST['status'] = "Paid";
                 } else {
                     $_POST['status'] = "Open";
                 }
                 $_POST['currency'] = $subscription->currency;
                 $_POST['issue_date'] = $subscription->next_payment;
                 $_POST['due_date'] = date('Y-m-d', strtotime('+3 day', strtotime($subscription->next_payment)));
                 $_POST['currency'] = $subscription->currency;
                 $_POST['terms'] = $subscription->terms;
                 $_POST['discount'] = $subscription->discount;
                 $_POST['reference'] = $invoice_reference->invoice_reference;
                 $invoice = Invoice::create($_POST);
                 $invoiceid = Invoice::last();
                 $items = SubscriptionHasItem::find('all', array('conditions' => array('subscription_id=?', $value2->id)));
                 foreach ($items as $value) {
                     $itemvalues = array('invoice_id' => $invoiceid->id, 'item_id' => $value->item_id, 'amount' => $value->amount, 'description' => $value->description, 'value' => $value->value, 'name' => $value->name, 'type' => $value->type);
                     InvoiceHasItem::create($itemvalues);
                 }
                 $invoice_reference->update_attributes(array('invoice_reference' => $invoice_reference->invoice_reference + 1));
                 if ($invoice) {
                     $subscription->next_payment = date('Y-m-d', strtotime($subscription->frequency, strtotime($subscription->next_payment)));
                     $subscription->save();
                     //Send Invoice to Client via email
                     $this->load->library('parser');
                     $data["invoice"] = Invoice::find($invoiceid->id);
                     $data['items'] = InvoiceHasItem::find('all', array('conditions' => array('invoice_id=?', $invoiceid->id)));
                     $data["core_settings"] = Setting::first();
                     // Generate PDF
                     $html = $this->load->view($data["core_settings"]->template . '/' . 'invoices/preview', $data, true);
                     $filename = $this->lang->line('application_invoice') . '_' . $data["invoice"]->reference;
                     pdf_create($html, $filename, FALSE);
                     //email
                     $this->email->from($data["core_settings"]->email, $data["core_settings"]->company);
                     $this->email->to($data["invoice"]->company->client->email);
                     $this->email->subject($data["core_settings"]->invoice_mail_subject);
                     $this->email->attach("files/temp/" . $filename . ".pdf");
                     $due_date = date($data["core_settings"]->date_format, human_to_unix($data["invoice"]->due_date . ' 00:00:00'));
                     //Set parse values
                     $parse_data = array('client_contact' => $data["invoice"]->company->client->firstname . ' ' . $data["invoice"]->company->client->lastname, 'due_date' => $due_date, 'invoice_id' => $data["invoice"]->reference, 'client_link' => $data["core_settings"]->domain, 'company' => $data["core_settings"]->company, 'logo' => '<img src="' . base_url() . '' . $data["core_settings"]->logo . '" alt="' . $data["core_settings"]->company . '"/>', 'invoice_logo' => '<img src="' . base_url() . '' . $data["core_settings"]->invoice_logo . '" alt="' . $data["core_settings"]->company . '"/>');
                     $email_invoice = read_file('./application/views/' . $data["core_settings"]->template . '/templates/email_invoice.html');
                     $message = $this->parser->parse_string($email_invoice, $parse_data);
                     $this->email->message($message);
                     if ($this->email->send()) {
                         $data["invoice"]->update_attributes(array('status' => 'Sent', 'sent_date' => date("Y-m-d")));
                     }
                     log_message('error', $eventline);
                     unlink("files/temp/" . $filename . ".pdf");
                 }
             }
         }
         //Check Subscriptions end
         // Auto Backup every 7 days
         if ($core_settings->autobackup == "1" && time() > $core_settings->last_autobackup + 7 * 24 * 60 * 60) {
             $this->load->dbutil();
             $prefs = array('format' => 'zip', 'filename' => 'Database-auto-full-backup_' . date('Y-m-d_H-i'));
             $backup =& $this->dbutil->backup($prefs);
             if (!write_file('./files/backup/Database-auto-full-backup_' . date('Y-m-d_H-i') . '.zip', $backup)) {
                 log_message('error', "Error while creating auto database backup!");
             } else {
                 $core_settings->last_autobackup = time();
                 $core_settings->save();
                 log_message('error', "Auto backup has been created.");
             }
         }
         echo "Success";
     }
 }
Ejemplo n.º 13
0
function omb_broadcast_profile($profile)
{
    # First, get remote users subscribed to this profile
    # XXX: use a join here rather than looping through results
    $sub = new Subscription();
    $sub->subscribed = $profile->id;
    if ($sub->find()) {
        $updated = array();
        while ($sub->fetch()) {
            $rp = Remote_profile::staticGet('id', $sub->subscriber);
            if ($rp) {
                if (!array_key_exists($rp->updateprofileurl, $updated)) {
                    if (omb_update_profile($profile, $rp, $sub)) {
                        $updated[$rp->updateprofileurl] = true;
                    }
                }
            }
        }
    }
}
Ejemplo n.º 14
0
 /**
  * [postRenewalSubscriptionData]
  * @return [json] [DT compatible object]
  */
 public function postNieuwsbrievenSubscriptionData()
 {
     $posted_values = $_POST['data']['subscriptions'];
     $posted_p = var_export($_POST, true);
     error_log($posted_p);
     //error_log($posted_ndx);
     $curr_company = Company::find((int) $posted_values["company_id"]);
     $subscription = Subscription::find((int) $posted_values["id"]);
     $curr_aws_account = $posted_values["aws_auth"];
     if ($curr_company && $subscription) {
         $aws_auth = CompanyMeta::firstOrNew(['company_id' => $curr_company->id, 'type' => 'aws', 'subtype' => 'auth', 'key' => 'account']);
         $aws_auth->value = $curr_aws_account;
         $aws_auth->save();
         // load relations
         $load_curr_company = $subscription->company;
         $load_curr_service = $subscription->service;
         $load_curr_category = $subscription->service->category;
         $load_curr_status = $subscription->status;
         $load_curr_period = $subscription->period;
         $curr_company = $subscription->company !== NULL ? (object) ['id' => $subscription->company_id, 'bedrijfsnaam' => utf8_encode($subscription->company->bedrijfsnaam)] : (object) null;
         $curr_service = $subscription->service !== NULL ? (object) ['id' => $subscription->service_id, 'category_id' => $subscription->category_id, 'name' => utf8_encode($subscription->service->name)] : (object) null;
         $curr_category = $subscription->service->category !== NULL ? (object) ['id' => $subscription->service->category_id, 'name' => utf8_encode($subscription->service->category->name)] : (object) null;
         $curr_status = $subscription->status !== NULL ? (object) ['id' => $subscription->status_id, 'description' => utf8_encode($subscription->status->description)] : (object) null;
         $curr_period = $subscription->period !== NULL ? (object) ['id' => $subscription->invoice_periods_id, 'description' => utf8_encode($subscription->period->description)] : (object) null;
         $data = (object) ['DT_RowId' => 'row_' . $subscription->id, 'subscriptions' => $subscription, 'companies' => $curr_company, 'service_categories' => $curr_category, 'services' => $curr_service, 'statuses' => $curr_status, 'invoice_periods' => $curr_period];
         $ret = ['row' => $data, 'companies' => $this->getAllCompanies(), 'services' => $this->getAllServices(), 'service_categories' => $this->getAllServiceCategories(), 'statuses' => $this->getAllStatuses(), 'invoice_periods' => $this->getAllInvoicePeriods()];
         return Response::json($ret);
     }
     return Response::json((object) null);
 }
Ejemplo n.º 15
0
 function update_profile($req, $consumer, $token)
 {
     $version = $req->get_parameter('omb_version');
     if ($version != OMB_VERSION_01) {
         $this->clientError(_('Unsupported OMB version'), 400);
         return false;
     }
     # First, check to see if listenee exists
     $listenee = $req->get_parameter('omb_listenee');
     $remote = Remote_profile::staticGet('uri', $listenee);
     if (!$remote) {
         $this->clientError(_('Profile unknown'), 404);
         return false;
     }
     # Second, check to see if they should be able to post updates!
     # We see if there are any subscriptions to that remote user with
     # the given token.
     $sub = new Subscription();
     $sub->subscribed = $remote->id;
     $sub->token = $token->key;
     if (!$sub->find(true)) {
         $this->clientError(_('You did not send us that profile'), 403);
         return false;
     }
     $profile = Profile::staticGet('id', $remote->id);
     if (!$profile) {
         # This one is our fault
         $this->serverError(_('Remote profile with no matching profile'), 500);
         return false;
     }
     $nickname = $req->get_parameter('omb_listenee_nickname');
     if ($nickname && !Validate::string($nickname, array('min_length' => 1, 'max_length' => 64, 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
         $this->clientError(_('Nickname must have only lowercase letters and numbers and no spaces.'));
         return false;
     }
     $license = $req->get_parameter('omb_listenee_license');
     if ($license && !common_valid_http_url($license)) {
         $this->clientError(sprintf(_("Invalid license URL '%s'"), $license));
         return false;
     }
     $profile_url = $req->get_parameter('omb_listenee_profile');
     if ($profile_url && !common_valid_http_url($profile_url)) {
         $this->clientError(sprintf(_("Invalid profile URL '%s'."), $profile_url));
         return false;
     }
     # optional stuff
     $fullname = $req->get_parameter('omb_listenee_fullname');
     if ($fullname && mb_strlen($fullname) > 255) {
         $this->clientError(_("Full name is too long (max 255 chars)."));
         return false;
     }
     $homepage = $req->get_parameter('omb_listenee_homepage');
     if ($homepage && (!common_valid_http_url($homepage) || mb_strlen($homepage) > 255)) {
         $this->clientError(sprintf(_("Invalid homepage '%s'"), $homepage));
         return false;
     }
     $bio = $req->get_parameter('omb_listenee_bio');
     if ($bio && mb_strlen($bio) > 140) {
         $this->clientError(_("Bio is too long (max 140 chars)."));
         return false;
     }
     $location = $req->get_parameter('omb_listenee_location');
     if ($location && mb_strlen($location) > 255) {
         $this->clientError(_("Location is too long (max 255 chars)."));
         return false;
     }
     $avatar = $req->get_parameter('omb_listenee_avatar');
     if ($avatar) {
         if (!common_valid_http_url($avatar) || strlen($avatar) > 255) {
             $this->clientError(sprintf(_("Invalid avatar URL '%s'"), $avatar));
             return false;
         }
         $size = @getimagesize($avatar);
         if (!$size) {
             $this->clientError(sprintf(_("Can't read avatar URL '%s'"), $avatar));
             return false;
         }
         if ($size[0] != AVATAR_PROFILE_SIZE || $size[1] != AVATAR_PROFILE_SIZE) {
             $this->clientError(sprintf(_("Wrong size image at '%s'"), $avatar));
             return false;
         }
         if (!in_array($size[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
             $this->clientError(sprintf(_("Wrong image type for '%s'"), $avatar));
             return false;
         }
     }
     $orig_profile = clone $profile;
     /* Use values even if they are an empty string. Parsing an empty string in
        updateProfile is the specified way of clearing a parameter in OMB. */
     if (!is_null($nickname)) {
         $profile->nickname = $nickname;
     }
     if (!is_null($profile_url)) {
         $profile->profileurl = $profile_url;
     }
     if (!is_null($fullname)) {
         $profile->fullname = $fullname;
     }
     if (!is_null($homepage)) {
         $profile->homepage = $homepage;
     }
     if (!is_null($bio)) {
         $profile->bio = $bio;
     }
     if (!is_null($location)) {
         $profile->location = $location;
     }
     if (!$profile->update($orig_profile)) {
         $this->serverError(_('Could not save new profile info'), 500);
         return false;
     } else {
         if ($avatar) {
             $temp_filename = tempnam(sys_get_temp_dir(), 'listenee_avatar');
             copy($avatar, $temp_filename);
             $imagefile = new ImageFile($profile->id, $temp_filename);
             $filename = Avatar::filename($profile->id, image_type_to_extension($imagefile->type), null, common_timestamp());
             rename($temp_filename, Avatar::path($filename));
             if (!$profile->setOriginal($filename)) {
                 $this->serverError(_('Could not save avatar info'), 500);
                 return false;
             }
         }
         return true;
     }
 }
Ejemplo n.º 16
0
 private static function getSubscriptionIDs($get_type, $profile_id, $offset, $limit)
 {
     switch ($get_type) {
         case 'subscribed':
             $by_type = 'subscriber';
             break;
         case 'subscriber':
             $by_type = 'subscribed';
             break;
         default:
             throw new Exception('Bad type argument to getSubscriptionIDs');
     }
     $cacheKey = 'subscription:by-' . $by_type . ':' . $profile_id;
     $queryoffset = $offset;
     $querylimit = $limit;
     if ($offset + $limit <= self::CACHE_WINDOW) {
         // Oh, it seems it should be cached
         $ids = self::cacheGet($cacheKey);
         if (is_array($ids)) {
             return array_slice($ids, $offset, $limit);
         }
         // Being here indicates we didn't find anything cached
         // so we'll have to fill it up simultaneously
         $queryoffset = 0;
         $querylimit = self::CACHE_WINDOW;
     }
     $sub = new Subscription();
     $sub->{$by_type} = $profile_id;
     $sub->selectAdd($get_type);
     $sub->whereAdd("{$get_type} != {$profile_id}");
     $sub->orderBy('created DESC');
     $sub->limit($queryoffset, $querylimit);
     if (!$sub->find()) {
         return array();
     }
     $ids = $sub->fetchAll($get_type);
     // If we're simultaneously filling up cache, remember to slice
     if ($queryoffset === 0 && $querylimit === self::CACHE_WINDOW) {
         self::cacheSet($cacheKey, $ids);
         return array_slice($ids, $offset, $limit);
     }
     return $ids;
 }
Ejemplo n.º 17
0
 function subscriptions($apidata, $other_attr, $user_attr, $onlyIDs = false)
 {
     $this->auth_user = $apidata['user'];
     $user = $this->get_user($apidata['api_arg'], $apidata);
     if (!$user) {
         $this->clientError('Not Found', 404, $apidata['content-type']);
         return;
     }
     $page = $this->trimmed('page');
     if (!$page || !is_numeric($page)) {
         $page = 1;
     }
     $profile = $user->getProfile();
     if (!$profile) {
         $this->serverError(_('User has no profile.'));
         return;
     }
     $sub = new Subscription();
     $sub->{$user_attr} = $profile->id;
     $since = strtotime($this->trimmed('since'));
     if ($since) {
         $d = date('Y-m-d H:i:s', $since);
         $sub->whereAdd("created > '{$d}'");
     }
     $sub->orderBy('created DESC');
     if (!$onlyIDs) {
         $sub->limit(($page - 1) * 100, 100);
     }
     $others = array();
     if ($sub->find()) {
         while ($sub->fetch()) {
             $others[] = Profile::staticGet($sub->{$other_attr});
         }
     } else {
         // user has no followers
     }
     $type = $apidata['content-type'];
     $this->init_document($type);
     if ($onlyIDs) {
         $this->showIDs($others, $type);
     } else {
         $this->show_profiles($others, $type);
     }
     $this->end_document($type);
 }
Ejemplo n.º 18
0
 function _deleteSubscriptions()
 {
     $sub = new Subscription();
     $sub->subscriber = $this->id;
     $sub->find();
     while ($sub->fetch()) {
         $other = Profile::staticGet('id', $sub->subscribed);
         if (empty($other)) {
             continue;
         }
         if ($other->id == $this->id) {
             continue;
         }
         Subscription::cancel($this, $other);
     }
     $subd = new Subscription();
     $subd->subscribed = $this->id;
     $subd->find();
     while ($subd->fetch()) {
         $other = Profile::staticGet('id', $subd->subscriber);
         if (empty($other)) {
             continue;
         }
         if ($other->id == $this->id) {
             continue;
         }
         Subscription::cancel($other, $this);
     }
     $self = new Subscription();
     $self->subscriber = $this->id;
     $self->subscribed = $this->id;
     $self->delete();
 }
Ejemplo n.º 19
0
        Mail::later(5, 'emails.warning', array(), function ($message) use($email) {
            $message->to($email)->subject('[hasztag.info] Mamy problem!');
        });
    } else {
        $lastTry = $notifications->orderBy('id', 'desc')->first()->created_at;
        $diff = $lastTry->diffInDays($lastPayment);
        if ($diff == 3) {
            EmailNotification::create(array('subscription_id' => $subscription->id, 'user_id' => $subscription->user_id));
            Mail::later(5, 'emails.warning', array(), function ($message) use($email) {
                $message->to($email)->subject('[hasztag.info] Mamy problem!');
            });
        }
    }
});
Event::listen('activate.subscription', function ($subscriptionId) {
    $subscription = Subscription::find($subscriptionId);
    $expiration = Carbon::createFromTimeStamp(strtotime($subscription->expires_at));
    $user = User::find($subscription->user_id);
    $client = new Paylane\PayLaneRestClient('adubiel', 'dru9pra2');
    if ($expiration->isToday() || $expiration->isPast()) {
        $sale = $subscription->payment()->orderBy('id', 'desc')->first();
        if ($sale->is_success == 2 || $sale->is_success == 1) {
            if ($sale->is_success == 2) {
                $resale_params = array('id_authorization' => $sale->sale_id, 'amount' => 189.0, 'currency' => 'PLN', 'description' => 'Subskrypcja Hasztag.info');
                $status = $client->resaleByAuthorization($resale_params);
            } else {
                if ($sale->is_success == 1) {
                    $params = array('id_sale' => $sale->sale_id, 'amount' => 189.0, 'currency' => 'PLN', 'description' => 'Subskrypcja Hasztag.info');
                    $status = $client->resaleBySale($params);
                }
            }
Ejemplo n.º 20
0
 private static function realBySubscribed($subscribedId, $offset, $limit)
 {
     $sub = new Subscription();
     $sub->subscribed = $subscribedId;
     $sub->whereAdd('subscriber != ' . $subscribedId);
     $sub->orderBy('created DESC');
     $sub->limit($offset, $limit);
     $sub->find();
     $subs = array();
     while ($sub->fetch()) {
         $subs[] = clone $sub;
     }
     return $subs;
 }
Ejemplo n.º 21
0
 /**
  * Save a subscription
  *
  * Saves the subscription from $subscriber_uri to $subscribed_user_uri.
  * Throws exceptions in case of error.
  *
  * @param string     $subscriber_uri      The OMB identifier URI specifying
  *                                        the subscribing profile
  *
  * @param string     $subscribed_user_uri The OMB identifier URI specifying
  *                                        the subscribed profile
  * @param OAuthToken $token               The access token
  *
  * @access public
  **/
 public function saveSubscription($subscriber_uri, $subscribed_user_uri, $token)
 {
     $sub = new Subscription();
     $subscribed = $this->_getAnyProfile($subscribed_user_uri);
     $subscriber = $this->_getAnyProfile($subscriber_uri);
     if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
         common_log(LOG_INFO, __METHOD__ . ": remote subscriber banned ({$subscriber_uri} subbing to {$subscribed_user_uri})");
         // TRANS: Error message displayed to a banned user when they try to subscribe.
         return _('You have been banned from subscribing.');
     }
     $sub->subscribed = $subscribed->id;
     $sub->subscriber = $subscriber->id;
     $sub_exists = $sub->find(true);
     if ($sub_exists) {
         $orig_sub = clone $sub;
     } else {
         $sub->created = DB_DataObject_Cast::dateTime();
     }
     $sub->token = $token->key;
     $sub->secret = $token->secret;
     if ($sub_exists) {
         $result = $sub->update($orig_sub);
     } else {
         $result = $sub->insert();
     }
     if (!$result) {
         common_log_db_error($sub, $sub_exists ? 'UPDATE' : 'INSERT', __FILE__);
         // TRANS: Exception thrown when creating a new subscription fails in OAuth store.
         throw new Exception(_('Could not insert new subscription.'));
         return;
     }
     /* Notify user, if necessary. */
     if ($subscribed instanceof User) {
         mail_subscribe_notify_profile($subscribed, Profile::staticGet($subscriber->id));
     }
 }
 /**
  * [invoiceClient - append selected entries to a MB invoice if one exists. Otherwise create a new one]
  * @param  [array]  $all_company_values     [segmented data company row]
  * @param  [int]    $company_id             [description]
  * @param  [string] $op_type                [invoice/invoice_clear + strip/strip_clear]
  * @return [mb invoice]                     [MB invoice that was used]
  */
 public function invoiceClient($all_company_values, $company_id, $op_type)
 {
     error_log('Invoicing client');
     // create invoice details obj
     //$customer_id = Config::get('eenvoudcrm.moneybird_test_user_id');
     $customer_id = $this->getContact($company_id);
     if ($customer_id === -1) {
         return false;
     }
     error_log('Local Contact Exists');
     $contact = null;
     try {
         $contact = $this->getRequest('contacts/' . $customer_id . '.json');
     } catch (Exception $e) {
         error_log($e->getMessage());
         die;
     }
     if (!$contact) {
         error_log("Consistency check failure: contact not found");
         return false;
     }
     error_log('Remote Contact Exists');
     // check for open invoices
     try {
         $open_invoices = $this->getRequest('sales_invoices.json?filter=state:draft,contact_id:' . $customer_id);
     } catch (Exception $e) {
         error_log($e->getMessage());
         die;
     }
     //$invoice = null;
     $details = [];
     $new_invoice = false;
     if (count($open_invoices) > 0) {
         $used_invoice_id = -1;
         error_log('found an open invoice for ' . $customer_id . ' - ' . json_encode($open_invoices[0]));
         //$used_invoice_id = 135871568029943606;
         if (isset($open_invoices[0]->id)) {
             $used_invoice_id = $open_invoices[0]->id;
         }
         if ($used_invoice_id === -1) {
             $error_msg = 'Error: IntegrationMoneybirdController2 - Found open invoices but could not get invoice id';
             throw new Exception($error_msg);
             error_log($error_msg);
             die;
         }
         // sanity check - try getting the first invoice draft
         // try {
         //     $invoice = $this->getRequest('sales_invoices/'.$used_invoice_id.'.json');
         // } catch(Exception $e) {
         //     error_log($e->getMessage());
         //     die();
         // }
     } else {
         $new_invoice = true;
     }
     // get price and description
     if ($op_type === 'subscription') {
         // append details
         $segmented_by_service = $this->segmentDataByService($all_company_values);
         foreach ($segmented_by_service as $service_ndx => $service_values) {
             $service = Service::find((int) $service_ndx);
             // load relations
             $load_cat_relation = $service->category;
             $service_line = "\r\n*" . $service->category->name . " - " . $service->name . "*";
             // invoice details line 1
             foreach ($service_values as $key => $company_row_values) {
                 $curr_price = 0;
                 $curr_description = '';
                 $item_id = (int) $company_row_values['subscriptions.id'];
                 $subscription = Subscription::find($item_id);
                 $service = $subscription->service;
                 $service_category = $service->category;
                 $periodicity = $subscription->invoice_periods_id;
                 $interval_size = 1;
                 $periodicity_str = "";
                 switch ($periodicity) {
                     case 1:
                         $periodicity_str = "jaar";
                         $interval_size = 12;
                         break;
                     case 2:
                         $periodicity_str = "kwartjaar";
                         $interval_size = 4;
                         break;
                     case 3:
                         $periodicity_str = "kwartaal";
                         $interval_size = 3;
                         break;
                     case 4:
                         $periodicity_str = "mnd";
                         $interval_size = 1;
                         break;
                     default:
                         break;
                 }
                 // avoid MB errors dues to ammount too large
                 if ($subscription->subscription_start === '0000-00-00' || $subscription->subscription_end === '000-00-00') {
                     continue;
                 }
                 $start_date = new DateTime($subscription->subscription_start);
                 $end_date = new DateTime($subscription->subscription_end);
                 $end_date->add(new DateInterval('P1D'));
                 $num_months = $start_date->diff($end_date)->m + $start_date->diff($end_date)->y * 12;
                 $num_items = floatval($num_months) / floatval($interval_size);
                 if ($interval_size > $num_months) {
                     $num_items = $num_months;
                     $periodicity_str = "maand";
                 }
                 // calc price depending on whether item is singular or periodic
                 $curr_price = round((double) $subscription->price, 2);
                 $curr_description = ($subscription->description ? "{$subscription->description}" : "") . " _({$subscription->subscription_start} - {$subscription->subscription_end})_";
                 // invoice details line 1
                 $details[] = (object) ['amount' => "{$num_items} x {$periodicity_str}", 'description' => $curr_description, 'price' => $curr_price, 'tax_rate_id' => Config::get('eenvoudcrm.taxrate_high_id'), 'ledger_account_id' => Config::get('eenvoudcrm.ledger_account_id')];
             }
         }
     } elseif ($op_type === 'worklog') {
         $worklogs_line = "\r\n*Werklogs*";
         // invoice details line 1
         $details[] = (object) ['description' => $worklogs_line];
         foreach ($all_company_values as $company_row_ndx => $company_row_values) {
             $curr_price = 0;
             $curr_description = '';
             $item_id = (int) $company_row_values['worklogs.id'];
             $worklog = Werklog::find($item_id);
             // round minutes to upper quarter of the hour
             $round_minutes = floor($worklog->minutes / 15.0) * 15 + ($worklog->minutes % 15 > 0 ? 15 : 0);
             $dec_hours = (double) $round_minutes / 60.0;
             // calc total price
             $curr_price = (double) Config::get('eenvoudcrm.worklog_price_per_hour') * $dec_hours;
             $hours = floor($dec_hours);
             $minutes = round(60.0 * ($dec_hours - $hours));
             $curr_description = "{$worklog->date} - (" . ($hours > 0 ? "{$hours} h " : "") . "{$minutes} m)" . ($worklog->description ? " - {$worklog->description}" : "");
             if ($worklog->comment) {
                 $curr_description .= "\r\n[{$worklog->comment}]";
             }
             // invoice details line 1
             $details[] = (object) ['amount' => '1 x', 'description' => $curr_description, 'price' => $curr_price, 'tax_rate_id' => Config::get('eenvoudcrm.taxrate_high_id'), 'ledger_account_id' => Config::get('eenvoudcrm.ledger_account_id')];
         }
     }
     $details_line = '{"sales_invoice":{"details_attributes":' . json_encode((object) $details) . '}}';
     $ret_invoice = null;
     // save
     try {
         if (!$new_invoice) {
             $ret_invoice = $this->patchRequest('sales_invoices/' . $used_invoice_id . '.json', $details_line);
         } else {
             $invoice = '{"sales_invoice":{"reference":"","contact_id":' . $customer_id . ',"details_attributes":' . json_encode((object) $details) . '}}';
             $ret_invoice = $this->postRequest('sales_invoices.json', $invoice);
         }
     } catch (Exception $e) {
         error_log($e->getMessage());
         die;
     }
     return $ret_invoice;
 }
Ejemplo n.º 23
0
 /**
  * [postSubscriptionData - Process posted subscription data]
  * @return [json]       [DT compatible object]
  */
 public function postSubscriptionData()
 {
     error_log('>>> ALL POSTED subscription data ' . json_encode($_POST));
     $all_posted_values = $_POST['values'];
     $op_type = $_POST['type'];
     $segmented_data = null;
     if ($op_type === "invoice") {
         $segmented_data = $this->segmentDataByCompany($all_posted_values, 'subscriptions', false);
         $mb = new IntegrationMoneybirdController2();
         foreach ($segmented_data as $company_ndx => $all_company_values) {
             $company_invoice = $mb->invoiceClient($all_company_values, $company_ndx, 'subscription');
             if ($company_invoice && $company_invoice->id) {
                 foreach ($all_company_values as $company_subscriptions_ndx => $company_subscription_values) {
                     $subscription = Subscription::find((int) $company_subscription_values['subscriptions.id']);
                     if ($subscription) {
                         $subscription->invoice_id = $company_invoice->id;
                         $subscription->save();
                     }
                 }
             } else {
                 error_log('AAC: No $invoice');
             }
         }
     } elseif ($op_type === "invoice_clear") {
         $segmented_data = $this->segmentDataByCompany($all_posted_values, 'subscriptions', true);
         foreach ($segmented_data as $company_ndx => $all_company_values) {
             foreach ($all_company_values as $company_subscriptions_ndx => $company_subscription_values) {
                 $subscription = Subscription::find((int) $company_subscription_values['subscriptions.id']);
                 if ($subscription) {
                     $subscription->invoice_id = null;
                     $subscription->save();
                 }
             }
         }
     } else {
         error_log('AAC: No $op_type');
     }
     return Response::json((object) null);
 }
Ejemplo n.º 24
0
 /**
  * Output FOAF <account> bit for the given profile.
  *
  * @param Profile $profile
  * @param mixed $service Root URL of this StatusNet instance for a local
  *                       user, otherwise null.
  * @param mixed $useruri URI string for the referenced profile..
  * @param boolean $fetchSubscriptions Should we load and list all their subscriptions?
  * @param boolean $isSubscriber if not fetching subs, we can still mark the user as following the current page.
  *
  * @return array if $fetchSubscribers is set, return a list of info on those
  *               subscriptions.
  */
 function showMicrobloggingAccount($profile, $service = null, $useruri = null, $fetchSubscriptions = false, $isSubscriber = false)
 {
     $attr = array();
     if ($useruri) {
         $attr['rdf:about'] = $useruri . '#acct';
     }
     // Their account
     $this->elementStart('account');
     $this->elementStart('OnlineAccount', $attr);
     if ($service) {
         $this->element('accountServiceHomepage', array('rdf:resource' => $service));
     }
     $this->element('accountName', null, $profile->nickname);
     $this->element('accountProfilePage', array('rdf:resource' => $profile->profileurl));
     if ($useruri) {
         $this->element('sioc:account_of', array('rdf:resource' => $useruri));
     }
     $person = array();
     if ($fetchSubscriptions) {
         // Get people user is subscribed to
         $sub = new Subscription();
         $sub->subscriber = $profile->id;
         $sub->whereAdd('subscriber != subscribed');
         if ($sub->find()) {
             while ($sub->fetch()) {
                 $profile = Profile::staticGet('id', $sub->subscribed);
                 if (empty($profile)) {
                     common_debug('Got a bad subscription: ' . print_r($sub, true));
                     continue;
                 }
                 $user = $profile->getUser();
                 $other_uri = $profile->getUri();
                 $this->element('sioc:follows', array('rdf:resource' => $other_uri . '#acct'));
                 $person[$other_uri] = array(LISTENEE, $profile->id, $profile->nickname, $user ? 'local' : 'remote');
                 unset($profile);
             }
         }
         unset($sub);
     } else {
         if ($isSubscriber) {
             // Just declare that they follow the user whose FOAF we're showing.
             $this->element('sioc:follows', array('rdf:resource' => $this->user->uri . '#acct'));
         }
     }
     $this->elementEnd('OnlineAccount');
     $this->elementEnd('account');
     return $person;
 }
Ejemplo n.º 25
0
function initSubscriptionURI()
{
    printfnq("Ensuring all subscriptions have a URI...");
    $sub = new Subscription();
    $sub->whereAdd('uri IS NULL');
    if ($sub->find()) {
        while ($sub->fetch()) {
            try {
                $sub->decache();
                $sub->query(sprintf('update subscription ' . 'set uri = "%s" ' . 'where subscriber = %d ' . 'and subscribed = %d', Subscription::newURI($sub->subscriber, $sub->subscribed, $sub->created), $sub->subscriber, $sub->subscribed));
            } catch (Exception $e) {
                common_log(LOG_ERR, "Error updated subscription URI: " . $e->getMessage());
            }
        }
    }
    printfnq("DONE.\n");
}
Ejemplo n.º 26
0
 function validateOmb()
 {
     $listener = $_GET['omb_listener'];
     $listenee = $_GET['omb_listenee'];
     $nickname = $_GET['omb_listenee_nickname'];
     $profile = $_GET['omb_listenee_profile'];
     $user = User::staticGet('uri', $listener);
     if (!$user) {
         throw new Exception(sprintf(_('Listener URI ‘%s’ not found here.'), $listener));
     }
     if (strlen($listenee) > 255) {
         throw new Exception(sprintf(_('Listenee URI ‘%s’ is too long.'), $listenee));
     }
     $other = User::staticGet('uri', $listenee);
     if ($other) {
         throw new Exception(sprintf(_('Listenee URI ‘%s’ is a local user.'), $listenee));
     }
     $remote = Remote_profile::staticGet('uri', $listenee);
     if ($remote) {
         $sub = new Subscription();
         $sub->subscriber = $user->id;
         $sub->subscribed = $remote->id;
         if ($sub->find(true)) {
             throw new Exception('You are already subscribed to this user.');
         }
     }
     if ($profile == common_profile_url($nickname)) {
         throw new Exception(sprintf(_('Profile URL ‘%s’ is for a local user.'), $profile));
     }
     $license = $_GET['omb_listenee_license'];
     $site_license = common_config('license', 'url');
     if (!common_compatible_license($license, $site_license)) {
         throw new Exception(sprintf(_('Listenee stream license ‘%1$s’ is not ' . 'compatible with site license ‘%2$s’.'), $license, $site_license));
     }
     $avatar = $_GET['omb_listenee_avatar'];
     if ($avatar) {
         if (!common_valid_http_url($avatar) || strlen($avatar) > 255) {
             throw new Exception(sprintf(_('Avatar URL ‘%s’ is not valid.'), $avatar));
         }
         $size = @getimagesize($avatar);
         if (!$size) {
             throw new Exception(sprintf(_('Can’t read avatar URL ‘%s’.'), $avatar));
         }
         if (!in_array($size[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
             throw new Exception(sprintf(_('Wrong image type for avatar URL ' . '‘%s’.'), $avatar));
         }
     }
 }
Ejemplo n.º 27
0
 function handle($args)
 {
     parent::handle($args);
     if (common_logged_in()) {
         $this->clientError(_('You can use the local subscription!'));
         return;
     }
     $omb = $_SESSION['oauth_authorization_request'];
     if (!$omb) {
         $this->clientError(_('Not expecting this response!'));
         return;
     }
     common_debug('stored request: ' . print_r($omb, true), __FILE__);
     common_remove_magic_from_request();
     $req = OAuthRequest::from_request();
     $token = $req->get_parameter('oauth_token');
     # I think this is the success metric
     if ($token != $omb['token']) {
         $this->clientError(_('Not authorized.'));
         return;
     }
     $version = $req->get_parameter('omb_version');
     if ($version != OMB_VERSION_01) {
         $this->clientError(_('Unknown version of OMB protocol.'));
         return;
     }
     $nickname = $req->get_parameter('omb_listener_nickname');
     if (!$nickname) {
         $this->clientError(_('No nickname provided by remote server.'));
         return;
     }
     $profile_url = $req->get_parameter('omb_listener_profile');
     if (!$profile_url) {
         $this->clientError(_('No profile URL returned by server.'));
         return;
     }
     if (!Validate::uri($profile_url, array('allowed_schemes' => array('http', 'https')))) {
         $this->clientError(_('Invalid profile URL returned by server.'));
         return;
     }
     if ($profile_url == common_local_url('showstream', array('nickname' => $nickname))) {
         $this->clientError(_('You can use the local subscription!'));
         return;
     }
     common_debug('listenee: "' . $omb['listenee'] . '"', __FILE__);
     $user = User::staticGet('nickname', $omb['listenee']);
     if (!$user) {
         $this->clientError(_('User being listened to doesn\'t exist.'));
         return;
     }
     $other = User::staticGet('uri', $omb['listener']);
     if ($other) {
         $this->clientError(_('You can use the local subscription!'));
         return;
     }
     $fullname = $req->get_parameter('omb_listener_fullname');
     $homepage = $req->get_parameter('omb_listener_homepage');
     $bio = $req->get_parameter('omb_listener_bio');
     $location = $req->get_parameter('omb_listener_location');
     $avatar_url = $req->get_parameter('omb_listener_avatar');
     list($newtok, $newsecret) = $this->access_token($omb);
     if (!$newtok || !$newsecret) {
         $this->clientError(_('Couldn\'t convert request tokens to access tokens.'));
         return;
     }
     # XXX: possible attack point; subscribe and return someone else's profile URI
     $remote = Remote_profile::staticGet('uri', $omb['listener']);
     if ($remote) {
         $exists = true;
         $profile = Profile::staticGet($remote->id);
         $orig_remote = clone $remote;
         $orig_profile = clone $profile;
         # XXX: compare current postNotice and updateProfile URLs to the ones
         # stored in the DB to avoid (possibly...) above attack
     } else {
         $exists = false;
         $remote = new Remote_profile();
         $remote->uri = $omb['listener'];
         $profile = new Profile();
     }
     $profile->nickname = $nickname;
     $profile->profileurl = $profile_url;
     if (!is_null($fullname)) {
         $profile->fullname = $fullname;
     }
     if (!is_null($homepage)) {
         $profile->homepage = $homepage;
     }
     if (!is_null($bio)) {
         $profile->bio = $bio;
     }
     if (!is_null($location)) {
         $profile->location = $location;
     }
     if ($exists) {
         $profile->update($orig_profile);
     } else {
         $profile->created = DB_DataObject_Cast::dateTime();
         # current time
         $id = $profile->insert();
         if (!$id) {
             $this->serverError(_('Error inserting new profile'));
             return;
         }
         $remote->id = $id;
     }
     if ($avatar_url) {
         if (!$this->add_avatar($profile, $avatar_url)) {
             $this->serverError(_('Error inserting avatar'));
             return;
         }
     }
     $remote->postnoticeurl = $omb['post_notice_url'];
     $remote->updateprofileurl = $omb['update_profile_url'];
     if ($exists) {
         if (!$remote->update($orig_remote)) {
             $this->serverError(_('Error updating remote profile'));
             return;
         }
     } else {
         $remote->created = DB_DataObject_Cast::dateTime();
         # current time
         if (!$remote->insert()) {
             $this->serverError(_('Error inserting remote profile'));
             return;
         }
     }
     if ($user->hasBlocked($profile)) {
         $this->clientError(_('That user has blocked you from subscribing.'));
         return;
     }
     $sub = new Subscription();
     $sub->subscriber = $remote->id;
     $sub->subscribed = $user->id;
     $sub_exists = false;
     if ($sub->find(true)) {
         $sub_exists = true;
         $orig_sub = clone $sub;
     } else {
         $sub_exists = false;
         $sub->created = DB_DataObject_Cast::dateTime();
         # current time
     }
     $sub->token = $newtok;
     $sub->secret = $newsecret;
     if ($sub_exists) {
         $result = $sub->update($orig_sub);
     } else {
         $result = $sub->insert();
     }
     if (!$result) {
         common_log_db_error($sub, $sub_exists ? 'UPDATE' : 'INSERT', __FILE__);
         $this->clientError(_('Couldn\'t insert new subscription.'));
         return;
     }
     # Notify user, if necessary
     mail_subscribe_notify_profile($user, $profile);
     # Clear the data
     unset($_SESSION['oauth_authorization_request']);
     # If we show subscriptions in reverse chron order, this should
     # show up close to the top of the page
     common_redirect(common_local_url('subscribers', array('nickname' => $user->nickname)));
 }
Ejemplo n.º 28
0
 function item($id = FALSE)
 {
     if ($_POST) {
         unset($_POST['send']);
         $_POST = array_map('htmlspecialchars', $_POST);
         if ($_POST['name'] != "") {
             $_POST['name'] = $_POST['name'];
             $_POST['value'] = $_POST['value'];
             $_POST['type'] = $_POST['type'];
         } else {
             if ($_POST['item_id'] == "-") {
                 $this->session->set_flashdata('message', 'error:' . $this->lang->line('messages_add_item_error'));
                 redirect('subscriptions/view/' . $_POST['subscription_id']);
             } else {
                 $itemvalue = Item::find($_POST['item_id']);
                 $_POST['name'] = $itemvalue->name;
                 $_POST['type'] = $itemvalue->type;
                 $_POST['value'] = $itemvalue->value;
             }
         }
         $item = SubscriptionHasItem::create($_POST);
         if (!$item) {
             $this->session->set_flashdata('message', 'error:' . $this->lang->line('messages_add_item_error'));
         } else {
             $this->session->set_flashdata('message', 'success:' . $this->lang->line('messages_add_item_success'));
         }
         redirect('subscriptions/view/' . $_POST['subscription_id']);
     } else {
         $this->view_data['subscription'] = Subscription::find($id);
         $this->view_data['items'] = Item::find('all', array('conditions' => array('inactive=?', '0')));
         $this->theme_view = 'modal';
         $this->view_data['title'] = $this->lang->line('application_add_item');
         $this->view_data['form_action'] = 'subscriptions/item';
         $this->content_view = 'subscriptions/_item';
     }
 }
Ejemplo n.º 29
0
 function validateOmb(&$req)
 {
     foreach (array('omb_version', 'omb_listener', 'omb_listenee', 'omb_listenee_profile', 'omb_listenee_nickname', 'omb_listenee_license') as $param) {
         if (is_null($req->get_parameter($param))) {
             throw new OAuthException("Required parameter '{$param}' not found");
         }
     }
     # Now, OMB stuff
     $version = $req->get_parameter('omb_version');
     if ($version != OMB_VERSION_01) {
         throw new OAuthException("OpenMicroBlogging version '{$version}' not supported");
     }
     $listener = $req->get_parameter('omb_listener');
     $user = User::staticGet('uri', $listener);
     if (!$user) {
         throw new OAuthException("Listener URI '{$listener}' not found here");
     }
     $cur = common_current_user();
     if ($cur->id != $user->id) {
         throw new OAuthException("Can't add for another user!");
     }
     $listenee = $req->get_parameter('omb_listenee');
     if (!Validate::uri($listenee) && !common_valid_tag($listenee)) {
         throw new OAuthException("Listenee URI '{$listenee}' not a recognizable URI");
     }
     if (strlen($listenee) > 255) {
         throw new OAuthException("Listenee URI '{$listenee}' too long");
     }
     $other = User::staticGet('uri', $listenee);
     if ($other) {
         throw new OAuthException("Listenee URI '{$listenee}' is local user");
     }
     $remote = Remote_profile::staticGet('uri', $listenee);
     if ($remote) {
         $sub = new Subscription();
         $sub->subscriber = $user->id;
         $sub->subscribed = $remote->id;
         if ($sub->find(true)) {
             throw new OAuthException("Already subscribed to user!");
         }
     }
     $nickname = $req->get_parameter('omb_listenee_nickname');
     if (!Validate::string($nickname, array('min_length' => 1, 'max_length' => 64, 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
         throw new OAuthException('Nickname must have only letters and numbers and no spaces.');
     }
     $profile = $req->get_parameter('omb_listenee_profile');
     if (!common_valid_http_url($profile)) {
         throw new OAuthException("Invalid profile URL '{$profile}'.");
     }
     if ($profile == common_local_url('showstream', array('nickname' => $nickname))) {
         throw new OAuthException("Profile URL '{$profile}' is for a local user.");
     }
     $license = $req->get_parameter('omb_listenee_license');
     if (!common_valid_http_url($license)) {
         throw new OAuthException("Invalid license URL '{$license}'.");
     }
     $site_license = common_config('license', 'url');
     if (!common_compatible_license($license, $site_license)) {
         throw new OAuthException("Listenee stream license '{$license}' not compatible with site license '{$site_license}'.");
     }
     # optional stuff
     $fullname = $req->get_parameter('omb_listenee_fullname');
     if ($fullname && mb_strlen($fullname) > 255) {
         throw new OAuthException("Full name '{$fullname}' too long.");
     }
     $homepage = $req->get_parameter('omb_listenee_homepage');
     if ($homepage && (!common_valid_http_url($homepage) || mb_strlen($homepage) > 255)) {
         throw new OAuthException("Invalid homepage '{$homepage}'");
     }
     $bio = $req->get_parameter('omb_listenee_bio');
     if ($bio && mb_strlen($bio) > 140) {
         throw new OAuthException("Bio too long '{$bio}'");
     }
     $location = $req->get_parameter('omb_listenee_location');
     if ($location && mb_strlen($location) > 255) {
         throw new OAuthException("Location too long '{$location}'");
     }
     $avatar = $req->get_parameter('omb_listenee_avatar');
     if ($avatar) {
         if (!common_valid_http_url($avatar) || strlen($avatar) > 255) {
             throw new OAuthException("Invalid avatar URL '{$avatar}'");
         }
         $size = @getimagesize($avatar);
         if (!$size) {
             throw new OAuthException("Can't read avatar URL '{$avatar}'");
         }
         if ($size[0] != AVATAR_PROFILE_SIZE || $size[1] != AVATAR_PROFILE_SIZE) {
             throw new OAuthException("Wrong size image at '{$avatar}'");
         }
         if (!in_array($size[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
             throw new OAuthException("Wrong image type for '{$avatar}'");
         }
     }
     $callback = $req->get_parameter('oauth_callback');
     if ($callback && !common_valid_http_url($callback)) {
         throw new OAuthException("Invalid callback URL '{$callback}'");
     }
     if ($callback && $callback == common_local_url('finishremotesubscribe')) {
         throw new OAuthException("Callback URL '{$callback}' is for local site.");
     }
 }