profiledetailsettings.php 17.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<?php
/*
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2011, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

20
if (!defined('GNUSOCIAL')) { exit(1); }
21

Zach Copley's avatar
Zach Copley committed
22
class ProfileDetailSettingsAction extends ProfileSettingsAction
23 24 25
{
    function title()
    {
26
        // TRANS: Title for extended profile settings.
27 28 29 30 31
        return _m('Extended profile settings');
    }

    function showStylesheets() {
        parent::showStylesheets();
32 33 34 35 36 37 38
        $this->cssLink('plugins/ExtendedProfile/css/profiledetail.css');
        return true;
    }

    function  showScripts() {
        parent::showScripts();
        $this->script('plugins/ExtendedProfile/js/profiledetail.js');
39 40 41
        return true;
    }

42
    protected function doPost()
43
    {
44
        if ($this->arg('save')) {
45
            return $this->saveDetails();
46
        }
47 48 49

        // TRANS: Message given submitting a form with an unknown action.
        throw new ClientException(_m('Unexpected form submission.'));
50 51 52 53
    }

    function showContent()
    {
Zach Copley's avatar
Zach Copley committed
54 55
        $widget = new ExtendedProfileWidget(
            $this,
56
            $this->scoped,
Zach Copley's avatar
Zach Copley committed
57 58
            ExtendedProfileWidget::EDITABLE
        );
59 60
        $widget->show();
    }
61 62 63 64 65

    function saveDetails()
    {
        common_debug(var_export($_POST, true));

66
        $this->saveStandardProfileDetails();
67

68 69
        $simpleFieldNames = array('title', 'spouse', 'kids', 'manager');
        $dateFieldNames   = array('birthday');
70

71 72 73 74
        foreach ($simpleFieldNames as $name) {
            $value = $this->trimmed('extprofile-' . $name);
            if (!empty($value)) {
                $this->saveField($name, $value);
75
            }
76
        }
77

78 79 80 81 82 83 84 85 86 87
        foreach ($dateFieldNames as $name) {
            $value = $this->trimmed('extprofile-' . $name);
            $dateVal = $this->parseDate($name, $value);
            $this->saveField(
                $name,
                null,
                null,
                null,
                $dateVal
            );
88
        }
Zach Copley's avatar
Zach Copley committed
89

90 91 92 93 94 95
        $this->savePhoneNumbers();
        $this->saveIms();
        $this->saveWebsites();
        $this->saveExperiences();
        $this->saveEducations();

96
        // TRANS: Success message after saving extended profile details.
97
        return _m('Details saved.');
98 99 100

    }

101 102
    function parseDate($fieldname, $datestr, $required = false)
    {
103 104 105
        if (empty($datestr)) {
            if ($required) {
                $msg = sprintf(
106 107
                    // TRANS: Exception thrown when no date was entered in a required date field.
                    // TRANS: %s is the field name.
108 109 110 111 112
                    _m('You must supply a date for "%s".'),
                    $fieldname
                );
                throw new Exception($msg);
            }
113 114 115 116 117
        } else {
            $ts = strtotime($datestr);
            if ($ts === false) {
                throw new Exception(
                    sprintf(
118 119 120
                        // TRANS: Exception thrown on incorrect data input.
                        // TRANS: %1$s is a field name, %2$s is the incorrect input.
                        _m('Invalid date entered for "%1$s": %2$s.'),
121 122 123 124 125 126 127 128 129 130
                        $fieldname,
                        $ts
                    )
                );
            }
            return common_sql_date($ts);
        }
        return null;
    }

131
    function savePhoneNumbers() {
Zach Copley's avatar
Zach Copley committed
132
        $phones = $this->findPhoneNumbers();
133
        $this->removeAll('phone');
134 135 136 137 138 139 140 141 142 143 144
        $i = 0;
        foreach($phones as $phone) {
            if (!empty($phone['value'])) {
                ++$i;
                $this->saveField(
                    'phone',
                    $phone['value'],
                    $phone['rel'],
                    $i
                );
            }
Zach Copley's avatar
Zach Copley committed
145 146 147 148
        }
    }

    function findPhoneNumbers() {
149

150 151 152 153 154 155
        // Form vals look like this:
        // 'extprofile-phone-1' => '11332',
        // 'extprofile-phone-1-rel' => 'mobile',

        $phones     = $this->sliceParams('phone', 2);
        $phoneArray = array();
Zach Copley's avatar
Zach Copley committed
156

157
        foreach ($phones as $phone) {
Zach Copley's avatar
Zach Copley committed
158
            list($number, $rel) = array_values($phone);
159
            $phoneArray[] = array(
Zach Copley's avatar
Zach Copley committed
160 161 162 163 164
                'value' => $number,
                'rel'   => $rel
            );
        }

165
        return $phoneArray;
166 167
    }

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    function findIms() {

        //  Form vals look like this:
        // 'extprofile-im-0' => 'jed',
        // 'extprofile-im-0-rel' => 'yahoo',

        $ims     = $this->sliceParams('im', 2);
        $imArray = array();

        foreach ($ims as $im) {
            list($id, $rel) = array_values($im);
            $imArray[] = array(
                'value' => $id,
                'rel'   => $rel
            );
        }

        return $imArray;
    }

188
    function saveIms() {
189
        $ims = $this->findIms();
190
        $this->removeAll('im');
191 192 193 194 195 196 197 198 199 200 201 202 203 204
        $i = 0;
        foreach($ims as $im) {
            if (!empty($im['value'])) {
                ++$i;
                $this->saveField(
                    'im',
                    $im['value'],
                    $im['rel'],
                    $i
                );
            }
        }
    }

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    function findWebsites() {

        //  Form vals look like this:

        $sites = $this->sliceParams('website', 2);
        $wsArray = array();

        foreach ($sites as $site) {
            list($id, $rel) = array_values($site);
            $wsArray[] = array(
                'value' => $id,
                'rel'   => $rel
            );
        }

        return $wsArray;
    }

223
    function saveWebsites() {
224
        $sites = $this->findWebsites();
225
        $this->removeAll('website');
226 227
        $i = 0;
        foreach($sites as $site) {
228
            if (!empty($site['value']) && !common_valid_http_url($site['value'])) {
229 230 231
                // TRANS: Exception thrown when entering an invalid URL.
                // TRANS: %s is the invalid URL.
                throw new Exception(sprintf(_m('Invalid URL: %s.'), $site['value']));
232 233
            }

234 235 236 237 238 239 240 241 242 243 244 245
            if (!empty($site['value'])) {
                ++$i;
                $this->saveField(
                    'website',
                    $site['value'],
                    $site['rel'],
                    $i
                );
            }
        }
    }

246 247 248 249 250 251 252 253
    function findExperiences() {

        // Form vals look like this:
        // 'extprofile-experience-0'         => 'Bozotronix',
        // 'extprofile-experience-0-current' => 'true'
        // 'extprofile-experience-0-start'   => '1/5/10',
        // 'extprofile-experience-0-end'     => '2/3/11',

254
        $experiences = $this->sliceParams('experience', 4);
255 256 257
        $expArray = array();

        foreach ($experiences as $exp) {
258 259 260 261 262 263
            if (sizeof($experiences) == 4) {
                list($company, $current, $end, $start) = array_values($exp);
            } else {
                $end = null;
                list($company, $current, $start) = array_values($exp);
            }
264 265 266
            if (!empty($company)) {
                $expArray[] = array(
                    'company' => $company,
267
                    'start'   => $this->parseDate('Start', $start, true),
268
                    'end'     => ($current == 'false') ? $this->parseDate('End', $end, true) : null,
269 270 271
                    'current' => ($current == 'false') ? false : true
                );
            }
272 273 274 275 276
        }

        return $expArray;
    }

277
    function saveExperiences() {
278 279 280
        common_debug('save experiences');
        $experiences = $this->findExperiences();

281 282 283
        $this->removeAll('company');
        $this->removeAll('start');
        $this->removeAll('end'); // also stores 'current'
284 285 286 287 288 289 290 291 292 293 294

        $i = 0;
        foreach($experiences as $experience) {
            if (!empty($experience['company'])) {
                ++$i;
                $this->saveField(
                    'company',
                    $experience['company'],
                    null,
                    $i
                );
295

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
                $this->saveField(
                    'start',
                    null,
                    null,
                    $i,
                    $experience['start']
                );

                // Save "current" employer indicator in rel
                if ($experience['current']) {
                    $this->saveField(
                        'end',
                        null,
                        'current', // rel
                        $i
                    );
                } else {
                    $this->saveField(
                        'end',
                        null,
                        null,
                        $i,
                        $experience['end']
                    );
                }
321

322 323 324 325
            }
        }
    }

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    function findEducations() {

        // Form vals look like this:
        // 'extprofile-education-0-school' => 'Pigdog',
        // 'extprofile-education-0-degree' => 'BA',
        // 'extprofile-education-0-description' => 'Blar',
        // 'extprofile-education-0-start' => '05/22/99',
        // 'extprofile-education-0-end' => '05/22/05',

        $edus = $this->sliceParams('education', 5);
        $eduArray = array();

        foreach ($edus as $edu) {
            list($school, $degree, $description, $end, $start) = array_values($edu);
            if (!empty($school)) {
                $eduArray[] = array(
                    'school'      => $school,
                    'degree'      => $degree,
                    'description' => $description,
345 346
                    'start'       => $this->parseDate('Start', $start, true),
                    'end'         => $this->parseDate('End', $end, true)
347 348 349 350 351 352 353 354
                );
            }
        }

        return $eduArray;
    }


355
    function saveEducations() {
356 357 358 359
         common_debug('save education');
         $edus = $this->findEducations();
         common_debug(var_export($edus, true));

360 361 362 363 364
         $this->removeAll('school');
         $this->removeAll('degree');
         $this->removeAll('degree_descr');
         $this->removeAll('school_start');
         $this->removeAll('school_end');
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406

         $i = 0;
         foreach($edus as $edu) {
             if (!empty($edu['school'])) {
                 ++$i;
                 $this->saveField(
                     'school',
                     $edu['school'],
                     null,
                     $i
                 );
                 $this->saveField(
                     'degree',
                     $edu['degree'],
                     null,
                     $i
                 );
                 $this->saveField(
                     'degree_descr',
                     $edu['description'],
                     null,
                     $i
                 );
                 $this->saveField(
                     'school_start',
                     null,
                     null,
                     $i,
                     $edu['start']
                 );

                 $this->saveField(
                     'school_end',
                     null,
                     null,
                     $i,
                     $edu['end']
                 );
            }
         }
     }

Zach Copley's avatar
Zach Copley committed
407
    function arraySplit($array, $pieces)
408
    {
Zach Copley's avatar
Zach Copley committed
409 410 411 412 413 414
        if ($pieces < 2) {
            return array($array);
        }

        $newCount = ceil(count($array) / $pieces);
        $a = array_slice($array, 0, $newCount);
415
        $b = $this->arraySplit(array_slice($array, $newCount), $pieces - 1);
416

Zach Copley's avatar
Zach Copley committed
417 418 419 420 421 422 423 424 425 426 427 428 429 430
        return array_merge(array($a), $b);
    }

    function findMultiParams($type) {
        $formVals = array();
        $target   = $type;
        foreach ($_POST as $key => $val) {
            if (strrpos('extprofile-' . $key, $target) !== false) {
                $formVals[$key] = $val;
            }
        }
        return $formVals;
    }

431 432 433 434 435 436 437 438
    function sliceParams($key, $size) {
        $slice = array();
        $params = $this->findMultiParams($key);
        ksort($params);
        $slice = $this->arraySplit($params, sizeof($params) / $size);
        return $slice;
    }

Zach Copley's avatar
Zach Copley committed
439 440 441 442 443 444 445
    /**
     * Save an extended profile field as a Profile_detail
     *
     * @param string $name    field name
     * @param string $value   field value
     * @param string $rel     field rel (type)
     * @param int    $index   index (fields can have multiple values)
446
     * @param date   $date    related date
Zach Copley's avatar
Zach Copley committed
447
     */
448
    function saveField($name, $value, $rel = null, $index = null, $date = null)
Zach Copley's avatar
Zach Copley committed
449 450
    {
        $detail  = new Profile_detail();
451

452
        $detail->profile_id  = $this->scoped->getID();
453
        $detail->field_name  = $name;
Zach Copley's avatar
Zach Copley committed
454
        $detail->value_index = $index;
455 456 457

        $result = $detail->find(true);

458 459
        if (!$result instanceof Profile_detail) {
            $detail->value_index = $index;
Zach Copley's avatar
Zach Copley committed
460
            $detail->rel         = $rel;
461
            $detail->field_value = $value;
462
            $detail->date        = $date;
Zach Copley's avatar
Zach Copley committed
463
            $detail->created     = common_sql_now();
464
            $result = $detail->insert();
465
            if ($result === false) {
466
                common_log_db_error($detail, 'INSERT', __FILE__);
467
                // TRANS: Server error displayed when a field could not be saved in the database.
468
                throw new ServerException(_m('Could not save profile details.'));
469
            }
470 471
        } else {
            $orig = clone($detail);
Zach Copley's avatar
Zach Copley committed
472

473
            $detail->field_value = $value;
Zach Copley's avatar
Zach Copley committed
474
            $detail->rel         = $rel;
475
            $detail->date        = $date;
476

Zach Copley's avatar
Zach Copley committed
477
            $result = $detail->update($orig);
478
            if ($result === false) {
Zach Copley's avatar
Zach Copley committed
479
                common_log_db_error($detail, 'UPDATE', __FILE__);
480
                // TRANS: Server error displayed when a field could not be saved in the database.
481
                throw new ServerException(_m('Could not save profile details.'));
Zach Copley's avatar
Zach Copley committed
482
            }
483 484 485 486 487
        }

        $detail->free();
    }

488
    function removeAll($name)
489 490
    {
        $detail  = new Profile_detail();
491
        $detail->profile_id  = $this->scoped->getID();
492 493 494 495 496
        $detail->field_name  = $name;
        $detail->delete();
        $detail->free();
    }

497 498 499 500 501 502
    /**
     * Save fields that should be stored in the main profile object
     *
     * XXX: There's a lot of dupe code here from ProfileSettingsAction.
     *      Do not want.
     */
503
    function saveStandardProfileDetails()
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
    {
        $fullname  = $this->trimmed('extprofile-fullname');
        $location  = $this->trimmed('extprofile-location');
        $tagstring = $this->trimmed('extprofile-tags');
        $bio       = $this->trimmed('extprofile-bio');

        if ($tagstring) {
            $tags = array_map(
                'common_canonical_tag',
                preg_split('/[\s,]+/', $tagstring)
            );
        } else {
            $tags = array();
        }

        foreach ($tags as $tag) {
            if (!common_valid_profile_tag($tag)) {
                // TRANS: Validation error in form for profile settings.
                // TRANS: %s is an invalid tag.
                throw new Exception(sprintf(_m('Invalid tag: "%s".'), $tag));
            }
        }

527
        $oldTags = Profile_tag::getSelfTagsArray($this->scoped);
528 529
        $newTags = array_diff($tags, $oldTags);

530 531
        if ($fullname    != $this->scoped->getFullname()
            || $location != $this->scoped->location
532
            || !empty($newTags)
533
            || $bio      != $this->scoped->getDescription()) {
Zach Copley's avatar
Zach Copley committed
534

535
            $orig = clone($this->scoped);
536

537 538 539 540 541 542
            // Skipping nickname change here until we add logic for when the site allows it or not
            // old Profilesettings will still let us do that.

            $this->scoped->fullname = $fullname;
            $this->scoped->bio      = $bio;
            $this->scoped->location = $location;
543 544 545 546

            $loc = Location::fromName($location);

            if (empty($loc)) {
547 548 549 550
                $this->scoped->lat         = null;
                $this->scoped->lon         = null;
                $this->scoped->location_id = null;
                $this->scoped->location_ns = null;
551
            } else {
552 553 554 555
                $this->scoped->lat         = $loc->lat;
                $this->scoped->lon         = $loc->lon;
                $this->scoped->location_id = $loc->location_id;
                $this->scoped->location_ns = $loc->location_ns;
556 557
            }

558
            $result = $this->scoped->update($orig);
559 560

            if ($result === false) {
561
                common_log_db_error($this->scoped, 'UPDATE', __FILE__);
562
                // TRANS: Server error thrown when user profile settings could not be saved.
563
                throw new ServerException(_m('Could not save profile.'));
564 565 566
            }

            // Set the user tags
567
            $result = Profile_tag::setSelfTags($this->scoped, $tags);
568 569 570 571 572

            Event::handle('EndProfileSaveForm', array($this));
        }
    }

573
}